blob: 30d3b49d9d7fc9a8ae6333d0c1504282f50d649c [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Teresa Johnson63ee0e72018-06-26 13:56:49 +000074 return ParseTopLevelEntities() || ValidateEndOfModule() ||
75 ValidateEndOfIndex();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000123 if (!M)
124 return false;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000125 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000126 for (const auto &RAG : ForwardRefAttrGroups) {
127 Value *V = RAG.first;
128 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000129 AttrBuilder B;
130
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000131 for (const auto &Attr : Attrs)
132 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000133
134 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000135 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000136 AttrBuilder FnAttrs(AS.getFnAttributes());
137 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000138
139 FnAttrs.merge(B);
140
141 // If the alignment was parsed as an attribute, move to the alignment
142 // field.
143 if (FnAttrs.hasAlignmentAttr()) {
144 Fn->setAlignment(FnAttrs.getAlignment());
145 FnAttrs.removeAttribute(Attribute::Alignment);
146 }
147
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000148 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
149 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000153 AttrBuilder FnAttrs(AS.getFnAttributes());
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000155 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000156 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
157 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000160 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000163 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000164 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
165 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000166 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000167 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
168 AttrBuilder Attrs(GV->getAttributes());
169 Attrs.merge(B);
170 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000181
David Majnemer19b51052015-02-11 07:43:56 +0000182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000192
David Majnemerdad0a642014-06-27 18:19:56 +0000193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
197
Chris Lattnerac161bf2009-01-02 07:01:27 +0000198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000207
Devang Pateld2541152009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Pateld2541152009-07-08 19:23:54 +0000218
Mehdi Aminie4709272016-09-14 22:29:59 +0000219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000230
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
239 }
240 }
241
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000242 if (UpgradeDebugInfo)
243 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000244
Manman Renb5d7ff42016-05-25 23:14:48 +0000245 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000246 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000247
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000248 if (!Slots)
249 return false;
250 // Initialize the slot mapping.
251 // Because by this point we've parsed and validated everything, we can "steal"
252 // the mapping from LLParser as it doesn't need it anymore.
253 Slots->GlobalValues = std::move(NumberedVals);
254 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000255 for (const auto &I : NamedTypes)
256 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
257 for (const auto &I : NumberedTypes)
258 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000259
Chris Lattnerac161bf2009-01-02 07:01:27 +0000260 return false;
261}
262
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000263/// Do final validity and sanity checks at the end of the index.
264bool LLParser::ValidateEndOfIndex() {
265 if (!Index)
266 return false;
267
268 if (!ForwardRefValueInfos.empty())
269 return Error(ForwardRefValueInfos.begin()->second.front().second,
270 "use of undefined summary '^" +
271 Twine(ForwardRefValueInfos.begin()->first) + "'");
272
273 if (!ForwardRefAliasees.empty())
274 return Error(ForwardRefAliasees.begin()->second.front().second,
275 "use of undefined summary '^" +
276 Twine(ForwardRefAliasees.begin()->first) + "'");
277
278 if (!ForwardRefTypeIds.empty())
279 return Error(ForwardRefTypeIds.begin()->second.front().second,
280 "use of undefined type id summary '^" +
281 Twine(ForwardRefTypeIds.begin()->first) + "'");
282
283 return false;
284}
285
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286//===----------------------------------------------------------------------===//
287// Top-Level Entities
288//===----------------------------------------------------------------------===//
289
290bool LLParser::ParseTopLevelEntities() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000291 // If there is no Module, then parse just the summary index entries.
292 if (!M) {
293 while (true) {
294 switch (Lex.getKind()) {
295 case lltok::Eof:
296 return false;
297 case lltok::SummaryID:
298 if (ParseSummaryEntry())
299 return true;
300 break;
301 case lltok::kw_source_filename:
302 if (ParseSourceFileName())
303 return true;
304 break;
305 default:
306 // Skip everything else
307 Lex.Lex();
308 }
309 }
310 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000311 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000312 switch (Lex.getKind()) {
313 default: return TokError("expected top-level entity");
314 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000315 case lltok::kw_declare: if (ParseDeclare()) return true; break;
316 case lltok::kw_define: if (ParseDefine()) return true; break;
317 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
318 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000319 case lltok::kw_source_filename:
320 if (ParseSourceFileName())
321 return true;
322 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000323 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000324 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000326 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000328 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000329 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000330 case lltok::SummaryID:
331 if (ParseSummaryEntry())
332 return true;
333 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000334 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000335 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000336 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
337 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000338 if (ParseUseListOrderBB())
339 return true;
340 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 }
342 }
343}
344
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= 'module' 'asm' STRINGCONSTANT
347bool LLParser::ParseModuleAsm() {
348 assert(Lex.getKind() == lltok::kw_module);
349 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000350
351 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
353 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000354
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000355 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000356 return false;
357}
358
359/// toplevelentity
360/// ::= 'target' 'triple' '=' STRINGCONSTANT
361/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
362bool LLParser::ParseTargetDefinition() {
363 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000364 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000365 switch (Lex.Lex()) {
366 default: return TokError("unknown target property");
367 case lltok::kw_triple:
368 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000369 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
370 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000371 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000372 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373 return false;
374 case lltok::kw_datalayout:
375 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000376 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
377 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000379 if (DataLayoutStr.empty())
380 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381 return false;
382 }
383}
384
Bill Wendling706d3d62012-11-28 08:41:48 +0000385/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000386/// ::= 'source_filename' '=' STRINGCONSTANT
387bool LLParser::ParseSourceFileName() {
388 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000389 Lex.Lex();
390 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000391 ParseStringConstant(SourceFileName))
Teresa Johnson83c517c2016-03-30 18:15:08 +0000392 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000393 if (M)
394 M->setSourceFileName(SourceFileName);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000395 return false;
396}
397
398/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000399/// ::= 'deplibs' '=' '[' ']'
400/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
401/// FIXME: Remove in 4.0. Currently parse, but ignore.
402bool LLParser::ParseDepLibs() {
403 assert(Lex.getKind() == lltok::kw_deplibs);
404 Lex.Lex();
405 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
406 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
407 return true;
408
409 if (EatIfPresent(lltok::rsquare))
410 return false;
411
412 do {
413 std::string Str;
414 if (ParseStringConstant(Str)) return true;
415 } while (EatIfPresent(lltok::comma));
416
417 return ParseToken(lltok::rsquare, "expected ']' at end of list");
418}
419
Dan Gohman466876b2009-08-12 23:32:33 +0000420/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000421/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000423 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000425 Lex.Lex(); // eat LocalVarID;
426
427 if (ParseToken(lltok::equal, "expected '=' after name") ||
428 ParseToken(lltok::kw_type, "expected 'type' after '='"))
429 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000430
Craig Topper2617dcc2014-04-15 06:32:26 +0000431 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000432 if (ParseStructDefinition(TypeLoc, "",
433 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000434
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000435 if (!isa<StructType>(Result)) {
436 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
437 if (Entry.first)
438 return Error(TypeLoc, "non-struct types may not be recursive");
439 Entry.first = Result;
440 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000442
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 return false;
444}
445
446/// toplevelentity
447/// ::= LocalVar '=' 'type' type
448bool LLParser::ParseNamedType() {
449 std::string Name = Lex.getStrVal();
450 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000451 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000452
Chris Lattner3822f632009-01-02 08:05:26 +0000453 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000454 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000455 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000456
Craig Topper2617dcc2014-04-15 06:32:26 +0000457 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000458 if (ParseStructDefinition(NameLoc, Name,
459 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 if (!isa<StructType>(Result)) {
462 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
463 if (Entry.first)
464 return Error(NameLoc, "non-struct types may not be recursive");
465 Entry.first = Result;
466 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000469 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470}
471
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472/// toplevelentity
473/// ::= 'declare' FunctionHeader
474bool LLParser::ParseDeclare() {
475 assert(Lex.getKind() == lltok::kw_declare);
476 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000477
Peter Collingbourne21521892016-06-21 23:42:48 +0000478 std::vector<std::pair<unsigned, MDNode *>> MDs;
479 while (Lex.getKind() == lltok::MetadataVar) {
480 unsigned MDK;
481 MDNode *N;
482 if (ParseMetadataAttachment(MDK, N))
483 return true;
484 MDs.push_back({MDK, N});
485 }
486
Chris Lattnerac161bf2009-01-02 07:01:27 +0000487 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000488 if (ParseFunctionHeader(F, false))
489 return true;
490 for (auto &MD : MDs)
491 F->addMetadata(MD.first, *MD.second);
492 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000493}
494
495/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000496/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000497bool LLParser::ParseDefine() {
498 assert(Lex.getKind() == lltok::kw_define);
499 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerac161bf2009-01-02 07:01:27 +0000501 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000502 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000503 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000504 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000505}
506
Chris Lattner3822f632009-01-02 08:05:26 +0000507/// ParseGlobalType
508/// ::= 'constant'
509/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000510bool LLParser::ParseGlobalType(bool &IsConstant) {
511 if (Lex.getKind() == lltok::kw_constant)
512 IsConstant = true;
513 else if (Lex.getKind() == lltok::kw_global)
514 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000515 else {
516 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000517 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000518 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000519 Lex.Lex();
520 return false;
521}
522
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000523bool LLParser::ParseOptionalUnnamedAddr(
524 GlobalVariable::UnnamedAddr &UnnamedAddr) {
525 if (EatIfPresent(lltok::kw_unnamed_addr))
526 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
527 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
528 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
529 else
530 UnnamedAddr = GlobalValue::UnnamedAddr::None;
531 return false;
532}
533
Dan Gohman466876b2009-08-12 23:32:33 +0000534/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000535/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000536/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
537/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000538/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000539/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000540/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
541/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000542/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000543bool LLParser::ParseUnnamedGlobal() {
544 unsigned VarID = NumberedVals.size();
545 std::string Name;
546 LocTy NameLoc = Lex.getLoc();
547
548 // Handle the GlobalID form.
549 if (Lex.getKind() == lltok::GlobalID) {
550 if (Lex.getUIntVal() != VarID)
551 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000552 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000553 Lex.Lex(); // eat GlobalID;
554
555 if (ParseToken(lltok::equal, "expected '=' after name"))
556 return true;
557 }
558
559 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000560 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000561 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000562 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000563 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000564 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
565 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000566 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000567 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000568
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000569 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000570 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000571 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000572
573 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000574 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000575}
576
Chris Lattnerac161bf2009-01-02 07:01:27 +0000577/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000578/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000579/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
580/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000581/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000582bool LLParser::ParseNamedGlobal() {
583 assert(Lex.getKind() == lltok::GlobalVar);
584 LocTy NameLoc = Lex.getLoc();
585 std::string Name = Lex.getStrVal();
586 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000587
Chris Lattnerac161bf2009-01-02 07:01:27 +0000588 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000589 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000590 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000591 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000592 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000593 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000594 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
595 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000596 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000597 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000598
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000599 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000600 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000601 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000602
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000603 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000604 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000605}
606
David Majnemerdad0a642014-06-27 18:19:56 +0000607bool LLParser::parseComdat() {
608 assert(Lex.getKind() == lltok::ComdatVar);
609 std::string Name = Lex.getStrVal();
610 LocTy NameLoc = Lex.getLoc();
611 Lex.Lex();
612
613 if (ParseToken(lltok::equal, "expected '=' here"))
614 return true;
615
616 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
617 return TokError("expected comdat type");
618
619 Comdat::SelectionKind SK;
620 switch (Lex.getKind()) {
621 default:
622 return TokError("unknown selection kind");
623 case lltok::kw_any:
624 SK = Comdat::Any;
625 break;
626 case lltok::kw_exactmatch:
627 SK = Comdat::ExactMatch;
628 break;
629 case lltok::kw_largest:
630 SK = Comdat::Largest;
631 break;
632 case lltok::kw_noduplicates:
633 SK = Comdat::NoDuplicates;
634 break;
635 case lltok::kw_samesize:
636 SK = Comdat::SameSize;
637 break;
638 }
639 Lex.Lex();
640
641 // See if the comdat was forward referenced, if so, use the comdat.
642 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
643 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
644 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
645 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
646
647 Comdat *C;
648 if (I != ComdatSymTab.end())
649 C = &I->second;
650 else
651 C = M->getOrInsertComdat(Name);
652 C->setSelectionKind(SK);
653
654 return false;
655}
656
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000657// MDString:
658// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000659bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000660 std::string Str;
661 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000662 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000663 return false;
664}
665
666// MDNode:
667// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000668bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000669 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000670 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000671 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000672 if (ParseUInt32(MID))
673 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674
Chris Lattner8eff0152010-04-01 05:14:45 +0000675 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000676 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000677 Result = NumberedMetadata[MID];
678 return false;
679 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000680
Chris Lattner8eff0152010-04-01 05:14:45 +0000681 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000682 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000683 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000684
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000685 Result = FwdRef.first.get();
686 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000687 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000688}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000689
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000690/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000691/// !foo = !{ !1, !2 }
692bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000693 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000694 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000695 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000696
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000697 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000698 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000699 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000700 return true;
701
Dan Gohman2637cc12010-07-21 23:38:33 +0000702 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000703 if (Lex.getKind() != lltok::rbrace)
704 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000705 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000706 // Parse DIExpressions inline as a special case. They are still MDNodes,
707 // so they can still appear in named metadata. Remove this logic if they
708 // become plain Metadata.
709 if (Lex.getKind() == lltok::MetadataVar &&
710 Lex.getStrVal() == "DIExpression") {
711 if (ParseDIExpression(N, /*IsDistinct=*/false))
712 return true;
713 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
714 ParseMDNodeID(N)) {
715 return true;
716 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000717 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000718 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000719
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000720 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000721}
722
Devang Patel39e64d42009-07-01 19:21:12 +0000723/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000724/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000725bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000726 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000727 Lex.Lex();
728 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000729
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000730 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000731 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000732 ParseToken(lltok::equal, "expected '=' here"))
733 return true;
734
735 // Detect common error, from old metadata syntax.
736 if (Lex.getKind() == lltok::Type)
737 return TokError("unexpected type in metadata definition");
738
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000739 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000740 if (Lex.getKind() == lltok::MetadataVar) {
741 if (ParseSpecializedMDNode(Init, IsDistinct))
742 return true;
743 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
744 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000745 return true;
746
Chris Lattnerfc58af22009-12-30 04:51:58 +0000747 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000748 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000749 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000750 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000751 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000752
Chris Lattnerfc58af22009-12-30 04:51:58 +0000753 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
754 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000755 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000756 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000758 }
759
Devang Patel39e64d42009-07-01 19:21:12 +0000760 return false;
761}
762
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000763// Skips a single module summary entry.
764bool LLParser::SkipModuleSummaryEntry() {
765 // Each module summary entry consists of a tag for the entry
766 // type, followed by a colon, then the fields surrounded by nested sets of
767 // parentheses. The "tag:" looks like a Label. Once parsing support is
768 // in place we will look for the tokens corresponding to the expected tags.
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000769 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
770 Lex.getKind() != lltok::kw_typeid)
771 return TokError(
772 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
773 Lex.Lex();
774 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000775 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
776 return true;
777 // Now walk through the parenthesized entry, until the number of open
778 // parentheses goes back down to 0 (the first '(' was parsed above).
779 unsigned NumOpenParen = 1;
780 do {
781 switch (Lex.getKind()) {
782 case lltok::lparen:
783 NumOpenParen++;
784 break;
785 case lltok::rparen:
786 NumOpenParen--;
787 break;
788 case lltok::Eof:
789 return TokError("found end of file while parsing summary entry");
790 default:
791 // Skip everything in between parentheses.
792 break;
793 }
794 Lex.Lex();
795 } while (NumOpenParen > 0);
796 return false;
797}
798
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000799/// SummaryEntry
800/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000801bool LLParser::ParseSummaryEntry() {
802 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000803 unsigned SummaryID = Lex.getUIntVal();
804
805 // For summary entries, colons should be treated as distinct tokens,
806 // not an indication of the end of a label token.
807 Lex.setIgnoreColonInIdentifiers(true);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000808
809 Lex.Lex();
810 if (ParseToken(lltok::equal, "expected '=' here"))
811 return true;
812
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000813 // If we don't have an index object, skip the summary entry.
814 if (!Index)
815 return SkipModuleSummaryEntry();
816
817 switch (Lex.getKind()) {
818 case lltok::kw_gv:
819 return ParseGVEntry(SummaryID);
820 case lltok::kw_module:
821 return ParseModuleEntry(SummaryID);
822 case lltok::kw_typeid:
823 return ParseTypeIdEntry(SummaryID);
824 break;
825 default:
826 return Error(Lex.getLoc(), "unexpected summary kind");
827 }
828 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000829 return false;
830}
831
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000832static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
833 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
834 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
835}
836
Rafael Espindolae4b02312018-01-11 22:15:05 +0000837// If there was an explicit dso_local, update GV. In the absence of an explicit
838// dso_local we keep the default value.
839static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
840 if (DSOLocal)
841 GV.setDSOLocal(true);
842}
843
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000844/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000845/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000846/// OptionalVisibility OptionalDLLStorageClass
847/// OptionalThreadLocal OptionalUnnamedAddr
848// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000849///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000850/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000851/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852///
Eric Christopher536f0a92015-05-28 23:07:39 +0000853/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000855bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
856 unsigned L, unsigned Visibility,
857 unsigned DLLStorageClass, bool DSOLocal,
858 GlobalVariable::ThreadLocalMode TLM,
859 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000860 bool IsAlias;
861 if (Lex.getKind() == lltok::kw_alias)
862 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000863 else if (Lex.getKind() == lltok::kw_ifunc)
864 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000865 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000866 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000867 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868
Rafael Espindola78527052013-10-06 15:10:43 +0000869 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
870
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000871 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000872 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000873
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000874 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000875 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000876 "symbol with local linkage must have default visibility");
877
David Blaikie2f408302015-09-11 03:22:04 +0000878 Type *Ty;
879 LocTy ExplicitTypeLoc = Lex.getLoc();
880 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000881 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000882 return true;
883
Rafael Espindola64c1e182014-06-03 02:41:57 +0000884 Constant *Aliasee;
885 LocTy AliaseeLoc = Lex.getLoc();
886 if (Lex.getKind() != lltok::kw_bitcast &&
887 Lex.getKind() != lltok::kw_getelementptr &&
888 Lex.getKind() != lltok::kw_addrspacecast &&
889 Lex.getKind() != lltok::kw_inttoptr) {
890 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000891 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000893 // The bitcast dest type is not present, it is implied by the dest type.
894 ValID ID;
895 if (ParseValID(ID))
896 return true;
897 if (ID.Kind != ValID::t_Constant)
898 return Error(AliaseeLoc, "invalid aliasee");
899 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000901
Rafael Espindola64c1e182014-06-03 02:41:57 +0000902 Type *AliaseeType = Aliasee->getType();
903 auto *PTy = dyn_cast<PointerType>(AliaseeType);
904 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000905 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000906 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000908 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000909 return Error(
910 ExplicitTypeLoc,
911 "explicit pointee type doesn't match operand's pointee type");
912
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000913 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
914 return Error(
915 ExplicitTypeLoc,
916 "explicit pointee type should be a function type");
917
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000918 GlobalValue *GVal = nullptr;
919
920 // See if the alias was forward referenced, if so, prepare to replace the
921 // forward reference.
922 if (!Name.empty()) {
923 GVal = M->getNamedValue(Name);
924 if (GVal) {
925 if (!ForwardRefVals.erase(Name))
926 return Error(NameLoc, "redefinition of global '@" + Name + "'");
927 }
928 } else {
929 auto I = ForwardRefValIDs.find(NumberedVals.size());
930 if (I != ForwardRefValIDs.end()) {
931 GVal = I->second.first;
932 ForwardRefValIDs.erase(I);
933 }
934 }
935
Chris Lattnerac161bf2009-01-02 07:01:27 +0000936 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000937 std::unique_ptr<GlobalIndirectSymbol> GA;
938 if (IsAlias)
939 GA.reset(GlobalAlias::create(Ty, AddrSpace,
940 (GlobalValue::LinkageTypes)Linkage, Name,
941 Aliasee, /*Parent*/ nullptr));
942 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000943 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
944 (GlobalValue::LinkageTypes)Linkage, Name,
945 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000946 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000947 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000948 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000949 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000950 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Rafael Espindola54fc2982015-06-17 17:53:31 +0000952 if (Name.empty())
953 NumberedVals.push_back(GA.get());
954
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000955 if (GVal) {
956 // Verify that types agree.
957 if (GVal->getType() != GA->getType())
958 return Error(
959 ExplicitTypeLoc,
960 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattnerac161bf2009-01-02 07:01:27 +0000962 // If they agree, just RAUW the old value with the alias and remove the
963 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000964 GVal->replaceAllUsesWith(GA.get());
965 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000967
Chris Lattnerac161bf2009-01-02 07:01:27 +0000968 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000969 if (IsAlias)
970 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
971 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000972 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000973 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000974
Rafael Espindolaaa273822014-05-09 21:49:17 +0000975 // The module owns this now
976 GA.release();
977
Chris Lattnerac161bf2009-01-02 07:01:27 +0000978 return false;
979}
980
981/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000982/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
983/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000984/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000985/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000986/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
987/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
988/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
989/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000990///
Eric Christopher536f0a92015-05-28 23:07:39 +0000991/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000992/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000993///
994bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
995 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000996 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000997 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000998 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000999 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1000 return Error(NameLoc,
1001 "symbol with local linkage must have default visibility");
1002
Chris Lattnerac161bf2009-01-02 07:01:27 +00001003 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001004 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001005 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001007
Craig Topper2617dcc2014-04-15 06:32:26 +00001008 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001009 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001010 ParseOptionalToken(lltok::kw_externally_initialized,
1011 IsExternallyInitialized,
1012 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 ParseGlobalType(IsConstant) ||
1014 ParseType(Ty, TyLoc))
1015 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001016
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 // If the linkage is specified and is external, then no initializer is
1018 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001019 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001020 if (!HasLinkage ||
1021 !GlobalValue::isValidDeclarationLinkage(
1022 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001023 if (ParseGlobalValue(Ty, Init))
1024 return true;
1025 }
1026
David Majnemer49b3d9b2015-02-16 08:41:08 +00001027 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001028 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
David Majnemer598bd052014-12-09 05:56:09 +00001030 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001031
1032 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001033 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001034 GVal = M->getNamedValue(Name);
1035 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001036 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001037 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001038 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001039 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001040 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001042 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 ForwardRefValIDs.erase(I);
1044 }
1045 }
1046
David Majnemer598bd052014-12-09 05:56:09 +00001047 GlobalVariable *GV;
1048 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1050 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001051 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001052 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001053 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 return Error(TyLoc,
1055 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
David Majnemer598bd052014-12-09 05:56:09 +00001057 GV = cast<GlobalVariable>(GVal);
1058
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 // Move the forward-reference to the correct spot in the module.
1060 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1061 }
1062
1063 if (Name.empty())
1064 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001065
Chris Lattnerac161bf2009-01-02 07:01:27 +00001066 // Set the parsed properties on the global.
1067 if (Init)
1068 GV->setInitializer(Init);
1069 GV->setConstant(IsConstant);
1070 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001071 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001072 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001073 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001074 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001075 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001076 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 // Parse attributes on the global.
1079 while (Lex.getKind() == lltok::comma) {
1080 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001081
Chris Lattnerac161bf2009-01-02 07:01:27 +00001082 if (Lex.getKind() == lltok::kw_section) {
1083 Lex.Lex();
1084 GV->setSection(Lex.getStrVal());
1085 if (ParseToken(lltok::StringConstant, "expected global section string"))
1086 return true;
1087 } else if (Lex.getKind() == lltok::kw_align) {
1088 unsigned Alignment;
1089 if (ParseOptionalAlignment(Alignment)) return true;
1090 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001091 } else if (Lex.getKind() == lltok::MetadataVar) {
1092 if (ParseGlobalObjectMetadataAttachment(*GV))
1093 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001094 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001095 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001096 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001097 return true;
1098 if (C)
1099 GV->setComdat(C);
1100 else
1101 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 }
1103 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001104
Javed Absarf3d79042017-05-11 12:28:08 +00001105 AttrBuilder Attrs;
1106 LocTy BuiltinLoc;
1107 std::vector<unsigned> FwdRefAttrGrps;
1108 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1109 return true;
1110 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1111 GV->setAttributes(AttributeSet::get(Context, Attrs));
1112 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1113 }
1114
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115 return false;
1116}
1117
Bill Wendling63b88192013-02-06 06:52:58 +00001118/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001119/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001120bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001121 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001122 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001123 Lex.Lex();
1124
David Majnemerb39e22b2014-12-09 18:33:57 +00001125 if (Lex.getKind() != lltok::AttrGrpID)
1126 return TokError("expected attribute group id");
1127
Bill Wendling63b88192013-02-06 06:52:58 +00001128 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001129 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001130 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001131 Lex.Lex();
1132
1133 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001134 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001135 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001136 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001137 ParseToken(lltok::rbrace, "expected end of attribute group"))
1138 return true;
1139
Bill Wendlingb32b0412013-02-08 06:32:06 +00001140 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001141 return Error(AttrGrpLoc, "attribute group has no attributes");
1142
1143 return false;
1144}
1145
Bill Wendling8b0321d2013-02-08 00:52:31 +00001146/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001147/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001148bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1149 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001150 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001151 bool HaveError = false;
1152
1153 B.clear();
1154
Bill Wendling63b88192013-02-06 06:52:58 +00001155 while (true) {
1156 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001157 if (Token == lltok::kw_builtin)
1158 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001159 switch (Token) {
1160 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001161 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001162 return Error(Lex.getLoc(), "unterminated attribute group");
1163 case lltok::rbrace:
1164 // Finished.
1165 return false;
1166
Bill Wendlingb32b0412013-02-08 06:32:06 +00001167 case lltok::AttrGrpID: {
1168 // Allow a function to reference an attribute group:
1169 //
1170 // define void @foo() #1 { ... }
1171 if (inAttrGrp)
1172 HaveError |=
1173 Error(Lex.getLoc(),
1174 "cannot have an attribute group reference in an attribute group");
1175
1176 unsigned AttrGrpNum = Lex.getUIntVal();
1177 if (inAttrGrp) break;
1178
1179 // Save the reference to the attribute group. We'll fill it in later.
1180 FwdRefAttrGrps.push_back(AttrGrpNum);
1181 break;
1182 }
Bill Wendling63b88192013-02-06 06:52:58 +00001183 // Target-dependent attributes:
1184 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001185 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001186 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001187 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001188 }
1189
1190 // Target-independent attributes:
1191 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001192 // As a hack, we allow function alignment to be initially parsed as an
1193 // attribute on a function declaration/definition or added to an attribute
1194 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001195 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001196 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001197 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001198 if (ParseToken(lltok::equal, "expected '=' here") ||
1199 ParseUInt32(Alignment))
1200 return true;
1201 } else {
1202 if (ParseOptionalAlignment(Alignment))
1203 return true;
1204 }
Bill Wendling63b88192013-02-06 06:52:58 +00001205 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001206 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001207 }
1208 case lltok::kw_alignstack: {
1209 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001210 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001211 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001212 if (ParseToken(lltok::equal, "expected '=' here") ||
1213 ParseUInt32(Alignment))
1214 return true;
1215 } else {
1216 if (ParseOptionalStackAlignment(Alignment))
1217 return true;
1218 }
Bill Wendling63b88192013-02-06 06:52:58 +00001219 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001220 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001221 }
George Burgess IV278199f2016-04-12 01:05:35 +00001222 case lltok::kw_allocsize: {
1223 unsigned ElemSizeArg;
1224 Optional<unsigned> NumElemsArg;
1225 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1226 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1227 return true;
1228 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1229 continue;
1230 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001231 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1232 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1233 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1234 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1235 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001236 case lltok::kw_inaccessiblememonly:
1237 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1238 case lltok::kw_inaccessiblemem_or_argmemonly:
1239 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001240 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1241 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1242 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1243 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1244 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1245 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1246 case lltok::kw_noimplicitfloat:
1247 B.addAttribute(Attribute::NoImplicitFloat); break;
1248 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1249 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1250 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1251 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001252 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001253 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001254 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001255 case lltok::kw_optforfuzzing:
1256 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001257 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1258 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1259 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1260 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1261 case lltok::kw_returns_twice:
1262 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001263 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001264 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1265 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1266 case lltok::kw_sspstrong:
1267 B.addAttribute(Attribute::StackProtectStrong); break;
1268 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001269 case lltok::kw_shadowcallstack:
1270 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001271 case lltok::kw_sanitize_address:
1272 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001273 case lltok::kw_sanitize_hwaddress:
1274 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001275 case lltok::kw_sanitize_thread:
1276 B.addAttribute(Attribute::SanitizeThread); break;
1277 case lltok::kw_sanitize_memory:
1278 B.addAttribute(Attribute::SanitizeMemory); break;
Chandler Carruth664aa862018-09-04 12:38:00 +00001279 case lltok::kw_speculative_load_hardening:
1280 B.addAttribute(Attribute::SpeculativeLoadHardening);
1281 break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001282 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001283 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001284 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001285
1286 // Error handling.
1287 case lltok::kw_inreg:
1288 case lltok::kw_signext:
1289 case lltok::kw_zeroext:
1290 HaveError |=
1291 Error(Lex.getLoc(),
1292 "invalid use of attribute on a function");
1293 break;
1294 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001295 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001296 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001297 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001298 case lltok::kw_nest:
1299 case lltok::kw_noalias:
1300 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001301 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001302 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001303 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001304 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001305 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001306 HaveError |=
1307 Error(Lex.getLoc(),
1308 "invalid use of parameter-only attribute on a function");
1309 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001310 }
1311
1312 Lex.Lex();
1313 }
1314}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001315
1316//===----------------------------------------------------------------------===//
1317// GlobalValue Reference/Resolution Routines.
1318//===----------------------------------------------------------------------===//
1319
Karl Schimpf77729782015-09-03 18:06:44 +00001320static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1321 const std::string &Name) {
1322 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001323 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1324 PTy->getAddressSpace(), Name, M);
Karl Schimpf77729782015-09-03 18:06:44 +00001325 else
1326 return new GlobalVariable(*M, PTy->getElementType(), false,
1327 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1328 nullptr, GlobalVariable::NotThreadLocal,
1329 PTy->getAddressSpace());
1330}
1331
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001332Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1333 Value *Val, bool IsCall) {
1334 if (Val->getType() == Ty)
1335 return Val;
1336 // For calls we also accept variables in the program address space.
1337 Type *SuggestedTy = Ty;
1338 if (IsCall && isa<PointerType>(Ty)) {
1339 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1340 M->getDataLayout().getProgramAddressSpace());
1341 SuggestedTy = TyInProgAS;
1342 if (Val->getType() == TyInProgAS)
1343 return Val;
1344 }
1345 if (Ty->isLabelTy())
1346 Error(Loc, "'" + Name + "' is not a basic block");
1347 else
1348 Error(Loc, "'" + Name + "' defined with type '" +
1349 getTypeString(Val->getType()) + "' but expected '" +
1350 getTypeString(SuggestedTy) + "'");
1351 return nullptr;
1352}
1353
Chris Lattnerac161bf2009-01-02 07:01:27 +00001354/// GetGlobalVal - Get a value with the specified name or ID, creating a
1355/// forward reference record if needed. This can return null if the value
1356/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001357GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001358 LocTy Loc, bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001359 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001360 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001362 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001364
Chris Lattnerac161bf2009-01-02 07:01:27 +00001365 // Look this name up in the normal function symbol table.
1366 GlobalValue *Val =
1367 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001368
Chris Lattnerac161bf2009-01-02 07:01:27 +00001369 // If this is a forward reference for the value, see if we already created a
1370 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001371 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001372 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001373 if (I != ForwardRefVals.end())
1374 Val = I->second.first;
1375 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001376
Chris Lattnerac161bf2009-01-02 07:01:27 +00001377 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001378 if (Val)
1379 return cast_or_null<GlobalValue>(
1380 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001381
Chris Lattnerac161bf2009-01-02 07:01:27 +00001382 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001383 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1385 return FwdVal;
1386}
1387
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001388GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1389 bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001390 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001391 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001393 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001394 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001395
Craig Topper2617dcc2014-04-15 06:32:26 +00001396 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001397
Chris Lattnerac161bf2009-01-02 07:01:27 +00001398 // If this is a forward reference for the value, see if we already created a
1399 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001400 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001401 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001402 if (I != ForwardRefValIDs.end())
1403 Val = I->second.first;
1404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001405
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001407 if (Val)
1408 return cast_or_null<GlobalValue>(
1409 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001410
Chris Lattnerac161bf2009-01-02 07:01:27 +00001411 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001412 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001413 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1414 return FwdVal;
1415}
1416
Chris Lattnerac161bf2009-01-02 07:01:27 +00001417//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001418// Comdat Reference/Resolution Routines.
1419//===----------------------------------------------------------------------===//
1420
1421Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1422 // Look this name up in the comdat symbol table.
1423 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1424 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1425 if (I != ComdatSymTab.end())
1426 return &I->second;
1427
1428 // Otherwise, create a new forward reference for this value and remember it.
1429 Comdat *C = M->getOrInsertComdat(Name);
1430 ForwardRefComdats[Name] = Loc;
1431 return C;
1432}
1433
David Majnemerdad0a642014-06-27 18:19:56 +00001434//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001435// Helper Routines.
1436//===----------------------------------------------------------------------===//
1437
1438/// ParseToken - If the current token has the specified kind, eat it and return
1439/// success. Otherwise, emit the specified error and return failure.
1440bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1441 if (Lex.getKind() != T)
1442 return TokError(ErrMsg);
1443 Lex.Lex();
1444 return false;
1445}
1446
Chris Lattner3822f632009-01-02 08:05:26 +00001447/// ParseStringConstant
1448/// ::= StringConstant
1449bool LLParser::ParseStringConstant(std::string &Result) {
1450 if (Lex.getKind() != lltok::StringConstant)
1451 return TokError("expected string constant");
1452 Result = Lex.getStrVal();
1453 Lex.Lex();
1454 return false;
1455}
1456
1457/// ParseUInt32
1458/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001459bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001460 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1461 return TokError("expected integer");
1462 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1463 if (Val64 != unsigned(Val64))
1464 return TokError("expected 32-bit integer (too large)");
1465 Val = Val64;
1466 Lex.Lex();
1467 return false;
1468}
1469
Hal Finkelb0407ba2014-07-18 15:51:28 +00001470/// ParseUInt64
1471/// ::= uint64
1472bool LLParser::ParseUInt64(uint64_t &Val) {
1473 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1474 return TokError("expected integer");
1475 Val = Lex.getAPSIntVal().getLimitedValue();
1476 Lex.Lex();
1477 return false;
1478}
1479
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001480/// ParseTLSModel
1481/// := 'localdynamic'
1482/// := 'initialexec'
1483/// := 'localexec'
1484bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1485 switch (Lex.getKind()) {
1486 default:
1487 return TokError("expected localdynamic, initialexec or localexec");
1488 case lltok::kw_localdynamic:
1489 TLM = GlobalVariable::LocalDynamicTLSModel;
1490 break;
1491 case lltok::kw_initialexec:
1492 TLM = GlobalVariable::InitialExecTLSModel;
1493 break;
1494 case lltok::kw_localexec:
1495 TLM = GlobalVariable::LocalExecTLSModel;
1496 break;
1497 }
1498
1499 Lex.Lex();
1500 return false;
1501}
1502
1503/// ParseOptionalThreadLocal
1504/// := /*empty*/
1505/// := 'thread_local'
1506/// := 'thread_local' '(' tlsmodel ')'
1507bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1508 TLM = GlobalVariable::NotThreadLocal;
1509 if (!EatIfPresent(lltok::kw_thread_local))
1510 return false;
1511
1512 TLM = GlobalVariable::GeneralDynamicTLSModel;
1513 if (Lex.getKind() == lltok::lparen) {
1514 Lex.Lex();
1515 return ParseTLSModel(TLM) ||
1516 ParseToken(lltok::rparen, "expected ')' after thread local model");
1517 }
1518 return false;
1519}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001520
1521/// ParseOptionalAddrSpace
1522/// := /*empty*/
1523/// := 'addrspace' '(' uint32 ')'
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001524bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1525 AddrSpace = DefaultAS;
Chris Lattner3822f632009-01-02 08:05:26 +00001526 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001527 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001528 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001529 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001530 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001531}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001532
Artur Pilipenko17376c42015-08-03 14:31:49 +00001533/// ParseStringAttribute
1534/// := StringConstant
1535/// := StringConstant '=' StringConstant
1536bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1537 std::string Attr = Lex.getStrVal();
1538 Lex.Lex();
1539 std::string Val;
1540 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1541 return true;
1542 B.addAttribute(Attr, Val);
1543 return false;
1544}
1545
Bill Wendling34c2eb22012-12-04 23:40:58 +00001546/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1547bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1548 bool HaveError = false;
1549
1550 B.clear();
1551
Eugene Zelenko1804a772016-08-25 00:45:04 +00001552 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001553 lltok::Kind Token = Lex.getKind();
1554 switch (Token) {
1555 default: // End of attributes.
1556 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001557 case lltok::StringConstant: {
1558 if (ParseStringAttribute(B))
1559 return true;
1560 continue;
1561 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001562 case lltok::kw_align: {
1563 unsigned Alignment;
1564 if (ParseOptionalAlignment(Alignment))
1565 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001566 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001567 continue;
1568 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001569 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001570 case lltok::kw_dereferenceable: {
1571 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001572 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001573 return true;
1574 B.addDereferenceableAttr(Bytes);
1575 continue;
1576 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001577 case lltok::kw_dereferenceable_or_null: {
1578 uint64_t Bytes;
1579 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1580 return true;
1581 B.addDereferenceableOrNullAttr(Bytes);
1582 continue;
1583 }
Reid Klecknera534a382013-12-19 02:14:12 +00001584 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001585 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1586 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1587 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1588 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001589 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001590 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1591 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001592 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001593 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1594 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001595 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001596 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001597 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001598 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001599
Stephen Lin7577ed52013-04-20 13:16:13 +00001600 case lltok::kw_alignstack:
1601 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001602 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001603 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001604 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001605 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001606 case lltok::kw_minsize:
1607 case lltok::kw_naked:
1608 case lltok::kw_nobuiltin:
1609 case lltok::kw_noduplicate:
1610 case lltok::kw_noimplicitfloat:
1611 case lltok::kw_noinline:
1612 case lltok::kw_nonlazybind:
1613 case lltok::kw_noredzone:
1614 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001615 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001616 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001617 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001618 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001619 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001620 case lltok::kw_returns_twice:
1621 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001622 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001623 case lltok::kw_sanitize_memory:
1624 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001625 case lltok::kw_speculative_load_hardening:
Stephen Lin7577ed52013-04-20 13:16:13 +00001626 case lltok::kw_ssp:
1627 case lltok::kw_sspreq:
1628 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001629 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001630 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001631 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001632 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001633 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1634 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001635 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001636
Bill Wendling34c2eb22012-12-04 23:40:58 +00001637 Lex.Lex();
1638 }
1639}
1640
1641/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1642bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1643 bool HaveError = false;
1644
1645 B.clear();
1646
Eugene Zelenko1804a772016-08-25 00:45:04 +00001647 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001648 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001649 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001650 default: // End of attributes.
1651 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001652 case lltok::StringConstant: {
1653 if (ParseStringAttribute(B))
1654 return true;
1655 continue;
1656 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001657 case lltok::kw_dereferenceable: {
1658 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001659 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001660 return true;
1661 B.addDereferenceableAttr(Bytes);
1662 continue;
1663 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001664 case lltok::kw_dereferenceable_or_null: {
1665 uint64_t Bytes;
1666 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1667 return true;
1668 B.addDereferenceableOrNullAttr(Bytes);
1669 continue;
1670 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001671 case lltok::kw_align: {
1672 unsigned Alignment;
1673 if (ParseOptionalAlignment(Alignment))
1674 return true;
1675 B.addAlignmentAttr(Alignment);
1676 continue;
1677 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001678 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1679 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001680 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001681 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1682 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001683
Bill Wendling34c2eb22012-12-04 23:40:58 +00001684 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001685 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001686 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001687 case lltok::kw_nest:
1688 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001689 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001690 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001691 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001692 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001693 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001694 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001695
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001696 case lltok::kw_alignstack:
1697 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001698 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001699 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001700 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001701 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001702 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001703 case lltok::kw_minsize:
1704 case lltok::kw_naked:
1705 case lltok::kw_nobuiltin:
1706 case lltok::kw_noduplicate:
1707 case lltok::kw_noimplicitfloat:
1708 case lltok::kw_noinline:
1709 case lltok::kw_nonlazybind:
1710 case lltok::kw_noredzone:
1711 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001712 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001713 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001714 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001715 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001716 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001717 case lltok::kw_returns_twice:
1718 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001719 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001720 case lltok::kw_sanitize_memory:
1721 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001722 case lltok::kw_speculative_load_hardening:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001723 case lltok::kw_ssp:
1724 case lltok::kw_sspreq:
1725 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001726 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001727 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001728 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001729 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001730 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001731 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001732
1733 case lltok::kw_readnone:
1734 case lltok::kw_readonly:
1735 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001736 }
1737
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 Lex.Lex();
1739 }
1740}
1741
Rafael Espindolac6269912016-05-10 17:16:45 +00001742static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1743 HasLinkage = true;
1744 switch (Kind) {
1745 default:
1746 HasLinkage = false;
1747 return GlobalValue::ExternalLinkage;
1748 case lltok::kw_private:
1749 return GlobalValue::PrivateLinkage;
1750 case lltok::kw_internal:
1751 return GlobalValue::InternalLinkage;
1752 case lltok::kw_weak:
1753 return GlobalValue::WeakAnyLinkage;
1754 case lltok::kw_weak_odr:
1755 return GlobalValue::WeakODRLinkage;
1756 case lltok::kw_linkonce:
1757 return GlobalValue::LinkOnceAnyLinkage;
1758 case lltok::kw_linkonce_odr:
1759 return GlobalValue::LinkOnceODRLinkage;
1760 case lltok::kw_available_externally:
1761 return GlobalValue::AvailableExternallyLinkage;
1762 case lltok::kw_appending:
1763 return GlobalValue::AppendingLinkage;
1764 case lltok::kw_common:
1765 return GlobalValue::CommonLinkage;
1766 case lltok::kw_extern_weak:
1767 return GlobalValue::ExternalWeakLinkage;
1768 case lltok::kw_external:
1769 return GlobalValue::ExternalLinkage;
1770 }
1771}
1772
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773/// ParseOptionalLinkage
1774/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001775/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776/// ::= 'internal'
1777/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001778/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001779/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001780/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001781/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001783/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784/// ::= 'extern_weak'
1785/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001786bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1787 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001788 unsigned &DLLStorageClass,
1789 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001790 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1791 if (HasLinkage)
1792 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001793 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001794 ParseOptionalVisibility(Visibility);
1795 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001796
1797 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1798 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1799 }
1800
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 return false;
1802}
1803
Sean Fertilec70d28b2017-10-26 15:00:26 +00001804void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1805 switch (Lex.getKind()) {
1806 default:
1807 DSOLocal = false;
1808 break;
1809 case lltok::kw_dso_local:
1810 DSOLocal = true;
1811 Lex.Lex();
1812 break;
1813 case lltok::kw_dso_preemptable:
1814 DSOLocal = false;
1815 Lex.Lex();
1816 break;
1817 }
1818}
1819
Chris Lattnerac161bf2009-01-02 07:01:27 +00001820/// ParseOptionalVisibility
1821/// ::= /*empty*/
1822/// ::= 'default'
1823/// ::= 'hidden'
1824/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001825///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001826void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001828 default:
1829 Res = GlobalValue::DefaultVisibility;
1830 return;
1831 case lltok::kw_default:
1832 Res = GlobalValue::DefaultVisibility;
1833 break;
1834 case lltok::kw_hidden:
1835 Res = GlobalValue::HiddenVisibility;
1836 break;
1837 case lltok::kw_protected:
1838 Res = GlobalValue::ProtectedVisibility;
1839 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001840 }
1841 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842}
1843
Nico Rieck7157bb72014-01-14 15:22:47 +00001844/// ParseOptionalDLLStorageClass
1845/// ::= /*empty*/
1846/// ::= 'dllimport'
1847/// ::= 'dllexport'
1848///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001849void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001850 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001851 default:
1852 Res = GlobalValue::DefaultStorageClass;
1853 return;
1854 case lltok::kw_dllimport:
1855 Res = GlobalValue::DLLImportStorageClass;
1856 break;
1857 case lltok::kw_dllexport:
1858 Res = GlobalValue::DLLExportStorageClass;
1859 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001860 }
1861 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001862}
1863
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864/// ParseOptionalCallingConv
1865/// ::= /*empty*/
1866/// ::= 'ccc'
1867/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001868/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001869/// ::= 'coldcc'
1870/// ::= 'x86_stdcallcc'
1871/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001872/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001873/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001874/// ::= 'arm_apcscc'
1875/// ::= 'arm_aapcscc'
1876/// ::= 'arm_aapcs_vfpcc'
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001877/// ::= 'aarch64_vector_pcs'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001878/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001879/// ::= 'avr_intrcc'
1880/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001881/// ::= 'ptx_kernel'
1882/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001883/// ::= 'spir_func'
1884/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001885/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001886/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001887/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001888/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001889/// ::= 'preserve_mostcc'
1890/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001891/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001892/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001893/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001894/// ::= 'hhvmcc'
1895/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001896/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001897/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001898/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001899/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001900/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001901/// ::= 'amdgpu_gs'
1902/// ::= 'amdgpu_ps'
1903/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001904/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001906///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001907bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001908 switch (Lex.getKind()) {
1909 default: CC = CallingConv::C; return false;
1910 case lltok::kw_ccc: CC = CallingConv::C; break;
1911 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1912 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1913 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1914 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001915 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001916 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001917 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001918 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1919 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1920 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001921 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001922 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001923 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1924 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001925 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1926 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001927 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1928 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001929 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001930 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001931 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001932 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001933 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001934 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1935 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001936 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001937 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001938 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001939 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1940 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001941 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001942 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001943 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001944 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001945 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001946 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1947 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1948 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001949 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001950 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001951 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001952 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001953 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 Lex.Lex();
1957 return false;
1958}
1959
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001960/// ParseMetadataAttachment
1961/// ::= !dbg !42
1962bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1963 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1964
1965 std::string Name = Lex.getStrVal();
1966 Kind = M->getMDKindID(Name);
1967 Lex.Lex();
1968
1969 return ParseMDNode(MD);
1970}
1971
Chris Lattner5c427632009-12-30 05:31:19 +00001972/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001973/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001974bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001975 do {
1976 if (Lex.getKind() != lltok::MetadataVar)
1977 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001978
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001979 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001980 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001981 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001982 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001983
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001984 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001985 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001986 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001987
Chris Lattner596760d2009-12-29 21:25:40 +00001988 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001989 } while (EatIfPresent(lltok::comma));
1990 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001991}
1992
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001993/// ParseGlobalObjectMetadataAttachment
1994/// ::= !dbg !57
1995bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1996 unsigned MDK;
1997 MDNode *N;
1998 if (ParseMetadataAttachment(MDK, N))
1999 return true;
2000
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002001 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002002 return false;
2003}
2004
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002005/// ParseOptionalFunctionMetadata
2006/// ::= (!dbg !57)*
2007bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002008 while (Lex.getKind() == lltok::MetadataVar)
2009 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002010 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002011 return false;
2012}
2013
Chris Lattnerac161bf2009-01-02 07:01:27 +00002014/// ParseOptionalAlignment
2015/// ::= /* empty */
2016/// ::= 'align' 4
2017bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2018 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002019 if (!EatIfPresent(lltok::kw_align))
2020 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00002021 LocTy AlignLoc = Lex.getLoc();
2022 if (ParseUInt32(Alignment)) return true;
2023 if (!isPowerOf2_32(Alignment))
2024 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002025 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002026 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002027 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028}
2029
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002030/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002031/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002032/// ::= AttrKind '(' 4 ')'
2033///
2034/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2035bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2036 uint64_t &Bytes) {
2037 assert((AttrKind == lltok::kw_dereferenceable ||
2038 AttrKind == lltok::kw_dereferenceable_or_null) &&
2039 "contract!");
2040
Hal Finkelb0407ba2014-07-18 15:51:28 +00002041 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002042 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002043 return false;
2044 LocTy ParenLoc = Lex.getLoc();
2045 if (!EatIfPresent(lltok::lparen))
2046 return Error(ParenLoc, "expected '('");
2047 LocTy DerefLoc = Lex.getLoc();
2048 if (ParseUInt64(Bytes)) return true;
2049 ParenLoc = Lex.getLoc();
2050 if (!EatIfPresent(lltok::rparen))
2051 return Error(ParenLoc, "expected ')'");
2052 if (!Bytes)
2053 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2054 return false;
2055}
2056
Chris Lattnerb2f39502009-12-30 05:44:30 +00002057/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002058/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002059/// ::= ',' align 4
2060///
2061/// This returns with AteExtraComma set to true if it ate an excess comma at the
2062/// end.
2063bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2064 bool &AteExtraComma) {
2065 AteExtraComma = false;
2066 while (EatIfPresent(lltok::comma)) {
2067 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002068 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002069 AteExtraComma = true;
2070 return false;
2071 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002072
Chris Lattner95b0ff42010-04-23 00:50:50 +00002073 if (Lex.getKind() != lltok::kw_align)
2074 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002075
Chris Lattner95b0ff42010-04-23 00:50:50 +00002076 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002077 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002078
Devang Patelea8a4b92009-09-17 23:04:48 +00002079 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002080}
2081
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002082/// ParseOptionalCommaAddrSpace
2083/// ::=
2084/// ::= ',' addrspace(1)
2085///
2086/// This returns with AteExtraComma set to true if it ate an excess comma at the
2087/// end.
2088bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2089 LocTy &Loc,
2090 bool &AteExtraComma) {
2091 AteExtraComma = false;
2092 while (EatIfPresent(lltok::comma)) {
2093 // Metadata at the end is an early exit.
2094 if (Lex.getKind() == lltok::MetadataVar) {
2095 AteExtraComma = true;
2096 return false;
2097 }
2098
2099 Loc = Lex.getLoc();
2100 if (Lex.getKind() != lltok::kw_addrspace)
2101 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2102
2103 if (ParseOptionalAddrSpace(AddrSpace))
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
George Burgess IV278199f2016-04-12 01:05:35 +00002110bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2111 Optional<unsigned> &HowManyArg) {
2112 Lex.Lex();
2113
2114 auto StartParen = Lex.getLoc();
2115 if (!EatIfPresent(lltok::lparen))
2116 return Error(StartParen, "expected '('");
2117
2118 if (ParseUInt32(BaseSizeArg))
2119 return true;
2120
2121 if (EatIfPresent(lltok::comma)) {
2122 auto HowManyAt = Lex.getLoc();
2123 unsigned HowMany;
2124 if (ParseUInt32(HowMany))
2125 return true;
2126 if (HowMany == BaseSizeArg)
2127 return Error(HowManyAt,
2128 "'allocsize' indices can't refer to the same parameter");
2129 HowManyArg = HowMany;
2130 } else
2131 HowManyArg = None;
2132
2133 auto EndParen = Lex.getLoc();
2134 if (!EatIfPresent(lltok::rparen))
2135 return Error(EndParen, "expected ')'");
2136 return false;
2137}
2138
Eli Friedmanfee02c62011-07-25 23:16:38 +00002139/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002140/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002141/// else: ::=
2142///
2143/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002144bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002145 AtomicOrdering &Ordering) {
2146 if (!isAtomic)
2147 return false;
2148
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002149 return ParseScope(SSID) || ParseOrdering(Ordering);
2150}
Tim Northovere94a5182014-03-11 10:48:52 +00002151
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002152/// ParseScope
2153/// ::= syncscope("singlethread" | "<target scope>")?
2154///
2155/// This sets synchronization scope ID to the ID of the parsed value.
2156bool LLParser::ParseScope(SyncScope::ID &SSID) {
2157 SSID = SyncScope::System;
2158 if (EatIfPresent(lltok::kw_syncscope)) {
2159 auto StartParenAt = Lex.getLoc();
2160 if (!EatIfPresent(lltok::lparen))
2161 return Error(StartParenAt, "Expected '(' in syncscope");
2162
2163 std::string SSN;
2164 auto SSNAt = Lex.getLoc();
2165 if (ParseStringConstant(SSN))
2166 return Error(SSNAt, "Expected synchronization scope name");
2167
2168 auto EndParenAt = Lex.getLoc();
2169 if (!EatIfPresent(lltok::rparen))
2170 return Error(EndParenAt, "Expected ')' in syncscope");
2171
2172 SSID = Context.getOrInsertSyncScopeID(SSN);
2173 }
2174
2175 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002176}
2177
2178/// ParseOrdering
2179/// ::= AtomicOrdering
2180///
2181/// This sets Ordering to the parsed value.
2182bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002183 switch (Lex.getKind()) {
2184 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002185 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2186 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2187 // Not specified yet:
2188 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2189 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2190 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2191 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2192 case lltok::kw_seq_cst:
2193 Ordering = AtomicOrdering::SequentiallyConsistent;
2194 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002195 }
2196 Lex.Lex();
2197 return false;
2198}
2199
Charles Davisbe5557e2010-02-12 00:31:15 +00002200/// ParseOptionalStackAlignment
2201/// ::= /* empty */
2202/// ::= 'alignstack' '(' 4 ')'
2203bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2204 Alignment = 0;
2205 if (!EatIfPresent(lltok::kw_alignstack))
2206 return false;
2207 LocTy ParenLoc = Lex.getLoc();
2208 if (!EatIfPresent(lltok::lparen))
2209 return Error(ParenLoc, "expected '('");
2210 LocTy AlignLoc = Lex.getLoc();
2211 if (ParseUInt32(Alignment)) return true;
2212 ParenLoc = Lex.getLoc();
2213 if (!EatIfPresent(lltok::rparen))
2214 return Error(ParenLoc, "expected ')'");
2215 if (!isPowerOf2_32(Alignment))
2216 return Error(AlignLoc, "stack alignment is not a power of two");
2217 return false;
2218}
Devang Patelea8a4b92009-09-17 23:04:48 +00002219
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002220/// ParseIndexList - This parses the index list for an insert/extractvalue
2221/// instruction. This sets AteExtraComma in the case where we eat an extra
2222/// comma at the end of the line and find that it is followed by metadata.
2223/// Clients that don't allow metadata can call the version of this function that
2224/// only takes one argument.
2225///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226/// ParseIndexList
2227/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002228///
2229bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2230 bool &AteExtraComma) {
2231 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002232
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 if (Lex.getKind() != lltok::comma)
2234 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235
Chris Lattner3822f632009-01-02 08:05:26 +00002236 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002237 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002238 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002239 AteExtraComma = true;
2240 return false;
2241 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002242 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002243 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 Indices.push_back(Idx);
2245 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 return false;
2248}
2249
2250//===----------------------------------------------------------------------===//
2251// Type Parsing.
2252//===----------------------------------------------------------------------===//
2253
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002254/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002255bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002256 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002257 switch (Lex.getKind()) {
2258 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002259 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002260 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002261 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002266 // Type ::= StructType
2267 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 return true;
2269 break;
2270 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002271 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 Lex.Lex(); // eat the lsquare.
2273 if (ParseArrayVectorType(Result, false))
2274 return true;
2275 break;
2276 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002277 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002278 Lex.Lex();
2279 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002280 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002281 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002283 } else if (ParseArrayVectorType(Result, true))
2284 return true;
2285 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002286 case lltok::LocalVar: {
2287 // Type ::= %foo
2288 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002289
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002290 // If the type hasn't been defined yet, create a forward definition and
2291 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002292 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002293 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002294 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002296 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297 Lex.Lex();
2298 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002300
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301 case lltok::LocalVarID: {
2302 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 // If the type hasn't been defined yet, create a forward definition and
2306 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002307 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002308 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002309 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002311 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 Lex.Lex();
2313 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002314 }
2315 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002316
2317 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002318 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319 switch (Lex.getKind()) {
2320 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 default:
2322 if (!AllowVoid && Result->isVoidTy())
2323 return Error(TypeLoc, "void type only allowed for function results");
2324 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002325
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002328 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002330 if (Result->isVoidTy())
2331 return TokError("pointers to void are invalid - use i8* instead");
2332 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002333 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002334 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002335 Lex.Lex();
2336 break;
2337
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002339 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002340 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002343 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002344 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002345 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 unsigned AddrSpace;
2347 if (ParseOptionalAddrSpace(AddrSpace) ||
2348 ParseToken(lltok::star, "expected '*' in address space"))
2349 return true;
2350
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 break;
2353 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002354
Chris Lattnerac161bf2009-01-02 07:01:27 +00002355 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2356 case lltok::lparen:
2357 if (ParseFunctionType(Result))
2358 return true;
2359 break;
2360 }
2361 }
2362}
2363
2364/// ParseParameterList
2365/// ::= '(' ')'
2366/// ::= '(' Arg (',' Arg)* ')'
2367/// Arg
2368/// ::= Type OptionalAttributes Value OptionalAttributes
2369bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002370 PerFunctionState &PFS, bool IsMustTailCall,
2371 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 if (ParseToken(lltok::lparen, "expected '(' in call"))
2373 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002374
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375 while (Lex.getKind() != lltok::rparen) {
2376 // If this isn't the first argument, we need a comma.
2377 if (!ArgList.empty() &&
2378 ParseToken(lltok::comma, "expected ',' in argument list"))
2379 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002380
Reid Kleckner83498642014-08-26 00:33:28 +00002381 // Parse an ellipsis if this is a musttail call in a variadic function.
2382 if (Lex.getKind() == lltok::dotdotdot) {
2383 const char *Msg = "unexpected ellipsis in argument list for ";
2384 if (!IsMustTailCall)
2385 return TokError(Twine(Msg) + "non-musttail call");
2386 if (!InVarArgsFunc)
2387 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2388 Lex.Lex(); // Lex the '...', it is purely for readability.
2389 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2390 }
2391
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392 // Parse the argument.
2393 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002394 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002395 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002397 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002399
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002400 if (ArgTy->isMetadataTy()) {
2401 if (ParseMetadataAsValue(V, PFS))
2402 return true;
2403 } else {
2404 // Otherwise, handle normal operands.
2405 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2406 return true;
2407 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002408 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002409 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 }
2411
Reid Kleckner83498642014-08-26 00:33:28 +00002412 if (IsMustTailCall && InVarArgsFunc)
2413 return TokError("expected '...' at end of argument list for musttail call "
2414 "in varargs function");
2415
Chris Lattnerac161bf2009-01-02 07:01:27 +00002416 Lex.Lex(); // Lex the ')'.
2417 return false;
2418}
2419
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002420/// ParseOptionalOperandBundles
2421/// ::= /*empty*/
2422/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2423///
2424/// OperandBundle
2425/// ::= bundle-tag '(' ')'
2426/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2427///
2428/// bundle-tag ::= String Constant
2429bool LLParser::ParseOptionalOperandBundles(
2430 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2431 LocTy BeginLoc = Lex.getLoc();
2432 if (!EatIfPresent(lltok::lsquare))
2433 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002435 while (Lex.getKind() != lltok::rsquare) {
2436 // If this isn't the first operand bundle, we need a comma.
2437 if (!BundleList.empty() &&
2438 ParseToken(lltok::comma, "expected ',' in input list"))
2439 return true;
2440
2441 std::string Tag;
2442 if (ParseStringConstant(Tag))
2443 return true;
2444
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002445 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2446 return true;
2447
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002448 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002449 while (Lex.getKind() != lltok::rparen) {
2450 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002451 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002452 ParseToken(lltok::comma, "expected ',' in input list"))
2453 return true;
2454
2455 Type *Ty = nullptr;
2456 Value *Input = nullptr;
2457 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2458 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002459 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002460 }
2461
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002462 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2463
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002464 Lex.Lex(); // Lex the ')'.
2465 }
2466
2467 if (BundleList.empty())
2468 return Error(BeginLoc, "operand bundle set must not be empty");
2469
2470 Lex.Lex(); // Lex the ']'.
2471 return false;
2472}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002473
Chris Lattner2ed06b42009-01-05 18:34:07 +00002474/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002475/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476/// ::= '(' ArgTypeListI ')'
2477/// ArgTypeListI
2478/// ::= /*empty*/
2479/// ::= '...'
2480/// ::= ArgTypeList ',' '...'
2481/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002482///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002483bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2484 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 isVarArg = false;
2486 assert(Lex.getKind() == lltok::lparen);
2487 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 if (Lex.getKind() == lltok::rparen) {
2490 // empty
2491 } else if (Lex.getKind() == lltok::dotdotdot) {
2492 isVarArg = true;
2493 Lex.Lex();
2494 } else {
2495 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002496 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002497 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002500 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002501 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002502
Chris Lattnerfdd87902009-10-05 05:54:46 +00002503 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002504 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Chris Lattnerdef19492011-06-17 06:36:20 +00002506 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 Name = Lex.getStrVal();
2508 Lex.Lex();
2509 }
Chris Lattner3822f632009-01-02 08:05:26 +00002510
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002511 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002512 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002513
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002514 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002515 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002516 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002517
Chris Lattner3822f632009-01-02 08:05:26 +00002518 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002520 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002521 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 break;
2523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 // Otherwise must be an argument type.
2526 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002527 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002528
Chris Lattnerfdd87902009-10-05 05:54:46 +00002529 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002530 return Error(TypeLoc, "argument can not have void type");
2531
Chris Lattnerdef19492011-06-17 06:36:20 +00002532 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 Name = Lex.getStrVal();
2534 Lex.Lex();
2535 } else {
2536 Name = "";
2537 }
Chris Lattner3822f632009-01-02 08:05:26 +00002538
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002539 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002540 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002541
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002542 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002543 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002544 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 }
2546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002547
Chris Lattner3822f632009-01-02 08:05:26 +00002548 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002550
Chris Lattnerac161bf2009-01-02 07:01:27 +00002551/// ParseFunctionType
2552/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002553bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002554 assert(Lex.getKind() == lltok::lparen);
2555
Chris Lattnerce473c72009-01-05 08:04:33 +00002556 if (!FunctionType::isValidReturnType(Result))
2557 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002558
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002559 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002561 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 // Reject names on the arguments lists.
2565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2566 if (!ArgList[i].Name.empty())
2567 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002568 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002569 return Error(ArgList[i].Loc,
2570 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002571 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002572
Jay Foadb804a2b2011-07-12 14:06:48 +00002573 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002575 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002576
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002577 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578 return false;
2579}
2580
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002581/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2582/// other structs.
2583bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2584 SmallVector<Type*, 8> Elts;
2585 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002586
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002587 Result = StructType::get(Context, Elts, Packed);
2588 return false;
2589}
2590
2591/// ParseStructDefinition - Parse a struct in a 'type' definition.
2592bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2593 std::pair<Type*, LocTy> &Entry,
2594 Type *&ResultTy) {
2595 // If the type was already defined, diagnose the redefinition.
2596 if (Entry.first && !Entry.second.isValid())
2597 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002598
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002599 // If we have opaque, just return without filling in the definition for the
2600 // struct. This counts as a definition as far as the .ll file goes.
2601 if (EatIfPresent(lltok::kw_opaque)) {
2602 // This type is being defined, so clear the location to indicate this.
2603 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002604
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002605 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002606 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002607 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002608 ResultTy = Entry.first;
2609 return false;
2610 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002611
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002612 // If the type starts with '<', then it is either a packed struct or a vector.
2613 bool isPacked = EatIfPresent(lltok::less);
2614
2615 // If we don't have a struct, then we have a random type alias, which we
2616 // accept for compatibility with old files. These types are not allowed to be
2617 // forward referenced and not allowed to be recursive.
2618 if (Lex.getKind() != lltok::lbrace) {
2619 if (Entry.first)
2620 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002621
Craig Topper2617dcc2014-04-15 06:32:26 +00002622 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002623 if (isPacked)
2624 return ParseArrayVectorType(ResultTy, true);
2625 return ParseType(ResultTy);
2626 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002627
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002628 // This type is being defined, so clear the location to indicate this.
2629 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002630
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002631 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002632 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002633 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002634
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002635 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002636
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002637 SmallVector<Type*, 8> Body;
2638 if (ParseStructBody(Body) ||
2639 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2640 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002641
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002642 STy->setBody(Body, isPacked);
2643 ResultTy = STy;
2644 return false;
2645}
2646
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002648/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002650/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002652/// ::= '<' '{' Type (',' Type)* '}' '>'
2653bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 assert(Lex.getKind() == lltok::lbrace);
2655 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002657 // Handle the empty struct.
2658 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002660
Chris Lattnerf880ca22009-03-09 04:49:14 +00002661 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002662 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002663 if (ParseType(Ty)) return true;
2664 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002665
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002666 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002667 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Chris Lattner3822f632009-01-02 08:05:26 +00002669 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002670 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002671 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002672
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002673 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002674 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002675
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002676 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002679 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002680}
2681
2682/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2683/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002684/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685/// ::= '[' APSINTVAL 'x' Types ']'
2686/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002687bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2689 Lex.getAPSIntVal().getBitWidth() > 64)
2690 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002691
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 LocTy SizeLoc = Lex.getLoc();
2693 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002694 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002695
Chris Lattner3822f632009-01-02 08:05:26 +00002696 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2697 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002698
2699 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002700 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002701 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002702
Chris Lattner3822f632009-01-02 08:05:26 +00002703 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2704 "expected end of sequential type"))
2705 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002706
Chris Lattnerac161bf2009-01-02 07:01:27 +00002707 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002708 if (Size == 0)
2709 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002710 if ((unsigned)Size != Size)
2711 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002712 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002713 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002714 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002716 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002717 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002718 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 }
2720 return false;
2721}
2722
2723//===----------------------------------------------------------------------===//
2724// Function Semantic Analysis.
2725//===----------------------------------------------------------------------===//
2726
Chris Lattner3432c622009-10-28 03:39:23 +00002727LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2728 int functionNumber)
2729 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730
2731 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002732 for (Argument &A : F.args())
2733 if (!A.hasName())
2734 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002735}
2736
2737LLParser::PerFunctionState::~PerFunctionState() {
2738 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002739
David Blaikie9ebdc692015-09-21 21:07:50 +00002740 for (const auto &P : ForwardRefVals) {
2741 if (isa<BasicBlock>(P.second.first))
2742 continue;
2743 P.second.first->replaceAllUsesWith(
2744 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002745 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002746 }
2747
2748 for (const auto &P : ForwardRefValIDs) {
2749 if (isa<BasicBlock>(P.second.first))
2750 continue;
2751 P.second.first->replaceAllUsesWith(
2752 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002753 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002754 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755}
2756
Chris Lattner3432c622009-10-28 03:39:23 +00002757bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 if (!ForwardRefVals.empty())
2759 return P.Error(ForwardRefVals.begin()->second.second,
2760 "use of undefined value '%" + ForwardRefVals.begin()->first +
2761 "'");
2762 if (!ForwardRefValIDs.empty())
2763 return P.Error(ForwardRefValIDs.begin()->second.second,
2764 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002765 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 return false;
2767}
2768
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769/// GetVal - Get a value with the specified name or ID, creating a
2770/// forward reference record if needed. This can return null if the value
2771/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002772Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002773 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002774 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002775 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002776
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 // If this is a forward reference for the value, see if we already created a
2778 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002779 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002780 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 if (I != ForwardRefVals.end())
2782 Val = I->second.first;
2783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002784
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002786 if (Val)
2787 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002788
Chris Lattnerac161bf2009-01-02 07:01:27 +00002789 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002790 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002792 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002794
Chris Lattnerac161bf2009-01-02 07:01:27 +00002795 // Otherwise, create a new forward reference for this value and remember it.
2796 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002797 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002798 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002799 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002800 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002801 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002802
Chris Lattnerac161bf2009-01-02 07:01:27 +00002803 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2804 return FwdVal;
2805}
2806
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002807Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2808 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002809 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002810 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 // If this is a forward reference for the value, see if we already created a
2813 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002814 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002815 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002816 if (I != ForwardRefValIDs.end())
2817 Val = I->second.first;
2818 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002819
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002821 if (Val)
2822 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002823
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002824 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002826 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002828
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 // Otherwise, create a new forward reference for this value and remember it.
2830 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002831 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002832 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002833 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002834 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002835 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002836
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2838 return FwdVal;
2839}
2840
2841/// SetInstName - After an instruction is parsed and inserted into its
2842/// basic block, this installs its name.
2843bool LLParser::PerFunctionState::SetInstName(int NameID,
2844 const std::string &NameStr,
2845 LocTy NameLoc, Instruction *Inst) {
2846 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002847 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 if (NameID != -1 || !NameStr.empty())
2849 return P.Error(NameLoc, "instructions returning void cannot have a name");
2850 return false;
2851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002852
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 // If this was a numbered instruction, verify that the instruction is the
2854 // expected value and resolve any forward references.
2855 if (NameStr.empty()) {
2856 // If neither a name nor an ID was specified, just use the next ID.
2857 if (NameID == -1)
2858 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002859
Chris Lattnerac161bf2009-01-02 07:01:27 +00002860 if (unsigned(NameID) != NumberedVals.size())
2861 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002862 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
David Blaikie9ebdc692015-09-21 21:07:50 +00002864 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002866 Value *Sentinel = FI->second.first;
2867 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002869 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002870
2871 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002872 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 ForwardRefValIDs.erase(FI);
2874 }
2875
2876 NumberedVals.push_back(Inst);
2877 return false;
2878 }
2879
2880 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002881 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002882 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002883 Value *Sentinel = FI->second.first;
2884 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002886 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002887
2888 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002889 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002890 ForwardRefVals.erase(FI);
2891 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002892
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 // Set the name on the instruction.
2894 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002896 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002897 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002898 NameStr + "'");
2899 return false;
2900}
2901
2902/// GetBB - Get a basic block with the specified name or ID, creating a
2903/// forward reference record if needed.
2904BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2905 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002906 return dyn_cast_or_null<BasicBlock>(
2907 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908}
2909
2910BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002911 return dyn_cast_or_null<BasicBlock>(
2912 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002913}
2914
2915/// DefineBB - Define the specified basic block, which is either named or
2916/// unnamed. If there is an error, this returns null otherwise it returns
2917/// the block being defined.
2918BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2919 LocTy Loc) {
2920 BasicBlock *BB;
2921 if (Name.empty())
2922 BB = GetBB(NumberedVals.size(), Loc);
2923 else
2924 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002925 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002926
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927 // Move the block to the end of the function. Forward ref'd blocks are
2928 // inserted wherever they happen to be referenced.
2929 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002930
Chris Lattnerac161bf2009-01-02 07:01:27 +00002931 // Remove the block from forward ref sets.
2932 if (Name.empty()) {
2933 ForwardRefValIDs.erase(NumberedVals.size());
2934 NumberedVals.push_back(BB);
2935 } else {
2936 // BB forward references are already in the function symbol table.
2937 ForwardRefVals.erase(Name);
2938 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002939
Chris Lattnerac161bf2009-01-02 07:01:27 +00002940 return BB;
2941}
2942
2943//===----------------------------------------------------------------------===//
2944// Constants.
2945//===----------------------------------------------------------------------===//
2946
2947/// ParseValID - Parse an abstract value that doesn't necessarily have a
2948/// type implied. For example, if we parse "4" we don't know what integer type
2949/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002950/// sanity. PFS is used to convert function-local operands of metadata (since
2951/// metadata operands are not just parsed here but also converted to values).
2952/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002953bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 ID.Loc = Lex.getLoc();
2955 switch (Lex.getKind()) {
2956 default: return TokError("expected value token");
2957 case lltok::GlobalID: // @42
2958 ID.UIntVal = Lex.getUIntVal();
2959 ID.Kind = ValID::t_GlobalID;
2960 break;
2961 case lltok::GlobalVar: // @foo
2962 ID.StrVal = Lex.getStrVal();
2963 ID.Kind = ValID::t_GlobalName;
2964 break;
2965 case lltok::LocalVarID: // %42
2966 ID.UIntVal = Lex.getUIntVal();
2967 ID.Kind = ValID::t_LocalID;
2968 break;
2969 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 ID.StrVal = Lex.getStrVal();
2971 ID.Kind = ValID::t_LocalName;
2972 break;
2973 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002974 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002975 ID.Kind = ValID::t_APSInt;
2976 break;
2977 case lltok::APFloat:
2978 ID.APFloatVal = Lex.getAPFloatVal();
2979 ID.Kind = ValID::t_APFloat;
2980 break;
2981 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002982 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002983 ID.Kind = ValID::t_Constant;
2984 break;
2985 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002986 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002987 ID.Kind = ValID::t_Constant;
2988 break;
2989 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2990 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2991 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002992 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002993
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 case lltok::lbrace: {
2995 // ValID ::= '{' ConstVector '}'
2996 Lex.Lex();
2997 SmallVector<Constant*, 16> Elts;
2998 if (ParseGlobalValueVector(Elts) ||
2999 ParseToken(lltok::rbrace, "expected end of struct constant"))
3000 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003001
David Blaikieadbda4b2015-08-03 20:08:41 +00003002 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003003 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003004 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3005 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003006 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 return false;
3008 }
3009 case lltok::less: {
3010 // ValID ::= '<' ConstVector '>' --> Vector.
3011 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3012 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003013 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003014
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 SmallVector<Constant*, 16> Elts;
3016 LocTy FirstEltLoc = Lex.getLoc();
3017 if (ParseGlobalValueVector(Elts) ||
3018 (isPackedStruct &&
3019 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3020 ParseToken(lltok::greater, "expected end of constant"))
3021 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003022
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00003024 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3025 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3026 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003027 ID.UIntVal = Elts.size();
3028 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 return false;
3030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003031
Chris Lattnerac161bf2009-01-02 07:01:27 +00003032 if (Elts.empty())
3033 return Error(ID.Loc, "constant vector must not be empty");
3034
Duncan Sands9dff9be2010-02-15 16:12:20 +00003035 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003036 !Elts[0]->getType()->isFloatingPointTy() &&
3037 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003039 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003040
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 // Verify that all the vector elements have the same type.
3042 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3043 if (Elts[i]->getType() != Elts[0]->getType())
3044 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003045 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003046 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003047
Chris Lattner69229312011-02-15 00:14:00 +00003048 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 ID.Kind = ValID::t_Constant;
3050 return false;
3051 }
3052 case lltok::lsquare: { // Array Constant
3053 Lex.Lex();
3054 SmallVector<Constant*, 16> Elts;
3055 LocTy FirstEltLoc = Lex.getLoc();
3056 if (ParseGlobalValueVector(Elts) ||
3057 ParseToken(lltok::rsquare, "expected end of array constant"))
3058 return true;
3059
3060 // Handle empty element.
3061 if (Elts.empty()) {
3062 // Use undef instead of an array because it's inconvenient to determine
3063 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003064 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 return false;
3066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003067
Chris Lattnerac161bf2009-01-02 07:01:27 +00003068 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003069 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003070 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Owen Anderson4056ca92009-07-29 22:17:13 +00003072 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073
Chris Lattnerac161bf2009-01-02 07:01:27 +00003074 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003075 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003076 if (Elts[i]->getType() != Elts[0]->getType())
3077 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003078 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003079 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003081
Jay Foad83be3612011-06-22 09:24:39 +00003082 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 ID.Kind = ValID::t_Constant;
3084 return false;
3085 }
3086 case lltok::kw_c: // c "foo"
3087 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003088 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3089 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003090 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3091 ID.Kind = ValID::t_Constant;
3092 return false;
3093
3094 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003095 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3096 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003097 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003098 Lex.Lex();
3099 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003100 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003101 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003102 ParseStringConstant(ID.StrVal) ||
3103 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003104 ParseToken(lltok::StringConstant, "expected constraint string"))
3105 return true;
3106 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003107 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003108 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003109 ID.Kind = ValID::t_InlineAsm;
3110 return false;
3111 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003112
Chris Lattner3432c622009-10-28 03:39:23 +00003113 case lltok::kw_blockaddress: {
3114 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3115 Lex.Lex();
3116
3117 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003118
Chris Lattner3432c622009-10-28 03:39:23 +00003119 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3120 ParseValID(Fn) ||
3121 ParseToken(lltok::comma, "expected comma in block address expression")||
3122 ParseValID(Label) ||
3123 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3124 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003125
Chris Lattner3432c622009-10-28 03:39:23 +00003126 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3127 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003128 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003129 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003130
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003131 // Try to find the function (but skip it if it's forward-referenced).
3132 GlobalValue *GV = nullptr;
3133 if (Fn.Kind == ValID::t_GlobalID) {
3134 if (Fn.UIntVal < NumberedVals.size())
3135 GV = NumberedVals[Fn.UIntVal];
3136 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3137 GV = M->getNamedValue(Fn.StrVal);
3138 }
3139 Function *F = nullptr;
3140 if (GV) {
3141 // Confirm that it's actually a function with a definition.
3142 if (!isa<Function>(GV))
3143 return Error(Fn.Loc, "expected function name in blockaddress");
3144 F = cast<Function>(GV);
3145 if (F->isDeclaration())
3146 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3147 }
3148
3149 if (!F) {
3150 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003151 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003152 ForwardRefBlockAddresses.insert(std::make_pair(
3153 std::move(Fn),
3154 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003155 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3156 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003157 if (!FwdRef)
3158 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3159 GlobalValue::InternalLinkage, nullptr, "");
3160 ID.ConstantVal = FwdRef;
3161 ID.Kind = ValID::t_Constant;
3162 return false;
3163 }
3164
3165 // We found the function; now find the basic block. Don't use PFS, since we
3166 // might be inside a constant expression.
3167 BasicBlock *BB;
3168 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3169 if (Label.Kind == ValID::t_LocalID)
3170 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3171 else
3172 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3173 if (!BB)
3174 return Error(Label.Loc, "referenced value is not a basic block");
3175 } else {
3176 if (Label.Kind == ValID::t_LocalID)
3177 return Error(Label.Loc, "cannot take address of numeric label after "
3178 "the function is defined");
3179 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003180 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003181 if (!BB)
3182 return Error(Label.Loc, "referenced value is not a basic block");
3183 }
3184
3185 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003186 ID.Kind = ValID::t_Constant;
3187 return false;
3188 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003189
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 case lltok::kw_trunc:
3191 case lltok::kw_zext:
3192 case lltok::kw_sext:
3193 case lltok::kw_fptrunc:
3194 case lltok::kw_fpext:
3195 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003196 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 case lltok::kw_uitofp:
3198 case lltok::kw_sitofp:
3199 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003200 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003201 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003202 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003203 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003204 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 Constant *SrcVal;
3206 Lex.Lex();
3207 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3208 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003209 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003210 ParseType(DestTy) ||
3211 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3212 return true;
3213 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3214 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003215 getTypeString(SrcVal->getType()) + "' to '" +
3216 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003217 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003218 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003219 ID.Kind = ValID::t_Constant;
3220 return false;
3221 }
3222 case lltok::kw_extractvalue: {
3223 Lex.Lex();
3224 Constant *Val;
3225 SmallVector<unsigned, 4> Indices;
3226 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3227 ParseGlobalTypeAndValue(Val) ||
3228 ParseIndexList(Indices) ||
3229 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3230 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003231
Chris Lattner392be582010-02-12 20:49:41 +00003232 if (!Val->getType()->isAggregateType())
3233 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003234 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003235 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003236 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003237 ID.Kind = ValID::t_Constant;
3238 return false;
3239 }
3240 case lltok::kw_insertvalue: {
3241 Lex.Lex();
3242 Constant *Val0, *Val1;
3243 SmallVector<unsigned, 4> Indices;
3244 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3245 ParseGlobalTypeAndValue(Val0) ||
3246 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3247 ParseGlobalTypeAndValue(Val1) ||
3248 ParseIndexList(Indices) ||
3249 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3250 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003251 if (!Val0->getType()->isAggregateType())
3252 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003253 Type *IndexedType =
3254 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3255 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003256 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003257 if (IndexedType != Val1->getType())
3258 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3259 getTypeString(Val1->getType()) +
3260 "' instead of '" + getTypeString(IndexedType) +
3261 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003262 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003263 ID.Kind = ValID::t_Constant;
3264 return false;
3265 }
3266 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003267 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003268 unsigned PredVal, Opc = Lex.getUIntVal();
3269 Constant *Val0, *Val1;
3270 Lex.Lex();
3271 if (ParseCmpPredicate(PredVal, Opc) ||
3272 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3273 ParseGlobalTypeAndValue(Val0) ||
3274 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3275 ParseGlobalTypeAndValue(Val1) ||
3276 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3277 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003278
Chris Lattnerac161bf2009-01-02 07:01:27 +00003279 if (Val0->getType() != Val1->getType())
3280 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003283
Chris Lattnerac161bf2009-01-02 07:01:27 +00003284 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003285 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003286 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003287 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003288 } else {
3289 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003290 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003291 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003292 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003293 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294 }
3295 ID.Kind = ValID::t_Constant;
3296 return false;
3297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003298
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 // Binary Operators.
3300 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003301 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003302 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003303 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003304 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003305 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003306 case lltok::kw_udiv:
3307 case lltok::kw_sdiv:
3308 case lltok::kw_fdiv:
3309 case lltok::kw_urem:
3310 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003311 case lltok::kw_frem:
3312 case lltok::kw_shl:
3313 case lltok::kw_lshr:
3314 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003315 bool NUW = false;
3316 bool NSW = false;
3317 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003318 unsigned Opc = Lex.getUIntVal();
3319 Constant *Val0, *Val1;
3320 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003321 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003322 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3323 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003324 if (EatIfPresent(lltok::kw_nuw))
3325 NUW = true;
3326 if (EatIfPresent(lltok::kw_nsw)) {
3327 NSW = true;
3328 if (EatIfPresent(lltok::kw_nuw))
3329 NUW = true;
3330 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003331 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3332 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003333 if (EatIfPresent(lltok::kw_exact))
3334 Exact = true;
3335 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003336 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3337 ParseGlobalTypeAndValue(Val0) ||
3338 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3339 ParseGlobalTypeAndValue(Val1) ||
3340 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3341 return true;
3342 if (Val0->getType() != Val1->getType())
3343 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003344 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003345 if (NUW)
3346 return Error(ModifierLoc, "nuw only applies to integer operations");
3347 if (NSW)
3348 return Error(ModifierLoc, "nsw only applies to integer operations");
3349 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003350 // Check that the type is valid for the operator.
3351 switch (Opc) {
3352 case Instruction::Add:
3353 case Instruction::Sub:
3354 case Instruction::Mul:
3355 case Instruction::UDiv:
3356 case Instruction::SDiv:
3357 case Instruction::URem:
3358 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003359 case Instruction::Shl:
3360 case Instruction::AShr:
3361 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003362 if (!Val0->getType()->isIntOrIntVectorTy())
3363 return Error(ID.Loc, "constexpr requires integer operands");
3364 break;
3365 case Instruction::FAdd:
3366 case Instruction::FSub:
3367 case Instruction::FMul:
3368 case Instruction::FDiv:
3369 case Instruction::FRem:
3370 if (!Val0->getType()->isFPOrFPVectorTy())
3371 return Error(ID.Loc, "constexpr requires fp operands");
3372 break;
3373 default: llvm_unreachable("Unknown binary operator!");
3374 }
Dan Gohman1b849082009-09-07 23:54:19 +00003375 unsigned Flags = 0;
3376 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3377 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003378 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003379 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003380 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003381 ID.Kind = ValID::t_Constant;
3382 return false;
3383 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003384
Chris Lattnerac161bf2009-01-02 07:01:27 +00003385 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003386 case lltok::kw_and:
3387 case lltok::kw_or:
3388 case lltok::kw_xor: {
3389 unsigned Opc = Lex.getUIntVal();
3390 Constant *Val0, *Val1;
3391 Lex.Lex();
3392 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3393 ParseGlobalTypeAndValue(Val0) ||
3394 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3395 ParseGlobalTypeAndValue(Val1) ||
3396 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3397 return true;
3398 if (Val0->getType() != Val1->getType())
3399 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003400 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003401 return Error(ID.Loc,
3402 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003403 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 ID.Kind = ValID::t_Constant;
3405 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406 }
3407
Chris Lattnerac161bf2009-01-02 07:01:27 +00003408 case lltok::kw_getelementptr:
3409 case lltok::kw_shufflevector:
3410 case lltok::kw_insertelement:
3411 case lltok::kw_extractelement:
3412 case lltok::kw_select: {
3413 unsigned Opc = Lex.getUIntVal();
3414 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003415 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003416 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003417 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003418
Dan Gohman1639c392009-07-27 21:53:46 +00003419 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003420 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003421
3422 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3423 return true;
3424
3425 LocTy ExplicitTypeLoc = Lex.getLoc();
3426 if (Opc == Instruction::GetElementPtr) {
3427 if (ParseType(Ty) ||
3428 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3429 return true;
3430 }
3431
Peter Collingbourned93620b2016-11-10 22:34:55 +00003432 Optional<unsigned> InRangeOp;
3433 if (ParseGlobalValueVector(
3434 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003435 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3436 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003437
Chris Lattnerac161bf2009-01-02 07:01:27 +00003438 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003439 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003440 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003441 return Error(ID.Loc, "base of getelementptr must be a pointer");
3442
3443 Type *BaseType = Elts[0]->getType();
3444 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003445 if (Ty != BasePointerType->getElementType())
3446 return Error(
3447 ExplicitTypeLoc,
3448 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003449
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003450 unsigned GEPWidth =
3451 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3452
Jay Foaded8db7d2011-07-21 14:31:17 +00003453 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003454 for (Constant *Val : Indices) {
3455 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003456 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003457 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003458 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003459 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003460 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003461 return Error(
3462 ID.Loc,
3463 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003464 // GEPWidth may have been unknown because the base is a scalar,
3465 // but it is known now.
3466 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003467 }
3468 }
3469
Craig Toppere3dcce92015-08-01 22:20:21 +00003470 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003471 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003472 return Error(ID.Loc, "base element of getelementptr must be sized");
3473
David Blaikie4a2e73b2015-04-02 18:55:32 +00003474 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003475 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003476
3477 if (InRangeOp) {
3478 if (*InRangeOp == 0)
3479 return Error(ID.Loc,
3480 "inrange keyword may not appear on pointer operand");
3481 --*InRangeOp;
3482 }
3483
3484 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3485 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003486 } else if (Opc == Instruction::Select) {
3487 if (Elts.size() != 3)
3488 return Error(ID.Loc, "expected three operands to select");
3489 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3490 Elts[2]))
3491 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003492 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003493 } else if (Opc == Instruction::ShuffleVector) {
3494 if (Elts.size() != 3)
3495 return Error(ID.Loc, "expected three operands to shufflevector");
3496 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3497 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003498 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003499 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003500 } else if (Opc == Instruction::ExtractElement) {
3501 if (Elts.size() != 2)
3502 return Error(ID.Loc, "expected two operands to extractelement");
3503 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3504 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003505 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003506 } else {
3507 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3508 if (Elts.size() != 3)
3509 return Error(ID.Loc, "expected three operands to insertelement");
3510 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3511 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003512 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003513 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003514 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003515
Chris Lattnerac161bf2009-01-02 07:01:27 +00003516 ID.Kind = ValID::t_Constant;
3517 return false;
3518 }
3519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003520
Chris Lattnerac161bf2009-01-02 07:01:27 +00003521 Lex.Lex();
3522 return false;
3523}
3524
3525/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003526bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003527 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003528 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003529 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003530 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003531 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003532 if (V && !(C = dyn_cast<Constant>(V)))
3533 return Error(ID.Loc, "global values must be constants");
3534 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003535}
3536
Victor Hernandez9d75c962010-01-11 22:31:58 +00003537bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003538 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003539 return ParseType(Ty) ||
3540 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003541}
3542
Rafael Espindola83a362c2015-01-06 22:55:16 +00003543bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003544 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003545
3546 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003547 if (!EatIfPresent(lltok::kw_comdat))
3548 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003549
3550 if (EatIfPresent(lltok::lparen)) {
3551 if (Lex.getKind() != lltok::ComdatVar)
3552 return TokError("expected comdat variable");
3553 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3554 Lex.Lex();
3555 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3556 return true;
3557 } else {
3558 if (GlobalName.empty())
3559 return TokError("comdat cannot be unnamed");
3560 C = getComdat(GlobalName, KwLoc);
3561 }
3562
David Majnemerdad0a642014-06-27 18:19:56 +00003563 return false;
3564}
3565
Victor Hernandez9d75c962010-01-11 22:31:58 +00003566/// ParseGlobalValueVector
3567/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003568/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3569bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3570 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003571 // Empty list.
3572 if (Lex.getKind() == lltok::rbrace ||
3573 Lex.getKind() == lltok::rsquare ||
3574 Lex.getKind() == lltok::greater ||
3575 Lex.getKind() == lltok::rparen)
3576 return false;
3577
Peter Collingbourned93620b2016-11-10 22:34:55 +00003578 do {
3579 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3580 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003581
Peter Collingbourned93620b2016-11-10 22:34:55 +00003582 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003583 if (ParseGlobalTypeAndValue(C)) return true;
3584 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003585 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003586
3587 return false;
3588}
3589
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003590bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003591 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003592 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003593 return true;
3594
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003595 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003596 return false;
3597}
3598
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003599/// MDNode:
3600/// ::= !{ ... }
3601/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003602/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003603bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003604 if (Lex.getKind() == lltok::MetadataVar)
3605 return ParseSpecializedMDNode(N);
3606
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003607 return ParseToken(lltok::exclaim, "expected '!' here") ||
3608 ParseMDNodeTail(N);
3609}
3610
3611bool LLParser::ParseMDNodeTail(MDNode *&N) {
3612 // !{ ... }
3613 if (Lex.getKind() == lltok::lbrace)
3614 return ParseMDTuple(N);
3615
3616 // !42
3617 return ParseMDNodeID(N);
3618}
3619
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003620namespace {
3621
3622/// Structure to represent an optional metadata field.
3623template <class FieldTy> struct MDFieldImpl {
3624 typedef MDFieldImpl ImplTy;
3625 FieldTy Val;
3626 bool Seen;
3627
3628 void assign(FieldTy Val) {
3629 Seen = true;
3630 this->Val = std::move(Val);
3631 }
3632
3633 explicit MDFieldImpl(FieldTy Default)
3634 : Val(std::move(Default)), Seen(false) {}
3635};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003636
Sander de Smalenfdf40912018-01-24 09:56:07 +00003637/// Structure to represent an optional metadata field that
3638/// can be of either type (A or B) and encapsulates the
3639/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3640/// to reimplement the specifics for representing each Field.
3641template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3642 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3643 FieldTypeA A;
3644 FieldTypeB B;
3645 bool Seen;
3646
3647 enum {
3648 IsInvalid = 0,
3649 IsTypeA = 1,
3650 IsTypeB = 2
3651 } WhatIs;
3652
3653 void assign(FieldTypeA A) {
3654 Seen = true;
3655 this->A = std::move(A);
3656 WhatIs = IsTypeA;
3657 }
3658
3659 void assign(FieldTypeB B) {
3660 Seen = true;
3661 this->B = std::move(B);
3662 WhatIs = IsTypeB;
3663 }
3664
3665 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3666 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3667 WhatIs(IsInvalid) {}
3668};
3669
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003670struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3671 uint64_t Max;
3672
3673 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3674 : ImplTy(Default), Max(Max) {}
3675};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003676
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003677struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003678 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003679};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003680
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003681struct ColumnField : public MDUnsignedField {
3682 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3683};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003684
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003685struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003686 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003687 DwarfTagField(dwarf::Tag DefaultTag)
3688 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003689};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003690
Amjad Abouda9bcf162015-12-10 12:56:35 +00003691struct DwarfMacinfoTypeField : public MDUnsignedField {
3692 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3693 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3694 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3695};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003696
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003697struct DwarfAttEncodingField : public MDUnsignedField {
3698 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3699};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003700
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003701struct DwarfVirtualityField : public MDUnsignedField {
3702 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3703};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003704
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003705struct DwarfLangField : public MDUnsignedField {
3706 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3707};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003708
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003709struct DwarfCCField : public MDUnsignedField {
3710 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3711};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003712
Adrian Prantlb939a252016-03-31 23:56:58 +00003713struct EmissionKindField : public MDUnsignedField {
3714 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3715};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003716
David Blaikie66cf14d2018-08-16 21:29:55 +00003717struct NameTableKindField : public MDUnsignedField {
3718 NameTableKindField()
3719 : MDUnsignedField(
3720 0, (unsigned)
3721 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3722};
3723
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003724struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3725 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003726};
3727
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003728struct MDSignedField : public MDFieldImpl<int64_t> {
3729 int64_t Min;
3730 int64_t Max;
3731
3732 MDSignedField(int64_t Default = 0)
3733 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3734 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3735 : ImplTy(Default), Min(Min), Max(Max) {}
3736};
3737
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003738struct MDBoolField : public MDFieldImpl<bool> {
3739 MDBoolField(bool Default = false) : ImplTy(Default) {}
3740};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003741
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003742struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003743 bool AllowNull;
3744
3745 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003746};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003747
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003748struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3749 MDConstant() : ImplTy(nullptr) {}
3750};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003751
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003752struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003753 bool AllowEmpty;
3754 MDStringField(bool AllowEmpty = true)
3755 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003756};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003757
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003758struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3759 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3760};
3761
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003762struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003763 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3764};
3765
Sander de Smalenfdf40912018-01-24 09:56:07 +00003766struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3767 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3768 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3769
3770 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3771 bool AllowNull = true)
3772 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3773
3774 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3775 bool isMDField() const { return WhatIs == IsTypeB; }
3776 int64_t getMDSignedValue() const {
3777 assert(isMDSignedField() && "Wrong field type");
3778 return A.Val;
3779 }
3780 Metadata *getMDFieldValue() const {
3781 assert(isMDField() && "Wrong field type");
3782 return B.Val;
3783 }
3784};
3785
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003786struct MDSignedOrUnsignedField
3787 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3788 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3789
3790 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3791 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3792 int64_t getMDSignedValue() const {
3793 assert(isMDSignedField() && "Wrong field type");
3794 return A.Val;
3795 }
3796 uint64_t getMDUnsignedValue() const {
3797 assert(isMDUnsignedField() && "Wrong field type");
3798 return B.Val;
3799 }
3800};
3801
Eugene Zelenko1804a772016-08-25 00:45:04 +00003802} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003803
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003804namespace llvm {
3805
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003806template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003807bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003808 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003809 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3810 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003811
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003812 auto &U = Lex.getAPSIntVal();
3813 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003814 return TokError("value for '" + Name + "' too large, limit is " +
3815 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003816 Result.assign(U.getZExtValue());
3817 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003818 Lex.Lex();
3819 return false;
3820}
3821
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003822template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003823bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3824 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3825}
3826template <>
3827bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3828 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3829}
3830
3831template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003832bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3833 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003834 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003835
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003836 if (Lex.getKind() != lltok::DwarfTag)
3837 return TokError("expected DWARF tag");
3838
3839 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3840 if (Tag == dwarf::DW_TAG_invalid)
3841 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003842 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003843
3844 Result.assign(Tag);
3845 Lex.Lex();
3846 return false;
3847}
3848
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003849template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003850bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003851 DwarfMacinfoTypeField &Result) {
3852 if (Lex.getKind() == lltok::APSInt)
3853 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3854
3855 if (Lex.getKind() != lltok::DwarfMacinfo)
3856 return TokError("expected DWARF macinfo type");
3857
3858 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3859 if (Macinfo == dwarf::DW_MACINFO_invalid)
3860 return TokError(
3861 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3862 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3863
3864 Result.assign(Macinfo);
3865 Lex.Lex();
3866 return false;
3867}
3868
3869template <>
3870bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003871 DwarfVirtualityField &Result) {
3872 if (Lex.getKind() == lltok::APSInt)
3873 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3874
3875 if (Lex.getKind() != lltok::DwarfVirtuality)
3876 return TokError("expected DWARF virtuality code");
3877
3878 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003879 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003880 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3881 Lex.getStrVal() + "'");
3882 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3883 Result.assign(Virtuality);
3884 Lex.Lex();
3885 return false;
3886}
3887
3888template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003889bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3890 if (Lex.getKind() == lltok::APSInt)
3891 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3892
3893 if (Lex.getKind() != lltok::DwarfLang)
3894 return TokError("expected DWARF language");
3895
3896 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3897 if (!Lang)
3898 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3899 "'");
3900 assert(Lang <= Result.Max && "Expected valid DWARF language");
3901 Result.assign(Lang);
3902 Lex.Lex();
3903 return false;
3904}
3905
3906template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003907bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3908 if (Lex.getKind() == lltok::APSInt)
3909 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3910
3911 if (Lex.getKind() != lltok::DwarfCC)
3912 return TokError("expected DWARF calling convention");
3913
3914 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3915 if (!CC)
3916 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3917 "'");
3918 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3919 Result.assign(CC);
3920 Lex.Lex();
3921 return false;
3922}
3923
3924template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003925bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3926 if (Lex.getKind() == lltok::APSInt)
3927 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3928
3929 if (Lex.getKind() != lltok::EmissionKind)
3930 return TokError("expected emission kind");
3931
3932 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3933 if (!Kind)
3934 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3935 "'");
3936 assert(*Kind <= Result.Max && "Expected valid emission kind");
3937 Result.assign(*Kind);
3938 Lex.Lex();
3939 return false;
3940}
Fangrui Songf78650a2018-07-30 19:41:25 +00003941
Adrian Prantlb939a252016-03-31 23:56:58 +00003942template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003943bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00003944 NameTableKindField &Result) {
3945 if (Lex.getKind() == lltok::APSInt)
3946 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3947
3948 if (Lex.getKind() != lltok::NameTableKind)
3949 return TokError("expected nameTable kind");
3950
3951 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3952 if (!Kind)
3953 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3954 "'");
3955 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3956 Result.assign((unsigned)*Kind);
3957 Lex.Lex();
3958 return false;
3959}
3960
3961template <>
3962bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003963 DwarfAttEncodingField &Result) {
3964 if (Lex.getKind() == lltok::APSInt)
3965 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3966
3967 if (Lex.getKind() != lltok::DwarfAttEncoding)
3968 return TokError("expected DWARF type attribute encoding");
3969
3970 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3971 if (!Encoding)
3972 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3973 Lex.getStrVal() + "'");
3974 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3975 Result.assign(Encoding);
3976 Lex.Lex();
3977 return false;
3978}
3979
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003980/// DIFlagField
3981/// ::= uint32
3982/// ::= DIFlagVector
3983/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3984template <>
3985bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003986
3987 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003988 auto parseFlag = [&](DINode::DIFlags &Val) {
3989 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3990 uint32_t TempVal = static_cast<uint32_t>(Val);
3991 bool Res = ParseUInt32(TempVal);
3992 Val = static_cast<DINode::DIFlags>(TempVal);
3993 return Res;
3994 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003995
3996 if (Lex.getKind() != lltok::DIFlag)
3997 return TokError("expected debug info flag");
3998
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003999 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004000 if (!Val)
4001 return TokError(Twine("invalid debug info flag flag '") +
4002 Lex.getStrVal() + "'");
4003 Lex.Lex();
4004 return false;
4005 };
4006
4007 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004008 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004009 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004010 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004011 if (parseFlag(Val))
4012 return true;
4013 Combined |= Val;
4014 } while (EatIfPresent(lltok::bar));
4015
4016 Result.assign(Combined);
4017 return false;
4018}
4019
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004020template <>
4021bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004022 MDSignedField &Result) {
4023 if (Lex.getKind() != lltok::APSInt)
4024 return TokError("expected signed integer");
4025
4026 auto &S = Lex.getAPSIntVal();
4027 if (S < Result.Min)
4028 return TokError("value for '" + Name + "' too small, limit is " +
4029 Twine(Result.Min));
4030 if (S > Result.Max)
4031 return TokError("value for '" + Name + "' too large, limit is " +
4032 Twine(Result.Max));
4033 Result.assign(S.getExtValue());
4034 assert(Result.Val >= Result.Min && "Expected value in range");
4035 assert(Result.Val <= Result.Max && "Expected value in range");
4036 Lex.Lex();
4037 return false;
4038}
4039
4040template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004041bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4042 switch (Lex.getKind()) {
4043 default:
4044 return TokError("expected 'true' or 'false'");
4045 case lltok::kw_true:
4046 Result.assign(true);
4047 break;
4048 case lltok::kw_false:
4049 Result.assign(false);
4050 break;
4051 }
4052 Lex.Lex();
4053 return false;
4054}
4055
4056template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004057bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004058 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004059 if (!Result.AllowNull)
4060 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004061 Lex.Lex();
4062 Result.assign(nullptr);
4063 return false;
4064 }
4065
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004066 Metadata *MD;
4067 if (ParseMetadata(MD, nullptr))
4068 return true;
4069
4070 Result.assign(MD);
4071 return false;
4072}
4073
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004074template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004075bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4076 MDSignedOrMDField &Result) {
4077 // Try to parse a signed int.
4078 if (Lex.getKind() == lltok::APSInt) {
4079 MDSignedField Res = Result.A;
4080 if (!ParseMDField(Loc, Name, Res)) {
4081 Result.assign(Res);
4082 return false;
4083 }
4084 return true;
4085 }
4086
4087 // Otherwise, try to parse as an MDField.
4088 MDField Res = Result.B;
4089 if (!ParseMDField(Loc, Name, Res)) {
4090 Result.assign(Res);
4091 return false;
4092 }
4093
4094 return true;
4095}
4096
4097template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004098bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4099 MDSignedOrUnsignedField &Result) {
4100 if (Lex.getKind() != lltok::APSInt)
4101 return false;
4102
4103 if (Lex.getAPSIntVal().isSigned()) {
4104 MDSignedField Res = Result.A;
4105 if (ParseMDField(Loc, Name, Res))
4106 return true;
4107 Result.assign(Res);
4108 return false;
4109 }
4110
4111 MDUnsignedField Res = Result.B;
4112 if (ParseMDField(Loc, Name, Res))
4113 return true;
4114 Result.assign(Res);
4115 return false;
4116}
4117
4118template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004119bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004120 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004121 std::string S;
4122 if (ParseStringConstant(S))
4123 return true;
4124
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004125 if (!Result.AllowEmpty && S.empty())
4126 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4127
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004128 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004129 return false;
4130}
4131
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004132template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004133bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4134 SmallVector<Metadata *, 4> MDs;
4135 if (ParseMDNodeVector(MDs))
4136 return true;
4137
4138 Result.assign(std::move(MDs));
4139 return false;
4140}
4141
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004142template <>
4143bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4144 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004145 Optional<DIFile::ChecksumKind> CSKind =
4146 DIFile::getChecksumKind(Lex.getStrVal());
4147
4148 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004149 return TokError(
4150 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4151
Scott Linder71603842018-02-12 19:45:54 +00004152 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004153 Lex.Lex();
4154 return false;
4155}
4156
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004157} // end namespace llvm
4158
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004159template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004160bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004161 do {
4162 if (Lex.getKind() != lltok::LabelStr)
4163 return TokError("expected field label here");
4164
4165 if (parseField())
4166 return true;
4167 } while (EatIfPresent(lltok::comma));
4168
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004169 return false;
4170}
4171
4172template <class ParserTy>
4173bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4174 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4175 Lex.Lex();
4176
4177 if (ParseToken(lltok::lparen, "expected '(' here"))
4178 return true;
4179 if (Lex.getKind() != lltok::rparen)
4180 if (ParseMDFieldsImplBody(parseField))
4181 return true;
4182
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004183 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004184 return ParseToken(lltok::rparen, "expected ')' here");
4185}
4186
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004187template <class FieldTy>
4188bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4189 if (Result.Seen)
4190 return TokError("field '" + Name + "' cannot be specified more than once");
4191
4192 LocTy Loc = Lex.getLoc();
4193 Lex.Lex();
4194 return ParseMDField(Loc, Name, Result);
4195}
4196
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004197bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4198 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004199
4200#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004201 if (Lex.getStrVal() == #CLASS) \
4202 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004203#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004204
4205 return TokError("expected metadata type");
4206}
4207
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004208#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4209#define NOP_FIELD(NAME, TYPE, INIT)
4210#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4211 if (!NAME.Seen) \
4212 return Error(ClosingLoc, "missing required field '" #NAME "'");
4213#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004214 if (Lex.getStrVal() == #NAME) \
4215 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004216#define PARSE_MD_FIELDS() \
4217 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4218 do { \
4219 LocTy ClosingLoc; \
4220 if (ParseMDFieldsImpl([&]() -> bool { \
4221 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4222 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4223 }, ClosingLoc)) \
4224 return true; \
4225 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4226 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004227#define GET_OR_DISTINCT(CLASS, ARGS) \
4228 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004229
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004230/// ParseDILocationFields:
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004231/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4232/// isImplicitCode: true)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004233bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004235 OPTIONAL(line, LineField, ); \
4236 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004237 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004238 OPTIONAL(inlinedAt, MDField, ); \
4239 OPTIONAL(isImplicitCode, MDBoolField, (false));
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004240 PARSE_MD_FIELDS();
4241#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004242
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004243 Result =
4244 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4245 inlinedAt.Val, isImplicitCode.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004246 return false;
4247}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004248
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004249/// ParseGenericDINode:
4250/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4251bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004252#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004253 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004254 OPTIONAL(header, MDStringField, ); \
4255 OPTIONAL(operands, MDFieldList, );
4256 PARSE_MD_FIELDS();
4257#undef VISIT_MD_FIELDS
4258
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004259 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004260 (Context, tag.Val, header.Val, operands.Val));
4261 return false;
4262}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004263
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004264/// ParseDISubrange:
4265/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004266/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004267bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004268#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004269 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004270 OPTIONAL(lowerBound, MDSignedField, );
4271 PARSE_MD_FIELDS();
4272#undef VISIT_MD_FIELDS
4273
Sander de Smalenfdf40912018-01-24 09:56:07 +00004274 if (count.isMDSignedField())
4275 Result = GET_OR_DISTINCT(
4276 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4277 else if (count.isMDField())
4278 Result = GET_OR_DISTINCT(
4279 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4280 else
4281 return true;
4282
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004283 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004284}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004285
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004286/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004287/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004288bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004289#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004290 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004291 REQUIRED(value, MDSignedOrUnsignedField, ); \
4292 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004293 PARSE_MD_FIELDS();
4294#undef VISIT_MD_FIELDS
4295
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004296 if (isUnsigned.Val && value.isMDSignedField())
4297 return TokError("unsigned enumerator with negative value");
4298
4299 int64_t Value = value.isMDSignedField()
4300 ? value.getMDSignedValue()
4301 : static_cast<int64_t>(value.getMDUnsignedValue());
4302 Result =
4303 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4304
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004305 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004306}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004307
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004308/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004309/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4310/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004311bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004312#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004313 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004314 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004315 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004316 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004317 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4318 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004319 PARSE_MD_FIELDS();
4320#undef VISIT_MD_FIELDS
4321
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004322 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004323 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004324 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004325}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004326
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004327/// ParseDIDerivedType:
4328/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004329/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004330/// align: 32, offset: 0, flags: 0, extraData: !3,
4331/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004332bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004333#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4334 REQUIRED(tag, DwarfTagField, ); \
4335 OPTIONAL(name, MDStringField, ); \
4336 OPTIONAL(file, MDField, ); \
4337 OPTIONAL(line, LineField, ); \
4338 OPTIONAL(scope, MDField, ); \
4339 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004340 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004341 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004342 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004343 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004344 OPTIONAL(extraData, MDField, ); \
4345 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004346 PARSE_MD_FIELDS();
4347#undef VISIT_MD_FIELDS
4348
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004349 Optional<unsigned> DWARFAddressSpace;
4350 if (dwarfAddressSpace.Val != UINT32_MAX)
4351 DWARFAddressSpace = dwarfAddressSpace.Val;
4352
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004353 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004354 (Context, tag.Val, name.Val, file.Val, line.Val,
4355 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004356 offset.Val, DWARFAddressSpace, flags.Val,
4357 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004358 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004359}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004360
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004361bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004362#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4363 REQUIRED(tag, DwarfTagField, ); \
4364 OPTIONAL(name, MDStringField, ); \
4365 OPTIONAL(file, MDField, ); \
4366 OPTIONAL(line, LineField, ); \
4367 OPTIONAL(scope, MDField, ); \
4368 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004369 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004370 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004371 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004372 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004373 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004374 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004375 OPTIONAL(vtableHolder, MDField, ); \
4376 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004377 OPTIONAL(identifier, MDStringField, ); \
4378 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004379 PARSE_MD_FIELDS();
4380#undef VISIT_MD_FIELDS
4381
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004382 // If this has an identifier try to build an ODR type.
4383 if (identifier.Val)
4384 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004385 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4386 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4387 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004388 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004389 Result = CT;
4390 return false;
4391 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004392
4393 // Create a new node, and save it in the context if it belongs in the type
4394 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004395 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004396 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004397 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4398 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004399 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4400 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004401 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004402}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004403
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004406 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004407 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004408 REQUIRED(types, MDField, );
4409 PARSE_MD_FIELDS();
4410#undef VISIT_MD_FIELDS
4411
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004412 Result = GET_OR_DISTINCT(DISubroutineType,
4413 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004414 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004415}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004416
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004417/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004418/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004419/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004420/// checksum: "000102030405060708090a0b0c0d0e0f",
4421/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004422bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004423 // The default constructed value for checksumkind is required, but will never
4424 // be used, as the parser checks if the field was actually Seen before using
4425 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004426#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4427 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004428 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004429 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004430 OPTIONAL(checksum, MDStringField, ); \
4431 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004432 PARSE_MD_FIELDS();
4433#undef VISIT_MD_FIELDS
4434
Scott Linder71603842018-02-12 19:45:54 +00004435 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4436 if (checksumkind.Seen && checksum.Seen)
4437 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4438 else if (checksumkind.Seen || checksum.Seen)
4439 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4440
Scott Linder16c7bda2018-02-23 23:01:06 +00004441 Optional<MDString *> OptSource;
4442 if (source.Seen)
4443 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004444 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004445 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004446 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004447}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004448
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004449/// ParseDICompileUnit:
4450/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004451/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004452/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004453/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004454/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004455bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004456 if (!IsDistinct)
4457 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4458
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004459#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4460 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004461 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004462 OPTIONAL(producer, MDStringField, ); \
4463 OPTIONAL(isOptimized, MDBoolField, ); \
4464 OPTIONAL(flags, MDStringField, ); \
4465 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4466 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004467 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004468 OPTIONAL(enums, MDField, ); \
4469 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004470 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004471 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004472 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004473 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004474 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004475 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikie66cf14d2018-08-16 21:29:55 +00004476 OPTIONAL(nameTableKind, NameTableKindField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004477 PARSE_MD_FIELDS();
4478#undef VISIT_MD_FIELDS
4479
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004480 Result = DICompileUnit::getDistinct(
4481 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4482 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004483 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikie66cf14d2018-08-16 21:29:55 +00004484 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004485 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004486}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004487
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004488/// ParseDISubprogram:
4489/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004490/// file: !1, line: 7, type: !2, isLocal: false,
4491/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004492/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004493/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004494/// isOptimized: false, templateParams: !4, declaration: !5,
Shiva Chen2c864552018-05-09 02:40:45 +00004495/// retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004496bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004497 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004498#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4499 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004500 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004501 OPTIONAL(linkageName, MDStringField, ); \
4502 OPTIONAL(file, MDField, ); \
4503 OPTIONAL(line, LineField, ); \
4504 OPTIONAL(type, MDField, ); \
4505 OPTIONAL(isLocal, MDBoolField, ); \
4506 OPTIONAL(isDefinition, MDBoolField, (true)); \
4507 OPTIONAL(scopeLine, LineField, ); \
4508 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004509 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004510 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004511 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004512 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004513 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004514 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004515 OPTIONAL(templateParams, MDField, ); \
4516 OPTIONAL(declaration, MDField, ); \
Shiva Chen2c864552018-05-09 02:40:45 +00004517 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004518 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004519 PARSE_MD_FIELDS();
4520#undef VISIT_MD_FIELDS
4521
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004522 if (isDefinition.Val && !IsDistinct)
4523 return Lex.Error(
4524 Loc,
4525 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4526
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004527 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004528 DISubprogram,
4529 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4530 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4531 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4532 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004533 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004534 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004535}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004536
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004537/// ParseDILexicalBlock:
4538/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4539bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004540#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004541 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004542 OPTIONAL(file, MDField, ); \
4543 OPTIONAL(line, LineField, ); \
4544 OPTIONAL(column, ColumnField, );
4545 PARSE_MD_FIELDS();
4546#undef VISIT_MD_FIELDS
4547
4548 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004549 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004550 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004551}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004552
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004553/// ParseDILexicalBlockFile:
4554/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4555bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004556#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004557 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004558 OPTIONAL(file, MDField, ); \
4559 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4560 PARSE_MD_FIELDS();
4561#undef VISIT_MD_FIELDS
4562
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004563 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004564 (Context, scope.Val, file.Val, discriminator.Val));
4565 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004566}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004567
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004568/// ParseDINamespace:
4569/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4570bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4572 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004573 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004574 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004575 PARSE_MD_FIELDS();
4576#undef VISIT_MD_FIELDS
4577
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004578 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004579 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004580 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004581}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004582
Amjad Abouda9bcf162015-12-10 12:56:35 +00004583/// ParseDIMacro:
4584/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4585bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4586#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4587 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004588 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004589 REQUIRED(name, MDStringField, ); \
4590 OPTIONAL(value, MDStringField, );
4591 PARSE_MD_FIELDS();
4592#undef VISIT_MD_FIELDS
4593
4594 Result = GET_OR_DISTINCT(DIMacro,
4595 (Context, type.Val, line.Val, name.Val, value.Val));
4596 return false;
4597}
4598
4599/// ParseDIMacroFile:
4600/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4601bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4602#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4603 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004604 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004605 REQUIRED(file, MDField, ); \
4606 OPTIONAL(nodes, MDField, );
4607 PARSE_MD_FIELDS();
4608#undef VISIT_MD_FIELDS
4609
4610 Result = GET_OR_DISTINCT(DIMacroFile,
4611 (Context, type.Val, line.Val, file.Val, nodes.Val));
4612 return false;
4613}
4614
Adrian Prantlab1243f2015-06-29 23:03:47 +00004615/// ParseDIModule:
4616/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4617/// includePath: "/usr/include", isysroot: "/")
4618bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4619#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4620 REQUIRED(scope, MDField, ); \
4621 REQUIRED(name, MDStringField, ); \
4622 OPTIONAL(configMacros, MDStringField, ); \
4623 OPTIONAL(includePath, MDStringField, ); \
4624 OPTIONAL(isysroot, MDStringField, );
4625 PARSE_MD_FIELDS();
4626#undef VISIT_MD_FIELDS
4627
4628 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4629 configMacros.Val, includePath.Val, isysroot.Val));
4630 return false;
4631}
4632
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004633/// ParseDITemplateTypeParameter:
4634/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4635bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004636#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004637 OPTIONAL(name, MDStringField, ); \
4638 REQUIRED(type, MDField, );
4639 PARSE_MD_FIELDS();
4640#undef VISIT_MD_FIELDS
4641
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004642 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004643 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004644 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004645}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004646
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004647/// ParseDITemplateValueParameter:
4648/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004649/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004650bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004651#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004652 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004653 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004654 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004655 REQUIRED(value, MDField, );
4656 PARSE_MD_FIELDS();
4657#undef VISIT_MD_FIELDS
4658
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004659 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004660 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004661 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004662}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004663
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004664/// ParseDIGlobalVariable:
4665/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004666/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004667/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004668bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004669#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004670 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004671 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004672 OPTIONAL(linkageName, MDStringField, ); \
4673 OPTIONAL(file, MDField, ); \
4674 OPTIONAL(line, LineField, ); \
4675 OPTIONAL(type, MDField, ); \
4676 OPTIONAL(isLocal, MDBoolField, ); \
4677 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004678 OPTIONAL(declaration, MDField, ); \
4679 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004680 PARSE_MD_FIELDS();
4681#undef VISIT_MD_FIELDS
4682
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004683 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004684 (Context, scope.Val, name.Val, linkageName.Val,
4685 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004686 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004687 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004688}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004689
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004690/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004691/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004692/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4693/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004694/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004695/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4696/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004697bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004698#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004699 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004700 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004701 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004702 OPTIONAL(file, MDField, ); \
4703 OPTIONAL(line, LineField, ); \
4704 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004705 OPTIONAL(flags, DIFlagField, ); \
4706 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004707 PARSE_MD_FIELDS();
4708#undef VISIT_MD_FIELDS
4709
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004710 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004711 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004712 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004713 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004714}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004715
Shiva Chen2c864552018-05-09 02:40:45 +00004716/// ParseDILabel:
4717/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4718bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4719#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4720 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4721 REQUIRED(name, MDStringField, ); \
4722 REQUIRED(file, MDField, ); \
4723 REQUIRED(line, LineField, );
4724 PARSE_MD_FIELDS();
4725#undef VISIT_MD_FIELDS
4726
4727 Result = GET_OR_DISTINCT(DILabel,
4728 (Context, scope.Val, name.Val, file.Val, line.Val));
4729 return false;
4730}
4731
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004732/// ParseDIExpression:
4733/// ::= !DIExpression(0, 7, -1)
4734bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004735 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4736 Lex.Lex();
4737
4738 if (ParseToken(lltok::lparen, "expected '(' here"))
4739 return true;
4740
4741 SmallVector<uint64_t, 8> Elements;
4742 if (Lex.getKind() != lltok::rparen)
4743 do {
4744 if (Lex.getKind() == lltok::DwarfOp) {
4745 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4746 Lex.Lex();
4747 Elements.push_back(Op);
4748 continue;
4749 }
4750 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4751 }
4752
4753 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4754 return TokError("expected unsigned integer");
4755
4756 auto &U = Lex.getAPSIntVal();
4757 if (U.ugt(UINT64_MAX))
4758 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4759 Elements.push_back(U.getZExtValue());
4760 Lex.Lex();
4761 } while (EatIfPresent(lltok::comma));
4762
4763 if (ParseToken(lltok::rparen, "expected ')' here"))
4764 return true;
4765
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004766 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004767 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004768}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004769
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004770/// ParseDIGlobalVariableExpression:
4771/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4772bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4773 bool IsDistinct) {
4774#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4775 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004776 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004777 PARSE_MD_FIELDS();
4778#undef VISIT_MD_FIELDS
4779
4780 Result =
4781 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4782 return false;
4783}
4784
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004785/// ParseDIObjCProperty:
4786/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004787/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004788bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004789#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004790 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004791 OPTIONAL(file, MDField, ); \
4792 OPTIONAL(line, LineField, ); \
4793 OPTIONAL(setter, MDStringField, ); \
4794 OPTIONAL(getter, MDStringField, ); \
4795 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4796 OPTIONAL(type, MDField, );
4797 PARSE_MD_FIELDS();
4798#undef VISIT_MD_FIELDS
4799
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004800 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004801 (Context, name.Val, file.Val, line.Val, setter.Val,
4802 getter.Val, attributes.Val, type.Val));
4803 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004804}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004805
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004806/// ParseDIImportedEntity:
4807/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004808/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004809bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004810#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4811 REQUIRED(tag, DwarfTagField, ); \
4812 REQUIRED(scope, MDField, ); \
4813 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004814 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004815 OPTIONAL(line, LineField, ); \
4816 OPTIONAL(name, MDStringField, );
4817 PARSE_MD_FIELDS();
4818#undef VISIT_MD_FIELDS
4819
Adrian Prantld63bfd22017-07-19 00:09:54 +00004820 Result = GET_OR_DISTINCT(
4821 DIImportedEntity,
4822 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004823 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004824}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004825
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004826#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004827#undef NOP_FIELD
4828#undef REQUIRE_FIELD
4829#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004830
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004831/// ParseMetadataAsValue
4832/// ::= metadata i32 %local
4833/// ::= metadata i32 @global
4834/// ::= metadata i32 7
4835/// ::= metadata !0
4836/// ::= metadata !{...}
4837/// ::= metadata !"string"
4838bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4839 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004840 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004841 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004842 return true;
4843
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004844 V = MetadataAsValue::get(Context, MD);
4845 return false;
4846}
4847
4848/// ParseValueAsMetadata
4849/// ::= i32 %local
4850/// ::= i32 @global
4851/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004852bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4853 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004854 Type *Ty;
4855 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004856 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004857 return true;
4858 if (Ty->isMetadataTy())
4859 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4860
4861 Value *V;
4862 if (ParseValue(Ty, V, PFS))
4863 return true;
4864
4865 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004866 return false;
4867}
4868
4869/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004870/// ::= i32 %local
4871/// ::= i32 @global
4872/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004873/// ::= !42
4874/// ::= !{...}
4875/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004876/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004877bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004878 if (Lex.getKind() == lltok::MetadataVar) {
4879 MDNode *N;
4880 if (ParseSpecializedMDNode(N))
4881 return true;
4882 MD = N;
4883 return false;
4884 }
4885
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004886 // ValueAsMetadata:
4887 // <type> <value>
4888 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004889 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004890
4891 // '!'.
4892 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4893 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004894
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004895 // MDString:
4896 // ::= '!' STRINGCONSTANT
4897 if (Lex.getKind() == lltok::StringConstant) {
4898 MDString *S;
4899 if (ParseMDString(S))
4900 return true;
4901 MD = S;
4902 return false;
4903 }
4904
Dan Gohman8939ba332010-07-14 18:26:50 +00004905 // MDNode:
4906 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004907 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004908 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004909 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004910 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004911 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004912 return false;
4913}
4914
Victor Hernandez9d75c962010-01-11 22:31:58 +00004915//===----------------------------------------------------------------------===//
4916// Function Parsing.
4917//===----------------------------------------------------------------------===//
4918
Chris Lattner229907c2011-07-18 04:54:35 +00004919bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004920 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004921 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004923
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004926 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004927 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004928 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004930 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004931 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004932 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004933 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004934 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004935 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004936 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4937 (ID.UIntVal >> 1) & 1,
4938 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004939 return false;
4940 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 case ValID::t_GlobalName:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00004942 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004943 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004944 case ValID::t_GlobalID:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00004945 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004946 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004948 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004949 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004950 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004951 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004952 return false;
4953 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004954 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004955 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4956 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004957
Dan Gohman518cda42011-12-17 00:04:22 +00004958 // The lexer has no type info, so builds all half, float, and double FP
4959 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004960 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004962 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004963 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004964 &Ignored);
4965 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004966 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004967 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004969 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004970
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004971 if (V->getType() != Ty)
4972 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004973 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004974
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 return false;
4976 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004977 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004978 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004979 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004980 return false;
4981 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004982 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004983 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004984 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004985 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004987 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004988 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004989 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004990 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004991 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004993 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004994 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004996 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004998 case ValID::t_None:
4999 if (!Ty->isTokenTy())
5000 return Error(ID.Loc, "invalid type for none constant");
5001 V = Constant::getNullValue(Ty);
5002 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00005004 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005005 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005006
Chris Lattnerac161bf2009-01-02 07:01:27 +00005007 V = ID.ConstantVal;
5008 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005009 case ValID::t_ConstantStruct:
5010 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005011 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005012 if (ST->getNumElements() != ID.UIntVal)
5013 return Error(ID.Loc,
5014 "initializer with struct type has wrong # elements");
5015 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5016 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005017
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005018 // Verify that the elements are compatible with the structtype.
5019 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5020 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5021 return Error(ID.Loc, "element " + Twine(i) +
5022 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005023
David Blaikieadbda4b2015-08-03 20:08:41 +00005024 V = ConstantStruct::get(
5025 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005026 } else
5027 return Error(ID.Loc, "constant expression type mismatch");
5028 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005029 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005030 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005032
Alex Lorenzd2255952015-07-17 22:07:03 +00005033bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5034 C = nullptr;
5035 ValID ID;
5036 auto Loc = Lex.getLoc();
5037 if (ParseValID(ID, /*PFS=*/nullptr))
5038 return true;
5039 switch (ID.Kind) {
5040 case ValID::t_APSInt:
5041 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005042 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005043 case ValID::t_Constant:
5044 case ValID::t_ConstantStruct:
5045 case ValID::t_PackedConstantStruct: {
5046 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005047 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005048 return true;
5049 assert(isa<Constant>(V) && "Expected a constant value");
5050 C = cast<Constant>(V);
5051 return false;
5052 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005053 case ValID::t_Null:
5054 C = Constant::getNullValue(Ty);
5055 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005056 default:
5057 return Error(Loc, "expected a constant value");
5058 }
5059}
5060
David Majnemer8a1c45d2015-12-12 05:38:55 +00005061bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005062 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005064 return ParseValID(ID, PFS) ||
5065 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005066}
5067
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005068bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005069 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005070 return ParseType(Ty) ||
5071 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072}
5073
Chris Lattner3ed871f2009-10-27 19:13:16 +00005074bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5075 PerFunctionState &PFS) {
5076 Value *V;
5077 Loc = Lex.getLoc();
5078 if (ParseTypeAndValue(V, PFS)) return true;
5079 if (!isa<BasicBlock>(V))
5080 return Error(Loc, "expected a basic block");
5081 BB = cast<BasicBlock>(V);
5082 return false;
5083}
5084
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005086/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5087/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005088/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5089/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005090bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5091 // Parse the linkage.
5092 LocTy LinkageLoc = Lex.getLoc();
5093 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005094 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005095 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005096 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005097 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005098 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005099 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005100 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005102 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5103 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005104 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005105 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 return true;
5107
5108 // Verify that the linkage is ok.
5109 switch ((GlobalValue::LinkageTypes)Linkage) {
5110 case GlobalValue::ExternalLinkage:
5111 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005112 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 if (isDefine)
5114 return Error(LinkageLoc, "invalid linkage for function definition");
5115 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005116 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005118 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005119 case GlobalValue::LinkOnceAnyLinkage:
5120 case GlobalValue::LinkOnceODRLinkage:
5121 case GlobalValue::WeakAnyLinkage:
5122 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005123 if (!isDefine)
5124 return Error(LinkageLoc, "invalid linkage for function declaration");
5125 break;
5126 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005127 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005128 return Error(LinkageLoc, "invalid function linkage type");
5129 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005130
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005131 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5132 return Error(LinkageLoc,
5133 "symbol with local linkage must have default visibility");
5134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005135 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005136 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005137
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005139
5140 std::string FunctionName;
5141 if (Lex.getKind() == lltok::GlobalVar) {
5142 FunctionName = Lex.getStrVal();
5143 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5144 unsigned NameID = Lex.getUIntVal();
5145
5146 if (NameID != NumberedVals.size())
5147 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005148 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005149 } else {
5150 return TokError("expected function name");
5151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
Chris Lattner3822f632009-01-02 08:05:26 +00005153 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005154
Chris Lattner3822f632009-01-02 08:05:26 +00005155 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005156 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005157
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005158 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005160 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005161 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005162 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005164 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005165 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005166 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005167 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005168 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005169 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005170 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005171 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005173 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005174 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005175 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005176 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005177 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005178 (EatIfPresent(lltok::kw_section) &&
5179 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005180 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005181 ParseOptionalAlignment(Alignment) ||
5182 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005183 ParseStringConstant(GC)) ||
5184 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005185 ParseGlobalTypeAndValue(Prefix)) ||
5186 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005187 ParseGlobalTypeAndValue(Prologue)) ||
5188 (EatIfPresent(lltok::kw_personality) &&
5189 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005190 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191
Michael Gottesman41748d72013-06-27 00:25:01 +00005192 if (FuncAttrs.contains(Attribute::Builtin))
5193 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005194
Chris Lattnerac161bf2009-01-02 07:01:27 +00005195 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005196 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005197 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005198 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005200
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 // Okay, if we got here, the function is syntactically valid. Convert types
5202 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005203 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005204 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005205
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005207 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005208 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 }
5210
Reid Kleckner7f720332017-04-13 00:58:09 +00005211 AttributeList PAL =
5212 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5213 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005214
Bill Wendling749a43d2012-12-30 13:50:49 +00005215 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005216 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5217
Chris Lattner229907c2011-07-18 04:54:35 +00005218 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005219 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005220 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221
Craig Topper2617dcc2014-04-15 06:32:26 +00005222 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223 if (!FunctionName.empty()) {
5224 // If this was a definition of a forward reference, remove the definition
5225 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005226 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005227 if (FRVI != ForwardRefVals.end()) {
5228 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005229 if (!Fn)
5230 return Error(FRVI->second.second, "invalid forward reference to "
5231 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005232 if (Fn->getType() != PFT)
5233 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005234 "function '" + FunctionName + "' with wrong type: "
5235 "expected '" + getTypeString(PFT) + "' but was '" +
5236 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 ForwardRefVals.erase(FRVI);
5238 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005239 // Reject redefinitions.
5240 return Error(NameLoc, "invalid redefinition of function '" +
5241 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005242 } else if (M->getNamedValue(FunctionName)) {
5243 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005245
Dan Gohman399d6ae2009-08-29 23:37:49 +00005246 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 // If this is a definition of a forward referenced function, make sure the
5248 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005249 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005250 if (I != ForwardRefValIDs.end()) {
5251 Fn = cast<Function>(I->second.first);
5252 if (Fn->getType() != PFT)
5253 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005254 Twine(NumberedVals.size()) + "' disagree: "
5255 "expected '" + getTypeString(PFT) + "' but was '" +
5256 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 ForwardRefValIDs.erase(I);
5258 }
5259 }
5260
Craig Topper2617dcc2014-04-15 06:32:26 +00005261 if (!Fn)
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005262 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5263 FunctionName, M);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 else // Move the forward-reference to the correct spot in the module.
5265 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5266
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005267 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5268
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269 if (FunctionName.empty())
5270 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005271
Chris Lattnerac161bf2009-01-02 07:01:27 +00005272 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005273 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005275 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 Fn->setCallingConv(CC);
5277 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005278 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005279 Fn->setAlignment(Alignment);
5280 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005281 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005282 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005283 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005284 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005285 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005286 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005287
Chris Lattnerac161bf2009-01-02 07:01:27 +00005288 // Add all of the arguments we parsed to the function.
5289 Function::arg_iterator ArgIt = Fn->arg_begin();
5290 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5291 // If the argument has a name, insert it into the argument symbol table.
5292 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005293
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 // Set the name, if it conflicted, it will be auto-renamed.
5295 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005296
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005297 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5299 ArgList[i].Name + "'");
5300 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005301
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005302 if (isDefine)
5303 return false;
5304
Robin Morisset039781e2014-08-29 21:53:01 +00005305 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005306 ValID ID;
5307 if (FunctionName.empty()) {
5308 ID.Kind = ValID::t_GlobalID;
5309 ID.UIntVal = NumberedVals.size() - 1;
5310 } else {
5311 ID.Kind = ValID::t_GlobalName;
5312 ID.StrVal = FunctionName;
5313 }
5314 auto Blocks = ForwardRefBlockAddresses.find(ID);
5315 if (Blocks != ForwardRefBlockAddresses.end())
5316 return Error(Blocks->first.Loc,
5317 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005318 return false;
5319}
5320
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005321bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5322 ValID ID;
5323 if (FunctionNumber == -1) {
5324 ID.Kind = ValID::t_GlobalName;
5325 ID.StrVal = F.getName();
5326 } else {
5327 ID.Kind = ValID::t_GlobalID;
5328 ID.UIntVal = FunctionNumber;
5329 }
5330
5331 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5332 if (Blocks == P.ForwardRefBlockAddresses.end())
5333 return false;
5334
5335 for (const auto &I : Blocks->second) {
5336 const ValID &BBID = I.first;
5337 GlobalValue *GV = I.second;
5338
5339 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5340 "Expected local id or name");
5341 BasicBlock *BB;
5342 if (BBID.Kind == ValID::t_LocalName)
5343 BB = GetBB(BBID.StrVal, BBID.Loc);
5344 else
5345 BB = GetBB(BBID.UIntVal, BBID.Loc);
5346 if (!BB)
5347 return P.Error(BBID.Loc, "referenced value is not a basic block");
5348
5349 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5350 GV->eraseFromParent();
5351 }
5352
5353 P.ForwardRefBlockAddresses.erase(Blocks);
5354 return false;
5355}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005356
5357/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005358/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005360 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005361 return TokError("expected '{' in function body");
5362 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005363
Chris Lattner3432c622009-10-28 03:39:23 +00005364 int FunctionNumber = -1;
5365 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005366
Chris Lattner3432c622009-10-28 03:39:23 +00005367 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005368
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005369 // Resolve block addresses and allow basic blocks to be forward-declared
5370 // within this function.
5371 if (PFS.resolveForwardRefBlockAddresses())
5372 return true;
5373 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5374
Chris Lattnerbbddd962010-01-09 19:20:07 +00005375 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005376 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005377 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005378
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005379 while (Lex.getKind() != lltok::rbrace &&
5380 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005382
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005383 while (Lex.getKind() != lltok::rbrace)
5384 if (ParseUseListOrder(&PFS))
5385 return true;
5386
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 // Eat the }.
5388 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005389
Chris Lattnerac161bf2009-01-02 07:01:27 +00005390 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005391 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005392}
5393
5394/// ParseBasicBlock
5395/// ::= LabelStr? Instruction*
5396bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5397 // If this basic block starts out with a name, remember it.
5398 std::string Name;
5399 LocTy NameLoc = Lex.getLoc();
5400 if (Lex.getKind() == lltok::LabelStr) {
5401 Name = Lex.getStrVal();
5402 Lex.Lex();
5403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005404
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005406 if (!BB)
5407 return Error(NameLoc,
5408 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005409
Chris Lattnerac161bf2009-01-02 07:01:27 +00005410 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005411
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412 // Parse the instructions in this block until we get a terminator.
5413 Instruction *Inst;
5414 do {
5415 // This instruction may have three possibilities for a name: a) none
5416 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5417 LocTy NameLoc = Lex.getLoc();
5418 int NameID = -1;
5419 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005420
Chris Lattnerac161bf2009-01-02 07:01:27 +00005421 if (Lex.getKind() == lltok::LocalVarID) {
5422 NameID = Lex.getUIntVal();
5423 Lex.Lex();
5424 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5425 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005426 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005427 NameStr = Lex.getStrVal();
5428 Lex.Lex();
5429 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5430 return true;
5431 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005432
Chris Lattner77b89dc2009-12-30 05:23:43 +00005433 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005434 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005435 case InstError: return true;
5436 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005437 BB->getInstList().push_back(Inst);
5438
Chris Lattner77b89dc2009-12-30 05:23:43 +00005439 // With a normal result, we check to see if the instruction is followed by
5440 // a comma and metadata.
5441 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005442 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005443 return true;
5444 break;
5445 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005446 BB->getInstList().push_back(Inst);
5447
Chris Lattner77b89dc2009-12-30 05:23:43 +00005448 // If the instruction parser ate an extra comma at the end of it, it
5449 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005450 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005451 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005452 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005453 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005454
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 // Set the name on the instruction.
5456 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005457 } while (!Inst->isTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005458
Chris Lattnerac161bf2009-01-02 07:01:27 +00005459 return false;
5460}
5461
5462//===----------------------------------------------------------------------===//
5463// Instruction Parsing.
5464//===----------------------------------------------------------------------===//
5465
5466/// ParseInstruction - Parse one of the many different instructions.
5467///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005468int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5469 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005470 lltok::Kind Token = Lex.getKind();
5471 if (Token == lltok::Eof)
5472 return TokError("found end of file when expecting more instructions");
5473 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005474 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005475 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005476
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 switch (Token) {
5478 default: return Error(Loc, "expected instruction opcode");
5479 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005480 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005481 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5482 case lltok::kw_br: return ParseBr(Inst, PFS);
5483 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005484 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005485 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005486 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005487 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5488 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005489 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5490 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005491 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005492 // Binary Operators.
5493 case lltok::kw_add:
5494 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005495 case lltok::kw_mul:
5496 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005497 bool NUW = EatIfPresent(lltok::kw_nuw);
5498 bool NSW = EatIfPresent(lltok::kw_nsw);
5499 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005500
Chris Lattnera676c0f2011-02-07 16:40:21 +00005501 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005502
Chris Lattnera676c0f2011-02-07 16:40:21 +00005503 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5504 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5505 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005506 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005507 case lltok::kw_fadd:
5508 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005509 case lltok::kw_fmul:
5510 case lltok::kw_fdiv:
5511 case lltok::kw_frem: {
5512 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5513 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5514 if (Res != 0)
5515 return Res;
5516 if (FMF.any())
5517 Inst->setFastMathFlags(FMF);
5518 return 0;
5519 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005520
Chris Lattner35315d02011-02-06 21:44:57 +00005521 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005522 case lltok::kw_udiv:
5523 case lltok::kw_lshr:
5524 case lltok::kw_ashr: {
5525 bool Exact = EatIfPresent(lltok::kw_exact);
5526
5527 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5528 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5529 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005530 }
5531
Chris Lattnerac161bf2009-01-02 07:01:27 +00005532 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005533 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005534 case lltok::kw_and:
5535 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005536 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005537 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5538 case lltok::kw_fcmp: {
5539 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5540 int Res = ParseCompare(Inst, PFS, KeywordVal);
5541 if (Res != 0)
5542 return Res;
5543 if (FMF.any())
5544 Inst->setFastMathFlags(FMF);
5545 return 0;
5546 }
5547
Chris Lattnerac161bf2009-01-02 07:01:27 +00005548 // Casts.
5549 case lltok::kw_trunc:
5550 case lltok::kw_zext:
5551 case lltok::kw_sext:
5552 case lltok::kw_fptrunc:
5553 case lltok::kw_fpext:
5554 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005555 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005556 case lltok::kw_uitofp:
5557 case lltok::kw_sitofp:
5558 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005559 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005560 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005561 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562 // Other.
5563 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005564 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005565 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5566 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5567 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5568 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005569 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005570 // Call.
5571 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5572 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5573 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005574 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005575 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005576 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005577 case lltok::kw_load: return ParseLoad(Inst, PFS);
5578 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005579 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5580 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005581 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5583 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5584 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5585 }
5586}
5587
5588/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5589bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005590 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005591 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005592 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005593 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5594 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5595 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5596 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5597 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5598 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5599 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5600 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5601 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5602 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5603 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5604 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5605 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5606 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5607 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5608 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5609 }
5610 } else {
5611 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005612 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005613 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5614 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5615 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5616 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5617 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5618 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5619 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5620 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5621 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5622 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5623 }
5624 }
5625 Lex.Lex();
5626 return false;
5627}
5628
5629//===----------------------------------------------------------------------===//
5630// Terminator Instructions.
5631//===----------------------------------------------------------------------===//
5632
5633/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005634/// ::= 'ret' void (',' !dbg, !1)*
5635/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005636bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005637 PerFunctionState &PFS) {
5638 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005639 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005640 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005641
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005642 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005643
Chris Lattnerfdd87902009-10-05 05:54:46 +00005644 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005645 if (!ResType->isVoidTy())
5646 return Error(TypeLoc, "value doesn't match function result type '" +
5647 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005648
Owen Anderson55f1c092009-08-13 21:58:54 +00005649 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005650 return false;
5651 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005652
Chris Lattnerac161bf2009-01-02 07:01:27 +00005653 Value *RV;
5654 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005656 if (ResType != RV->getType())
5657 return Error(TypeLoc, "value doesn't match function result type '" +
5658 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005659
Owen Anderson55f1c092009-08-13 21:58:54 +00005660 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005661 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005662}
5663
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664/// ParseBr
5665/// ::= 'br' TypeAndValue
5666/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5667bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5668 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005669 Value *Op0;
5670 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005671 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005672
Chris Lattnerac161bf2009-01-02 07:01:27 +00005673 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5674 Inst = BranchInst::Create(BB);
5675 return false;
5676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005677
Owen Anderson55f1c092009-08-13 21:58:54 +00005678 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005679 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005680
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005682 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005683 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005684 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005685 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005686
Chris Lattner3ed871f2009-10-27 19:13:16 +00005687 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005688 return false;
5689}
5690
5691/// ParseSwitch
5692/// Instruction
5693/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5694/// JumpTable
5695/// ::= (TypeAndValue ',' TypeAndValue)*
5696bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5697 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005698 Value *Cond;
5699 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5701 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005702 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005703 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5704 return true;
5705
Duncan Sands19d0b472010-02-16 11:11:14 +00005706 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005707 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005708
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 // Parse the jump table pairs.
5710 SmallPtrSet<Value*, 32> SeenCases;
5711 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5712 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005713 Value *Constant;
5714 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005715
Chris Lattnerac161bf2009-01-02 07:01:27 +00005716 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5717 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005718 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005720
David Blaikie70573dc2014-11-19 07:49:26 +00005721 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722 return Error(CondLoc, "duplicate case value in switch");
5723 if (!isa<ConstantInt>(Constant))
5724 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005725
Chris Lattner3ed871f2009-10-27 19:13:16 +00005726 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005727 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005728
Chris Lattnerac161bf2009-01-02 07:01:27 +00005729 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005730
Chris Lattner3ed871f2009-10-27 19:13:16 +00005731 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005732 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5733 SI->addCase(Table[i].first, Table[i].second);
5734 Inst = SI;
5735 return false;
5736}
5737
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005738/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005739/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005740/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5741bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005742 LocTy AddrLoc;
5743 Value *Address;
5744 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005745 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5746 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005747 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005748
Duncan Sands19d0b472010-02-16 11:11:14 +00005749 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005750 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005751
Chris Lattner3ed871f2009-10-27 19:13:16 +00005752 // Parse the destination list.
5753 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005754
Chris Lattner3ed871f2009-10-27 19:13:16 +00005755 if (Lex.getKind() != lltok::rsquare) {
5756 BasicBlock *DestBB;
5757 if (ParseTypeAndBasicBlock(DestBB, PFS))
5758 return true;
5759 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005760
Chris Lattner3ed871f2009-10-27 19:13:16 +00005761 while (EatIfPresent(lltok::comma)) {
5762 if (ParseTypeAndBasicBlock(DestBB, PFS))
5763 return true;
5764 DestList.push_back(DestBB);
5765 }
5766 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005767
Chris Lattner3ed871f2009-10-27 19:13:16 +00005768 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5769 return true;
5770
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005771 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005772 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5773 IBI->addDestination(DestList[i]);
5774 Inst = IBI;
5775 return false;
5776}
5777
Chris Lattnerac161bf2009-01-02 07:01:27 +00005778/// ParseInvoke
5779/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5780/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5781bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5782 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005783 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005784 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005785 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005786 unsigned CC;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005787 unsigned InvokeAddrSpace;
Craig Topper2617dcc2014-04-15 06:32:26 +00005788 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 LocTy RetTypeLoc;
5790 ValID CalleeID;
5791 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005792 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005793
Chris Lattner3ed871f2009-10-27 19:13:16 +00005794 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005795 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005796 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005797 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005798 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005799 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5800 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005801 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005802 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005803 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005804 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005805 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005807
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 // If RetType is a non-function pointer type, then this is the short syntax
5809 // for the call, which means that RetType is just the return type. Infer the
5810 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005811 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5812 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005814 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005815 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5816 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005817
Chris Lattnerac161bf2009-01-02 07:01:27 +00005818 if (!FunctionType::isValidReturnType(RetType))
5819 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005820
Owen Anderson4056ca92009-07-29 22:17:13 +00005821 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005823
David Blaikie41ba2b42015-07-27 23:32:19 +00005824 CalleeID.FTy = Ty;
5825
Chris Lattnerac161bf2009-01-02 07:01:27 +00005826 // Look up the callee.
5827 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005828 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5829 Callee, &PFS, /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005830 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005831
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005832 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005833 SmallVector<Value *, 8> Args;
5834 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005835
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 // Loop through FunctionType's arguments and ensure they are specified
5837 // correctly. Also, gather any parameter attributes.
5838 FunctionType::param_iterator I = Ty->param_begin();
5839 FunctionType::param_iterator E = Ty->param_end();
5840 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005841 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 if (I != E) {
5843 ExpectedTy = *I++;
5844 } else if (!Ty->isVarArg()) {
5845 return Error(ArgList[i].Loc, "too many arguments specified");
5846 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005847
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5849 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005850 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005851 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005852 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005854
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 if (I != E)
5856 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005857
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005858 if (FnAttrs.hasAlignmentAttr())
5859 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005860
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005861 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005862 AttributeList PAL =
5863 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5864 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005865
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005866 InvokeInst *II =
5867 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005868 II->setCallingConv(CC);
5869 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005870 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005871 Inst = II;
5872 return false;
5873}
5874
Bill Wendlingf891bf82011-07-31 06:30:59 +00005875/// ParseResume
5876/// ::= 'resume' TypeAndValue
5877bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5878 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005879 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5880 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005881
Bill Wendlingf891bf82011-07-31 06:30:59 +00005882 ResumeInst *RI = ResumeInst::Create(Exn);
5883 Inst = RI;
5884 return false;
5885}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005886
David Majnemer654e1302015-07-31 17:58:14 +00005887bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5888 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005889 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005890 return true;
5891
5892 while (Lex.getKind() != lltok::rsquare) {
5893 // If this isn't the first argument, we need a comma.
5894 if (!Args.empty() &&
5895 ParseToken(lltok::comma, "expected ',' in argument list"))
5896 return true;
5897
5898 // Parse the argument.
5899 LocTy ArgLoc;
5900 Type *ArgTy = nullptr;
5901 if (ParseType(ArgTy, ArgLoc))
5902 return true;
5903
5904 Value *V;
5905 if (ArgTy->isMetadataTy()) {
5906 if (ParseMetadataAsValue(V, PFS))
5907 return true;
5908 } else {
5909 if (ParseValue(ArgTy, V, PFS))
5910 return true;
5911 }
5912 Args.push_back(V);
5913 }
5914
5915 Lex.Lex(); // Lex the ']'.
5916 return false;
5917}
5918
5919/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005920/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005921bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005922 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005923
David Majnemer8a1c45d2015-12-12 05:38:55 +00005924 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5925 return true;
5926
5927 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005928 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005929
5930 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5931 return true;
5932
5933 BasicBlock *UnwindBB = nullptr;
5934 if (Lex.getKind() == lltok::kw_to) {
5935 Lex.Lex();
5936 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5937 return true;
5938 } else {
5939 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5940 return true;
5941 }
5942 }
5943
David Majnemer8a1c45d2015-12-12 05:38:55 +00005944 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005945 return false;
5946}
5947
5948/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005949/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005950bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005951 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005952
David Majnemer8a1c45d2015-12-12 05:38:55 +00005953 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5954 return true;
5955
5956 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005957 return true;
5958
David Majnemer0bc0eef2015-08-15 02:46:08 +00005959 BasicBlock *BB;
5960 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5961 ParseTypeAndBasicBlock(BB, PFS))
5962 return true;
5963
David Majnemer8a1c45d2015-12-12 05:38:55 +00005964 Inst = CatchReturnInst::Create(CatchPad, BB);
5965 return false;
5966}
5967
5968/// ParseCatchSwitch
5969/// ::= 'catchswitch' within Parent
5970bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5971 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005972
5973 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5974 return true;
5975
5976 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5977 Lex.getKind() != lltok::LocalVarID)
5978 return TokError("expected scope value for catchswitch");
5979
5980 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5981 return true;
5982
5983 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5984 return true;
5985
5986 SmallVector<BasicBlock *, 32> Table;
5987 do {
5988 BasicBlock *DestBB;
5989 if (ParseTypeAndBasicBlock(DestBB, PFS))
5990 return true;
5991 Table.push_back(DestBB);
5992 } while (EatIfPresent(lltok::comma));
5993
5994 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5995 return true;
5996
5997 if (ParseToken(lltok::kw_unwind,
5998 "expected 'unwind' after catchswitch scope"))
5999 return true;
6000
6001 BasicBlock *UnwindBB = nullptr;
6002 if (EatIfPresent(lltok::kw_to)) {
6003 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6004 return true;
6005 } else {
6006 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6007 return true;
6008 }
6009
6010 auto *CatchSwitch =
6011 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6012 for (BasicBlock *DestBB : Table)
6013 CatchSwitch->addHandler(DestBB);
6014 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006015 return false;
6016}
6017
6018/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006019/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006020bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006021 Value *CatchSwitch = nullptr;
6022
6023 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6024 return true;
6025
6026 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6027 return TokError("expected scope value for catchpad");
6028
6029 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6030 return true;
6031
David Majnemer654e1302015-07-31 17:58:14 +00006032 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006033 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006034 return true;
6035
David Majnemer8a1c45d2015-12-12 05:38:55 +00006036 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006037 return false;
6038}
6039
David Majnemer654e1302015-07-31 17:58:14 +00006040/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006041/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006042bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006043 Value *ParentPad = nullptr;
6044
6045 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6046 return true;
6047
6048 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6049 Lex.getKind() != lltok::LocalVarID)
6050 return TokError("expected scope value for cleanuppad");
6051
6052 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6053 return true;
6054
David Majnemer654e1302015-07-31 17:58:14 +00006055 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006056 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006057 return true;
6058
David Majnemer8a1c45d2015-12-12 05:38:55 +00006059 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006060 return false;
6061}
6062
Chris Lattnerac161bf2009-01-02 07:01:27 +00006063//===----------------------------------------------------------------------===//
6064// Binary Operators.
6065//===----------------------------------------------------------------------===//
6066
6067/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006068/// ::= ArithmeticOps TypeAndValue ',' Value
6069///
6070/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6071/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006072bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006073 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006074 LocTy Loc; Value *LHS, *RHS;
6075 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6076 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6077 ParseValue(LHS->getType(), RHS, PFS))
6078 return true;
6079
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006080 bool Valid;
6081 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00006082 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006083 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00006084 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6085 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006086 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00006087 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6088 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006090
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006091 if (!Valid)
6092 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006093
Chris Lattnerac161bf2009-01-02 07:01:27 +00006094 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6095 return false;
6096}
6097
6098/// ParseLogical
6099/// ::= ArithmeticOps TypeAndValue ',' Value {
6100bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6101 unsigned Opc) {
6102 LocTy Loc; Value *LHS, *RHS;
6103 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6104 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6105 ParseValue(LHS->getType(), RHS, PFS))
6106 return true;
6107
Duncan Sands9dff9be2010-02-15 16:12:20 +00006108 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006109 return Error(Loc,"instruction requires integer or integer vector operands");
6110
6111 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6112 return false;
6113}
6114
Chris Lattnerac161bf2009-01-02 07:01:27 +00006115/// ParseCompare
6116/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6117/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006118bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6119 unsigned Opc) {
6120 // Parse the integer/fp comparison predicate.
6121 LocTy Loc;
6122 unsigned Pred;
6123 Value *LHS, *RHS;
6124 if (ParseCmpPredicate(Pred, Opc) ||
6125 ParseTypeAndValue(LHS, Loc, PFS) ||
6126 ParseToken(lltok::comma, "expected ',' after compare value") ||
6127 ParseValue(LHS->getType(), RHS, PFS))
6128 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006129
Chris Lattnerac161bf2009-01-02 07:01:27 +00006130 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006131 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006133 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006134 } else {
6135 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006136 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006137 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006138 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006139 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006140 }
6141 return false;
6142}
6143
6144//===----------------------------------------------------------------------===//
6145// Other Instructions.
6146//===----------------------------------------------------------------------===//
6147
6148
6149/// ParseCast
6150/// ::= CastOpc TypeAndValue 'to' Type
6151bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6152 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006153 LocTy Loc;
6154 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006155 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006156 if (ParseTypeAndValue(Op, Loc, PFS) ||
6157 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6158 ParseType(DestTy))
6159 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006160
Chris Lattner89d856e2009-03-01 00:53:13 +00006161 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6162 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006163 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006164 getTypeString(Op->getType()) + "' to '" +
6165 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006166 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006167 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6168 return false;
6169}
6170
6171/// ParseSelect
6172/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6173bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6174 LocTy Loc;
6175 Value *Op0, *Op1, *Op2;
6176 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6177 ParseToken(lltok::comma, "expected ',' after select condition") ||
6178 ParseTypeAndValue(Op1, PFS) ||
6179 ParseToken(lltok::comma, "expected ',' after select value") ||
6180 ParseTypeAndValue(Op2, PFS))
6181 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006182
Chris Lattnerac161bf2009-01-02 07:01:27 +00006183 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6184 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006185
Chris Lattnerac161bf2009-01-02 07:01:27 +00006186 Inst = SelectInst::Create(Op0, Op1, Op2);
6187 return false;
6188}
6189
Chris Lattnerb55ab542009-01-05 08:18:44 +00006190/// ParseVA_Arg
6191/// ::= 'va_arg' TypeAndValue ',' Type
6192bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006193 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006194 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006195 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196 if (ParseTypeAndValue(Op, PFS) ||
6197 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006198 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006199 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006200
Chris Lattnerb55ab542009-01-05 08:18:44 +00006201 if (!EltTy->isFirstClassType())
6202 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006203
6204 Inst = new VAArgInst(Op, EltTy);
6205 return false;
6206}
6207
6208/// ParseExtractElement
6209/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6210bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6211 LocTy Loc;
6212 Value *Op0, *Op1;
6213 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6214 ParseToken(lltok::comma, "expected ',' after extract value") ||
6215 ParseTypeAndValue(Op1, PFS))
6216 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006217
Chris Lattnerac161bf2009-01-02 07:01:27 +00006218 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6219 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006220
Eric Christopherc9742252009-07-25 02:28:41 +00006221 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006222 return false;
6223}
6224
6225/// ParseInsertElement
6226/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6227bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6228 LocTy Loc;
6229 Value *Op0, *Op1, *Op2;
6230 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6231 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6232 ParseTypeAndValue(Op1, PFS) ||
6233 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6234 ParseTypeAndValue(Op2, PFS))
6235 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006236
Chris Lattnerac161bf2009-01-02 07:01:27 +00006237 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006238 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006239
Chris Lattnerac161bf2009-01-02 07:01:27 +00006240 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6241 return false;
6242}
6243
6244/// ParseShuffleVector
6245/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6246bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6247 LocTy Loc;
6248 Value *Op0, *Op1, *Op2;
6249 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6250 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6251 ParseTypeAndValue(Op1, PFS) ||
6252 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6253 ParseTypeAndValue(Op2, PFS))
6254 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006255
Chris Lattnerac161bf2009-01-02 07:01:27 +00006256 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006257 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006258
Chris Lattnerac161bf2009-01-02 07:01:27 +00006259 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6260 return false;
6261}
6262
6263/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006264/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006265int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006266 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006267 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006268
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006269 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006270 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6271 ParseValue(Ty, Op0, PFS) ||
6272 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006273 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006274 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6275 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006276
Chris Lattnerf4f03422009-12-30 05:27:33 +00006277 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006278 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006279
6280 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006281 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006282
Chris Lattner3822f632009-01-02 08:05:26 +00006283 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006284 break;
6285
Chris Lattnerf4f03422009-12-30 05:27:33 +00006286 if (Lex.getKind() == lltok::MetadataVar) {
6287 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006288 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006289 }
Devang Patel8f842d32009-10-16 18:45:49 +00006290
Chris Lattner3822f632009-01-02 08:05:26 +00006291 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006292 ParseValue(Ty, Op0, PFS) ||
6293 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006294 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006295 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6296 return true;
6297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006298
Chris Lattnerac161bf2009-01-02 07:01:27 +00006299 if (!Ty->isFirstClassType())
6300 return Error(TypeLoc, "phi node must have first class type");
6301
Jay Foad52131342011-03-30 11:28:46 +00006302 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6304 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6305 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006306 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006307}
6308
Bill Wendlingfae14752011-08-12 20:24:12 +00006309/// ParseLandingPad
6310/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6311/// Clause
6312/// ::= 'catch' TypeAndValue
6313/// ::= 'filter'
6314/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6315bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006316 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006317
David Majnemer7fddecc2015-06-17 20:52:32 +00006318 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006319 return true;
6320
David Majnemer7fddecc2015-06-17 20:52:32 +00006321 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006322 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6323
6324 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6325 LandingPadInst::ClauseType CT;
6326 if (EatIfPresent(lltok::kw_catch))
6327 CT = LandingPadInst::Catch;
6328 else if (EatIfPresent(lltok::kw_filter))
6329 CT = LandingPadInst::Filter;
6330 else
6331 return TokError("expected 'catch' or 'filter' clause type");
6332
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006333 Value *V;
6334 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006335 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006336 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006337
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006338 // A 'catch' type expects a non-array constant. A filter clause expects an
6339 // array constant.
6340 if (CT == LandingPadInst::Catch) {
6341 if (isa<ArrayType>(V->getType()))
6342 Error(VLoc, "'catch' clause has an invalid type");
6343 } else {
6344 if (!isa<ArrayType>(V->getType()))
6345 Error(VLoc, "'filter' clause has an invalid type");
6346 }
6347
Owen Andersonf8f259d2015-03-09 07:13:42 +00006348 Constant *CV = dyn_cast<Constant>(V);
6349 if (!CV)
6350 return Error(VLoc, "clause argument must be a constant");
6351 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006352 }
6353
Owen Andersonf8f259d2015-03-09 07:13:42 +00006354 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006355 return false;
6356}
6357
Chris Lattnerac161bf2009-01-02 07:01:27 +00006358/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006359/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6360/// OptionalAttrs Type Value ParameterList OptionalAttrs
6361/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6362/// OptionalAttrs Type Value ParameterList OptionalAttrs
6363/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6364/// OptionalAttrs Type Value ParameterList OptionalAttrs
6365/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6366/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006367bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006368 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006369 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006370 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006371 LocTy BuiltinLoc;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006372 unsigned CallAddrSpace;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006373 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006374 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006375 LocTy RetTypeLoc;
6376 ValID CalleeID;
6377 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006378 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006379 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006380
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006381 if (TCK != CallInst::TCK_None &&
6382 ParseToken(lltok::kw_call,
6383 "expected 'tail call', 'musttail call', or 'notail call'"))
6384 return true;
6385
6386 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6387
6388 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006389 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006390 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006392 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6393 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006394 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6395 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006396 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006397
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006398 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6399 return Error(CallLoc, "fast-math-flags specified for call without "
6400 "floating-point scalar or vector return type");
6401
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 // If RetType is a non-function pointer type, then this is the short syntax
6403 // for the call, which means that RetType is just the return type. Infer the
6404 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006405 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6406 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006407 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006408 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006409 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6410 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006411
Chris Lattnerac161bf2009-01-02 07:01:27 +00006412 if (!FunctionType::isValidReturnType(RetType))
6413 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006414
Owen Anderson4056ca92009-07-29 22:17:13 +00006415 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006416 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006417
David Blaikie41ba2b42015-07-27 23:32:19 +00006418 CalleeID.FTy = Ty;
6419
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420 // Look up the callee.
6421 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006422 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6423 &PFS, /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006424 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006425
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006426 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006427 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006428
Chris Lattnerac161bf2009-01-02 07:01:27 +00006429 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006430
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431 // Loop through FunctionType's arguments and ensure they are specified
6432 // correctly. Also, gather any parameter attributes.
6433 FunctionType::param_iterator I = Ty->param_begin();
6434 FunctionType::param_iterator E = Ty->param_end();
6435 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006436 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006437 if (I != E) {
6438 ExpectedTy = *I++;
6439 } else if (!Ty->isVarArg()) {
6440 return Error(ArgList[i].Loc, "too many arguments specified");
6441 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006442
Chris Lattnerac161bf2009-01-02 07:01:27 +00006443 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6444 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006445 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006446 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006447 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006449
Chris Lattnerac161bf2009-01-02 07:01:27 +00006450 if (I != E)
6451 return Error(CallLoc, "not enough parameters specified for call");
6452
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006453 if (FnAttrs.hasAlignmentAttr())
6454 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006455
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006456 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006457 AttributeList PAL =
6458 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6459 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006460
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006461 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006462 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006463 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006464 if (FMF.any())
6465 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006466 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006467 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006468 Inst = CI;
6469 return false;
6470}
6471
6472//===----------------------------------------------------------------------===//
6473// Memory Instructions.
6474//===----------------------------------------------------------------------===//
6475
6476/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006477/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006478/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006479int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006480 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006481 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006482 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006483 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006484 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006485
6486 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006487 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006488
David Majnemera3b0eb22015-02-16 08:38:03 +00006489 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006490
David Majnemera3b0eb22015-02-16 08:38:03 +00006491 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6492 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006493
Chris Lattnerb2f39502009-12-30 05:44:30 +00006494 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006495 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006496 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006497 if (ParseOptionalAlignment(Alignment))
6498 return true;
6499 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6500 return true;
6501 } else if (Lex.getKind() == lltok::kw_addrspace) {
6502 ASLoc = Lex.getLoc();
6503 if (ParseOptionalAddrSpace(AddrSpace))
6504 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006505 } else if (Lex.getKind() == lltok::MetadataVar) {
6506 AteExtraComma = true;
6507 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006508 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006509 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006510 if (EatIfPresent(lltok::comma)) {
6511 if (Lex.getKind() == lltok::kw_align) {
6512 if (ParseOptionalAlignment(Alignment))
6513 return true;
6514 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6515 return true;
6516 } else if (Lex.getKind() == lltok::kw_addrspace) {
6517 ASLoc = Lex.getLoc();
6518 if (ParseOptionalAddrSpace(AddrSpace))
6519 return true;
6520 } else if (Lex.getKind() == lltok::MetadataVar) {
6521 AteExtraComma = true;
6522 }
6523 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006524 }
6525 }
6526
Dan Gohman2140a742010-05-28 01:14:11 +00006527 if (Size && !Size->getType()->isIntegerTy())
6528 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006529
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006530 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006531 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006532 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006533 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006534 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006535}
6536
6537/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006538/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006539/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006540/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006541int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006542 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006543 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006544 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006545 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006546 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006547 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006548
6549 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006550 isAtomic = true;
6551 Lex.Lex();
6552 }
6553
Chris Lattnerbc639292011-11-27 06:56:53 +00006554 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006555 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006556 isVolatile = true;
6557 Lex.Lex();
6558 }
6559
David Blaikie15d9a4c2015-04-06 20:59:48 +00006560 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006561 LocTy ExplicitTypeLoc = Lex.getLoc();
6562 if (ParseType(Ty) ||
6563 ParseToken(lltok::comma, "expected comma after load's type") ||
6564 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006565 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006566 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6567 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006568
David Blaikie15d9a4c2015-04-06 20:59:48 +00006569 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006570 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006571 if (isAtomic && !Alignment)
6572 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006573 if (Ordering == AtomicOrdering::Release ||
6574 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006575 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006576
David Blaikiea79ac142015-02-27 21:17:42 +00006577 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6578 return Error(ExplicitTypeLoc,
6579 "explicit pointee type doesn't match operand's pointee type");
6580
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006581 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006582 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006583}
6584
6585/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006586
6587/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6588/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006589/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006590int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006591 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006592 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006593 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006594 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006595 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006596 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006597
6598 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006599 isAtomic = true;
6600 Lex.Lex();
6601 }
6602
Chris Lattnerbc639292011-11-27 06:56:53 +00006603 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006604 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006605 isVolatile = true;
6606 Lex.Lex();
6607 }
6608
Chris Lattnerac161bf2009-01-02 07:01:27 +00006609 if (ParseTypeAndValue(Val, Loc, PFS) ||
6610 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006611 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006612 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006613 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006614 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006615
Duncan Sands19d0b472010-02-16 11:11:14 +00006616 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006617 return Error(PtrLoc, "store operand must be a pointer");
6618 if (!Val->getType()->isFirstClassType())
6619 return Error(Loc, "store operand must be a first class value");
6620 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6621 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006622 if (isAtomic && !Alignment)
6623 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006624 if (Ordering == AtomicOrdering::Acquire ||
6625 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006626 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006627
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006628 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006629 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006630}
6631
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006632/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006633/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6634/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006635int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006636 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6637 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006638 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6639 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006640 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006641 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006642 bool isWeak = false;
6643
6644 if (EatIfPresent(lltok::kw_weak))
6645 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006646
6647 if (EatIfPresent(lltok::kw_volatile))
6648 isVolatile = true;
6649
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006650 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6651 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6652 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6653 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6654 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006655 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006656 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006657 return true;
6658
JF Bastien800f87a2016-04-06 21:19:33 +00006659 if (SuccessOrdering == AtomicOrdering::Unordered ||
6660 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006661 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006662 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6663 return TokError("cmpxchg failure argument shall be no stronger than the "
6664 "success argument");
6665 if (FailureOrdering == AtomicOrdering::Release ||
6666 FailureOrdering == AtomicOrdering::AcquireRelease)
6667 return TokError(
6668 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006669 if (!Ptr->getType()->isPointerTy())
6670 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6671 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6672 return Error(CmpLoc, "compare value and pointer type do not match");
6673 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6674 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006675 if (!New->getType()->isFirstClassType())
6676 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006677 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006678 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006679 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006680 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006681 Inst = CXI;
6682 return AteExtraComma ? InstExtraComma : InstNormal;
6683}
6684
6685/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006686/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6687/// 'singlethread'? AtomicOrdering
6688int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006689 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6690 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006691 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006692 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006693 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006694 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006695
6696 if (EatIfPresent(lltok::kw_volatile))
6697 isVolatile = true;
6698
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006699 switch (Lex.getKind()) {
6700 default: return TokError("expected binary operation in atomicrmw");
6701 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6702 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6703 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6704 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6705 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6706 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6707 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6708 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6709 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6710 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6711 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6712 }
6713 Lex.Lex(); // Eat the operation.
6714
6715 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6716 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6717 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006718 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006719 return true;
6720
JF Bastien800f87a2016-04-06 21:19:33 +00006721 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006722 return TokError("atomicrmw cannot be unordered");
6723 if (!Ptr->getType()->isPointerTy())
6724 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6725 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6726 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6727 if (!Val->getType()->isIntegerTy())
6728 return Error(ValLoc, "atomicrmw operand must be an integer");
6729 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6730 if (Size < 8 || (Size & (Size - 1)))
6731 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6732 " integer");
6733
6734 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006735 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006736 RMWI->setVolatile(isVolatile);
6737 Inst = RMWI;
6738 return AteExtraComma ? InstExtraComma : InstNormal;
6739}
6740
Eli Friedmanfee02c62011-07-25 23:16:38 +00006741/// ParseFence
6742/// ::= 'fence' 'singlethread'? AtomicOrdering
6743int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006744 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006745 SyncScope::ID SSID = SyncScope::System;
6746 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006747 return true;
6748
JF Bastien800f87a2016-04-06 21:19:33 +00006749 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006750 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006751 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006752 return TokError("fence cannot be monotonic");
6753
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006754 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006755 return InstNormal;
6756}
6757
Chris Lattnerac161bf2009-01-02 07:01:27 +00006758/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006759/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006760int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006761 Value *Ptr = nullptr;
6762 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006763 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006764
Dan Gohman16cbbe42009-07-29 15:58:36 +00006765 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006766
David Blaikie79e6c742015-02-27 19:29:02 +00006767 Type *Ty = nullptr;
6768 LocTy ExplicitTypeLoc = Lex.getLoc();
6769 if (ParseType(Ty) ||
6770 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6771 ParseTypeAndValue(Ptr, Loc, PFS))
6772 return true;
6773
Eli Benderskyd9806682013-04-22 17:03:42 +00006774 Type *BaseType = Ptr->getType();
6775 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6776 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006777 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006778
David Blaikie8d757942015-03-09 23:08:44 +00006779 if (Ty != BasePointerType->getElementType())
6780 return Error(ExplicitTypeLoc,
6781 "explicit pointee type doesn't match operand's pointee type");
6782
Chris Lattnerac161bf2009-01-02 07:01:27 +00006783 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006784 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006785 // GEP returns a vector of pointers if at least one of parameters is a vector.
6786 // All vector parameters should have the same vector width.
6787 unsigned GEPWidth = BaseType->isVectorTy() ?
6788 BaseType->getVectorNumElements() : 0;
6789
Chris Lattner3822f632009-01-02 08:05:26 +00006790 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006791 if (Lex.getKind() == lltok::MetadataVar) {
6792 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006793 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006794 }
Chris Lattner3822f632009-01-02 08:05:26 +00006795 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006796 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006797 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006798
Nadav Rotem3924cb02011-12-05 06:29:09 +00006799 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006800 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6801 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006802 return Error(EltLoc,
6803 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006804 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006805 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006806 Indices.push_back(Val);
6807 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006808
Craig Toppere3dcce92015-08-01 22:20:21 +00006809 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006810 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006811 return Error(Loc, "base element of getelementptr must be sized");
6812
David Blaikied33bad32015-04-17 22:32:13 +00006813 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006814 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006815 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006816 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006817 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006818 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006819}
6820
6821/// ParseExtractValue
6822/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006823int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006824 Value *Val; LocTy Loc;
6825 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006826 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006827 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006828 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006829 return true;
6830
Chris Lattner392be582010-02-12 20:49:41 +00006831 if (!Val->getType()->isAggregateType())
6832 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006833
Jay Foad57aa6362011-07-13 10:26:04 +00006834 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006835 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006836 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006837 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006838}
6839
6840/// ParseInsertValue
6841/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006842int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006843 Value *Val0, *Val1; LocTy Loc0, Loc1;
6844 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006845 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006846 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6847 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6848 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006849 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006850 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006851
Chris Lattner392be582010-02-12 20:49:41 +00006852 if (!Val0->getType()->isAggregateType())
6853 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006854
David Majnemer30074532015-02-11 07:43:58 +00006855 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6856 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006857 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006858 if (IndexedType != Val1->getType())
6859 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6860 getTypeString(Val1->getType()) + "' instead of '" +
6861 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006862 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006863 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006864}
Nick Lewycky49f89192009-04-04 07:22:01 +00006865
6866//===----------------------------------------------------------------------===//
6867// Embedded metadata.
6868//===----------------------------------------------------------------------===//
6869
6870/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006871/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006872/// Element
6873/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006874bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006875 if (ParseToken(lltok::lbrace, "expected '{' here"))
6876 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006877
Dan Gohman1e0213a2010-07-13 19:33:27 +00006878 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006879 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006880 return false;
6881
Nick Lewycky49f89192009-04-04 07:22:01 +00006882 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006883 // Null is a special case since it is typeless.
6884 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006885 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006886 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006887 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006888
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006889 Metadata *MD;
6890 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006891 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006892 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006893 } while (EatIfPresent(lltok::comma));
6894
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006895 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006896}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006897
6898//===----------------------------------------------------------------------===//
6899// Use-list order directives.
6900//===----------------------------------------------------------------------===//
6901bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6902 SMLoc Loc) {
6903 if (V->use_empty())
6904 return Error(Loc, "value has no uses");
6905
6906 unsigned NumUses = 0;
6907 SmallDenseMap<const Use *, unsigned, 16> Order;
6908 for (const Use &U : V->uses()) {
6909 if (++NumUses > Indexes.size())
6910 break;
6911 Order[&U] = Indexes[NumUses - 1];
6912 }
6913 if (NumUses < 2)
6914 return Error(Loc, "value only has one use");
6915 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00006916 return Error(Loc,
6917 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006918
6919 V->sortUseList([&](const Use &L, const Use &R) {
6920 return Order.lookup(&L) < Order.lookup(&R);
6921 });
6922 return false;
6923}
6924
6925/// ParseUseListOrderIndexes
6926/// ::= '{' uint32 (',' uint32)+ '}'
6927bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6928 SMLoc Loc = Lex.getLoc();
6929 if (ParseToken(lltok::lbrace, "expected '{' here"))
6930 return true;
6931 if (Lex.getKind() == lltok::rbrace)
6932 return Lex.Error("expected non-empty list of uselistorder indexes");
6933
6934 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6935 // indexes should be distinct numbers in the range [0, size-1], and should
6936 // not be in order.
6937 unsigned Offset = 0;
6938 unsigned Max = 0;
6939 bool IsOrdered = true;
6940 assert(Indexes.empty() && "Expected empty order vector");
6941 do {
6942 unsigned Index;
6943 if (ParseUInt32(Index))
6944 return true;
6945
6946 // Update consistency checks.
6947 Offset += Index - Indexes.size();
6948 Max = std::max(Max, Index);
6949 IsOrdered &= Index == Indexes.size();
6950
6951 Indexes.push_back(Index);
6952 } while (EatIfPresent(lltok::comma));
6953
6954 if (ParseToken(lltok::rbrace, "expected '}' here"))
6955 return true;
6956
6957 if (Indexes.size() < 2)
6958 return Error(Loc, "expected >= 2 uselistorder indexes");
6959 if (Offset != 0 || Max >= Indexes.size())
6960 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6961 if (IsOrdered)
6962 return Error(Loc, "expected uselistorder indexes to change the order");
6963
6964 return false;
6965}
6966
6967/// ParseUseListOrder
6968/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6969bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6970 SMLoc Loc = Lex.getLoc();
6971 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6972 return true;
6973
6974 Value *V;
6975 SmallVector<unsigned, 16> Indexes;
6976 if (ParseTypeAndValue(V, PFS) ||
6977 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6978 ParseUseListOrderIndexes(Indexes))
6979 return true;
6980
6981 return sortUseListOrder(V, Indexes, Loc);
6982}
6983
6984/// ParseUseListOrderBB
6985/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6986bool LLParser::ParseUseListOrderBB() {
6987 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6988 SMLoc Loc = Lex.getLoc();
6989 Lex.Lex();
6990
6991 ValID Fn, Label;
6992 SmallVector<unsigned, 16> Indexes;
6993 if (ParseValID(Fn) ||
6994 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6995 ParseValID(Label) ||
6996 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6997 ParseUseListOrderIndexes(Indexes))
6998 return true;
6999
7000 // Check the function.
7001 GlobalValue *GV;
7002 if (Fn.Kind == ValID::t_GlobalName)
7003 GV = M->getNamedValue(Fn.StrVal);
7004 else if (Fn.Kind == ValID::t_GlobalID)
7005 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7006 else
7007 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7008 if (!GV)
7009 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7010 auto *F = dyn_cast<Function>(GV);
7011 if (!F)
7012 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7013 if (F->isDeclaration())
7014 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7015
7016 // Check the basic block.
7017 if (Label.Kind == ValID::t_LocalID)
7018 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7019 if (Label.Kind != ValID::t_LocalName)
7020 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007021 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007022 if (!V)
7023 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7024 if (!isa<BasicBlock>(V))
7025 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7026
7027 return sortUseListOrder(V, Indexes, Loc);
7028}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007029
7030/// ModuleEntry
7031/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7032/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7033bool LLParser::ParseModuleEntry(unsigned ID) {
7034 assert(Lex.getKind() == lltok::kw_module);
7035 Lex.Lex();
7036
7037 std::string Path;
7038 if (ParseToken(lltok::colon, "expected ':' here") ||
7039 ParseToken(lltok::lparen, "expected '(' here") ||
7040 ParseToken(lltok::kw_path, "expected 'path' here") ||
7041 ParseToken(lltok::colon, "expected ':' here") ||
7042 ParseStringConstant(Path) ||
7043 ParseToken(lltok::comma, "expected ',' here") ||
7044 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7045 ParseToken(lltok::colon, "expected ':' here") ||
7046 ParseToken(lltok::lparen, "expected '(' here"))
7047 return true;
7048
7049 ModuleHash Hash;
7050 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7051 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7052 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7053 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7054 ParseUInt32(Hash[4]))
7055 return true;
7056
7057 if (ParseToken(lltok::rparen, "expected ')' here") ||
7058 ParseToken(lltok::rparen, "expected ')' here"))
7059 return true;
7060
7061 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7062 ModuleIdMap[ID] = ModuleEntry->first();
7063
7064 return false;
7065}
7066
7067/// TypeIdEntry
7068/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7069bool LLParser::ParseTypeIdEntry(unsigned ID) {
7070 assert(Lex.getKind() == lltok::kw_typeid);
7071 Lex.Lex();
7072
7073 std::string Name;
7074 if (ParseToken(lltok::colon, "expected ':' here") ||
7075 ParseToken(lltok::lparen, "expected '(' here") ||
7076 ParseToken(lltok::kw_name, "expected 'name' here") ||
7077 ParseToken(lltok::colon, "expected ':' here") ||
7078 ParseStringConstant(Name))
7079 return true;
7080
7081 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7082 if (ParseToken(lltok::comma, "expected ',' here") ||
7083 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7084 return true;
7085
7086 // Check if this ID was forward referenced, and if so, update the
7087 // corresponding GUIDs.
7088 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7089 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7090 for (auto TIDRef : FwdRefTIDs->second) {
7091 assert(!*TIDRef.first &&
7092 "Forward referenced type id GUID expected to be 0");
7093 *TIDRef.first = GlobalValue::getGUID(Name);
7094 }
7095 ForwardRefTypeIds.erase(FwdRefTIDs);
7096 }
7097
7098 return false;
7099}
7100
7101/// TypeIdSummary
7102/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7103bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7104 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7105 ParseToken(lltok::colon, "expected ':' here") ||
7106 ParseToken(lltok::lparen, "expected '(' here") ||
7107 ParseTypeTestResolution(TIS.TTRes))
7108 return true;
7109
7110 if (EatIfPresent(lltok::comma)) {
7111 // Expect optional wpdResolutions field
7112 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7113 return true;
7114 }
7115
7116 if (ParseToken(lltok::rparen, "expected ')' here"))
7117 return true;
7118
7119 return false;
7120}
7121
7122/// TypeTestResolution
7123/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7124/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7125/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7126/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7127/// [',' 'inlinesBits' ':' UInt64]? ')'
7128bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7129 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7130 ParseToken(lltok::colon, "expected ':' here") ||
7131 ParseToken(lltok::lparen, "expected '(' here") ||
7132 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7133 ParseToken(lltok::colon, "expected ':' here"))
7134 return true;
7135
7136 switch (Lex.getKind()) {
7137 case lltok::kw_unsat:
7138 TTRes.TheKind = TypeTestResolution::Unsat;
7139 break;
7140 case lltok::kw_byteArray:
7141 TTRes.TheKind = TypeTestResolution::ByteArray;
7142 break;
7143 case lltok::kw_inline:
7144 TTRes.TheKind = TypeTestResolution::Inline;
7145 break;
7146 case lltok::kw_single:
7147 TTRes.TheKind = TypeTestResolution::Single;
7148 break;
7149 case lltok::kw_allOnes:
7150 TTRes.TheKind = TypeTestResolution::AllOnes;
7151 break;
7152 default:
7153 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7154 }
7155 Lex.Lex();
7156
7157 if (ParseToken(lltok::comma, "expected ',' here") ||
7158 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7159 ParseToken(lltok::colon, "expected ':' here") ||
7160 ParseUInt32(TTRes.SizeM1BitWidth))
7161 return true;
7162
7163 // Parse optional fields
7164 while (EatIfPresent(lltok::comma)) {
7165 switch (Lex.getKind()) {
7166 case lltok::kw_alignLog2:
7167 Lex.Lex();
7168 if (ParseToken(lltok::colon, "expected ':'") ||
7169 ParseUInt64(TTRes.AlignLog2))
7170 return true;
7171 break;
7172 case lltok::kw_sizeM1:
7173 Lex.Lex();
7174 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7175 return true;
7176 break;
7177 case lltok::kw_bitMask: {
7178 unsigned Val;
7179 Lex.Lex();
7180 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7181 return true;
7182 assert(Val <= 0xff);
7183 TTRes.BitMask = (uint8_t)Val;
7184 break;
7185 }
7186 case lltok::kw_inlineBits:
7187 Lex.Lex();
7188 if (ParseToken(lltok::colon, "expected ':'") ||
7189 ParseUInt64(TTRes.InlineBits))
7190 return true;
7191 break;
7192 default:
7193 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7194 }
7195 }
7196
7197 if (ParseToken(lltok::rparen, "expected ')' here"))
7198 return true;
7199
7200 return false;
7201}
7202
7203/// OptionalWpdResolutions
7204/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7205/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7206bool LLParser::ParseOptionalWpdResolutions(
7207 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7208 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7209 ParseToken(lltok::colon, "expected ':' here") ||
7210 ParseToken(lltok::lparen, "expected '(' here"))
7211 return true;
7212
7213 do {
7214 uint64_t Offset;
7215 WholeProgramDevirtResolution WPDRes;
7216 if (ParseToken(lltok::lparen, "expected '(' here") ||
7217 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7218 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7219 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7220 ParseToken(lltok::rparen, "expected ')' here"))
7221 return true;
7222 WPDResMap[Offset] = WPDRes;
7223 } while (EatIfPresent(lltok::comma));
7224
7225 if (ParseToken(lltok::rparen, "expected ')' here"))
7226 return true;
7227
7228 return false;
7229}
7230
7231/// WpdRes
7232/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7233/// [',' OptionalResByArg]? ')'
7234/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7235/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7236/// [',' OptionalResByArg]? ')'
7237/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7238/// [',' OptionalResByArg]? ')'
7239bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7240 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7241 ParseToken(lltok::colon, "expected ':' here") ||
7242 ParseToken(lltok::lparen, "expected '(' here") ||
7243 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7244 ParseToken(lltok::colon, "expected ':' here"))
7245 return true;
7246
7247 switch (Lex.getKind()) {
7248 case lltok::kw_indir:
7249 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7250 break;
7251 case lltok::kw_singleImpl:
7252 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7253 break;
7254 case lltok::kw_branchFunnel:
7255 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7256 break;
7257 default:
7258 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7259 }
7260 Lex.Lex();
7261
7262 // Parse optional fields
7263 while (EatIfPresent(lltok::comma)) {
7264 switch (Lex.getKind()) {
7265 case lltok::kw_singleImplName:
7266 Lex.Lex();
7267 if (ParseToken(lltok::colon, "expected ':' here") ||
7268 ParseStringConstant(WPDRes.SingleImplName))
7269 return true;
7270 break;
7271 case lltok::kw_resByArg:
7272 if (ParseOptionalResByArg(WPDRes.ResByArg))
7273 return true;
7274 break;
7275 default:
7276 return Error(Lex.getLoc(),
7277 "expected optional WholeProgramDevirtResolution field");
7278 }
7279 }
7280
7281 if (ParseToken(lltok::rparen, "expected ')' here"))
7282 return true;
7283
7284 return false;
7285}
7286
7287/// OptionalResByArg
7288/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7289/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7290/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7291/// 'virtualConstProp' )
7292/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7293/// [',' 'bit' ':' UInt32]? ')'
7294bool LLParser::ParseOptionalResByArg(
7295 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7296 &ResByArg) {
7297 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7298 ParseToken(lltok::colon, "expected ':' here") ||
7299 ParseToken(lltok::lparen, "expected '(' here"))
7300 return true;
7301
7302 do {
7303 std::vector<uint64_t> Args;
7304 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7305 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7306 ParseToken(lltok::colon, "expected ':' here") ||
7307 ParseToken(lltok::lparen, "expected '(' here") ||
7308 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7309 ParseToken(lltok::colon, "expected ':' here"))
7310 return true;
7311
7312 WholeProgramDevirtResolution::ByArg ByArg;
7313 switch (Lex.getKind()) {
7314 case lltok::kw_indir:
7315 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7316 break;
7317 case lltok::kw_uniformRetVal:
7318 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7319 break;
7320 case lltok::kw_uniqueRetVal:
7321 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7322 break;
7323 case lltok::kw_virtualConstProp:
7324 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7325 break;
7326 default:
7327 return Error(Lex.getLoc(),
7328 "unexpected WholeProgramDevirtResolution::ByArg kind");
7329 }
7330 Lex.Lex();
7331
7332 // Parse optional fields
7333 while (EatIfPresent(lltok::comma)) {
7334 switch (Lex.getKind()) {
7335 case lltok::kw_info:
7336 Lex.Lex();
7337 if (ParseToken(lltok::colon, "expected ':' here") ||
7338 ParseUInt64(ByArg.Info))
7339 return true;
7340 break;
7341 case lltok::kw_byte:
7342 Lex.Lex();
7343 if (ParseToken(lltok::colon, "expected ':' here") ||
7344 ParseUInt32(ByArg.Byte))
7345 return true;
7346 break;
7347 case lltok::kw_bit:
7348 Lex.Lex();
7349 if (ParseToken(lltok::colon, "expected ':' here") ||
7350 ParseUInt32(ByArg.Bit))
7351 return true;
7352 break;
7353 default:
7354 return Error(Lex.getLoc(),
7355 "expected optional whole program devirt field");
7356 }
7357 }
7358
7359 if (ParseToken(lltok::rparen, "expected ')' here"))
7360 return true;
7361
7362 ResByArg[Args] = ByArg;
7363 } while (EatIfPresent(lltok::comma));
7364
7365 if (ParseToken(lltok::rparen, "expected ')' here"))
7366 return true;
7367
7368 return false;
7369}
7370
7371/// OptionalResByArg
7372/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7373bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7374 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7375 ParseToken(lltok::colon, "expected ':' here") ||
7376 ParseToken(lltok::lparen, "expected '(' here"))
7377 return true;
7378
7379 do {
7380 uint64_t Val;
7381 if (ParseUInt64(Val))
7382 return true;
7383 Args.push_back(Val);
7384 } while (EatIfPresent(lltok::comma));
7385
7386 if (ParseToken(lltok::rparen, "expected ')' here"))
7387 return true;
7388
7389 return false;
7390}
7391
7392static ValueInfo EmptyVI =
7393 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7394
7395/// Stores the given Name/GUID and associated summary into the Index.
7396/// Also updates any forward references to the associated entry ID.
7397void LLParser::AddGlobalValueToIndex(
7398 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7399 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7400 // First create the ValueInfo utilizing the Name or GUID.
7401 ValueInfo VI;
7402 if (GUID != 0) {
7403 assert(Name.empty());
7404 VI = Index->getOrInsertValueInfo(GUID);
7405 } else {
7406 assert(!Name.empty());
7407 if (M) {
7408 auto *GV = M->getNamedValue(Name);
7409 assert(GV);
7410 VI = Index->getOrInsertValueInfo(GV);
7411 } else {
7412 assert(
7413 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7414 "Need a source_filename to compute GUID for local");
7415 GUID = GlobalValue::getGUID(
7416 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7417 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7418 }
7419 }
7420
7421 // Add the summary if one was provided.
7422 if (Summary)
7423 Index->addGlobalValueSummary(VI, std::move(Summary));
7424
7425 // Resolve forward references from calls/refs
7426 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7427 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7428 for (auto VIRef : FwdRefVIs->second) {
7429 assert(*VIRef.first == EmptyVI &&
7430 "Forward referenced ValueInfo expected to be empty");
7431 *VIRef.first = VI;
7432 }
7433 ForwardRefValueInfos.erase(FwdRefVIs);
7434 }
7435
7436 // Resolve forward references from aliases
7437 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7438 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7439 for (auto AliaseeRef : FwdRefAliasees->second) {
7440 assert(!AliaseeRef.first->hasAliasee() &&
7441 "Forward referencing alias already has aliasee");
7442 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7443 }
7444 ForwardRefAliasees.erase(FwdRefAliasees);
7445 }
7446
7447 // Save the associated ValueInfo for use in later references by ID.
7448 if (ID == NumberedValueInfos.size())
7449 NumberedValueInfos.push_back(VI);
7450 else {
7451 // Handle non-continuous numbers (to make test simplification easier).
7452 if (ID > NumberedValueInfos.size())
7453 NumberedValueInfos.resize(ID + 1);
7454 NumberedValueInfos[ID] = VI;
7455 }
7456}
7457
7458/// ParseGVEntry
7459/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7460/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7461/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7462bool LLParser::ParseGVEntry(unsigned ID) {
7463 assert(Lex.getKind() == lltok::kw_gv);
7464 Lex.Lex();
7465
7466 if (ParseToken(lltok::colon, "expected ':' here") ||
7467 ParseToken(lltok::lparen, "expected '(' here"))
7468 return true;
7469
7470 std::string Name;
7471 GlobalValue::GUID GUID = 0;
7472 switch (Lex.getKind()) {
7473 case lltok::kw_name:
7474 Lex.Lex();
7475 if (ParseToken(lltok::colon, "expected ':' here") ||
7476 ParseStringConstant(Name))
7477 return true;
7478 // Can't create GUID/ValueInfo until we have the linkage.
7479 break;
7480 case lltok::kw_guid:
7481 Lex.Lex();
7482 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7483 return true;
7484 break;
7485 default:
7486 return Error(Lex.getLoc(), "expected name or guid tag");
7487 }
7488
7489 if (!EatIfPresent(lltok::comma)) {
7490 // No summaries. Wrap up.
7491 if (ParseToken(lltok::rparen, "expected ')' here"))
7492 return true;
7493 // This was created for a call to an external or indirect target.
7494 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7495 // created for indirect calls with VP. A Name with no GUID came from
7496 // an external definition. We pass ExternalLinkage since that is only
7497 // used when the GUID must be computed from Name, and in that case
7498 // the symbol must have external linkage.
7499 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7500 nullptr);
7501 return false;
7502 }
7503
7504 // Have a list of summaries
7505 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7506 ParseToken(lltok::colon, "expected ':' here"))
7507 return true;
7508
7509 do {
7510 if (ParseToken(lltok::lparen, "expected '(' here"))
7511 return true;
7512 switch (Lex.getKind()) {
7513 case lltok::kw_function:
7514 if (ParseFunctionSummary(Name, GUID, ID))
7515 return true;
7516 break;
7517 case lltok::kw_variable:
7518 if (ParseVariableSummary(Name, GUID, ID))
7519 return true;
7520 break;
7521 case lltok::kw_alias:
7522 if (ParseAliasSummary(Name, GUID, ID))
7523 return true;
7524 break;
7525 default:
7526 return Error(Lex.getLoc(), "expected summary type");
7527 }
7528 if (ParseToken(lltok::rparen, "expected ')' here"))
7529 return true;
7530 } while (EatIfPresent(lltok::comma));
7531
7532 if (ParseToken(lltok::rparen, "expected ')' here"))
7533 return true;
7534
7535 return false;
7536}
7537
7538/// FunctionSummary
7539/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7540/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7541/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7542bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7543 unsigned ID) {
7544 assert(Lex.getKind() == lltok::kw_function);
7545 Lex.Lex();
7546
7547 StringRef ModulePath;
7548 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7549 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7550 /*Live=*/false, /*IsLocal=*/false);
7551 unsigned InstCount;
7552 std::vector<FunctionSummary::EdgeTy> Calls;
7553 FunctionSummary::TypeIdInfo TypeIdInfo;
7554 std::vector<ValueInfo> Refs;
7555 // Default is all-zeros (conservative values).
7556 FunctionSummary::FFlags FFlags = {};
7557 if (ParseToken(lltok::colon, "expected ':' here") ||
7558 ParseToken(lltok::lparen, "expected '(' here") ||
7559 ParseModuleReference(ModulePath) ||
7560 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7561 ParseToken(lltok::comma, "expected ',' here") ||
7562 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7563 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7564 return true;
7565
7566 // Parse optional fields
7567 while (EatIfPresent(lltok::comma)) {
7568 switch (Lex.getKind()) {
7569 case lltok::kw_funcFlags:
7570 if (ParseOptionalFFlags(FFlags))
7571 return true;
7572 break;
7573 case lltok::kw_calls:
7574 if (ParseOptionalCalls(Calls))
7575 return true;
7576 break;
7577 case lltok::kw_typeIdInfo:
7578 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7579 return true;
7580 break;
7581 case lltok::kw_refs:
7582 if (ParseOptionalRefs(Refs))
7583 return true;
7584 break;
7585 default:
7586 return Error(Lex.getLoc(), "expected optional function summary field");
7587 }
7588 }
7589
7590 if (ParseToken(lltok::rparen, "expected ')' here"))
7591 return true;
7592
7593 auto FS = llvm::make_unique<FunctionSummary>(
7594 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
7595 std::move(TypeIdInfo.TypeTests),
7596 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7597 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7598 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7599 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7600
7601 FS->setModulePath(ModulePath);
7602
7603 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7604 ID, std::move(FS));
7605
7606 return false;
7607}
7608
7609/// VariableSummary
7610/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7611/// [',' OptionalRefs]? ')'
7612bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7613 unsigned ID) {
7614 assert(Lex.getKind() == lltok::kw_variable);
7615 Lex.Lex();
7616
7617 StringRef ModulePath;
7618 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7619 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7620 /*Live=*/false, /*IsLocal=*/false);
7621 std::vector<ValueInfo> Refs;
7622 if (ParseToken(lltok::colon, "expected ':' here") ||
7623 ParseToken(lltok::lparen, "expected '(' here") ||
7624 ParseModuleReference(ModulePath) ||
7625 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags))
7626 return true;
7627
7628 // Parse optional refs field
7629 if (EatIfPresent(lltok::comma)) {
7630 if (ParseOptionalRefs(Refs))
7631 return true;
7632 }
7633
7634 if (ParseToken(lltok::rparen, "expected ')' here"))
7635 return true;
7636
7637 auto GS = llvm::make_unique<GlobalVarSummary>(GVFlags, std::move(Refs));
7638
7639 GS->setModulePath(ModulePath);
7640
7641 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7642 ID, std::move(GS));
7643
7644 return false;
7645}
7646
7647/// AliasSummary
7648/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7649/// 'aliasee' ':' GVReference ')'
7650bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7651 unsigned ID) {
7652 assert(Lex.getKind() == lltok::kw_alias);
7653 LocTy Loc = Lex.getLoc();
7654 Lex.Lex();
7655
7656 StringRef ModulePath;
7657 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7658 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7659 /*Live=*/false, /*IsLocal=*/false);
7660 if (ParseToken(lltok::colon, "expected ':' here") ||
7661 ParseToken(lltok::lparen, "expected '(' here") ||
7662 ParseModuleReference(ModulePath) ||
7663 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7664 ParseToken(lltok::comma, "expected ',' here") ||
7665 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7666 ParseToken(lltok::colon, "expected ':' here"))
7667 return true;
7668
7669 ValueInfo AliaseeVI;
7670 unsigned GVId;
7671 if (ParseGVReference(AliaseeVI, GVId))
7672 return true;
7673
7674 if (ParseToken(lltok::rparen, "expected ')' here"))
7675 return true;
7676
7677 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7678
7679 AS->setModulePath(ModulePath);
7680
7681 // Record forward reference if the aliasee is not parsed yet.
7682 if (AliaseeVI == EmptyVI) {
7683 auto FwdRef = ForwardRefAliasees.insert(
7684 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7685 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7686 } else
7687 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7688
7689 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7690 ID, std::move(AS));
7691
7692 return false;
7693}
7694
7695/// Flag
7696/// ::= [0|1]
7697bool LLParser::ParseFlag(unsigned &Val) {
7698 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7699 return TokError("expected integer");
7700 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7701 Lex.Lex();
7702 return false;
7703}
7704
7705/// OptionalFFlags
7706/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7707/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7708/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7709bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
7710 assert(Lex.getKind() == lltok::kw_funcFlags);
7711 Lex.Lex();
7712
7713 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
7714 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
7715 return true;
7716
7717 do {
7718 unsigned Val;
7719 switch (Lex.getKind()) {
7720 case lltok::kw_readNone:
7721 Lex.Lex();
7722 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7723 return true;
7724 FFlags.ReadNone = Val;
7725 break;
7726 case lltok::kw_readOnly:
7727 Lex.Lex();
7728 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7729 return true;
7730 FFlags.ReadOnly = Val;
7731 break;
7732 case lltok::kw_noRecurse:
7733 Lex.Lex();
7734 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7735 return true;
7736 FFlags.NoRecurse = Val;
7737 break;
7738 case lltok::kw_returnDoesNotAlias:
7739 Lex.Lex();
7740 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
7741 return true;
7742 FFlags.ReturnDoesNotAlias = Val;
7743 break;
7744 default:
7745 return Error(Lex.getLoc(), "expected function flag type");
7746 }
7747 } while (EatIfPresent(lltok::comma));
7748
7749 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
7750 return true;
7751
7752 return false;
7753}
7754
7755/// OptionalCalls
7756/// := 'calls' ':' '(' Call [',' Call]* ')'
7757/// Call ::= '(' 'callee' ':' GVReference
7758/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7759bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
7760 assert(Lex.getKind() == lltok::kw_calls);
7761 Lex.Lex();
7762
7763 if (ParseToken(lltok::colon, "expected ':' in calls") |
7764 ParseToken(lltok::lparen, "expected '(' in calls"))
7765 return true;
7766
7767 IdToIndexMapType IdToIndexMap;
7768 // Parse each call edge
7769 do {
7770 ValueInfo VI;
7771 if (ParseToken(lltok::lparen, "expected '(' in call") ||
7772 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
7773 ParseToken(lltok::colon, "expected ':'"))
7774 return true;
7775
7776 LocTy Loc = Lex.getLoc();
7777 unsigned GVId;
7778 if (ParseGVReference(VI, GVId))
7779 return true;
7780
7781 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7782 unsigned RelBF = 0;
7783 if (EatIfPresent(lltok::comma)) {
7784 // Expect either hotness or relbf
7785 if (EatIfPresent(lltok::kw_hotness)) {
7786 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
7787 return true;
7788 } else {
7789 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
7790 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
7791 return true;
7792 }
7793 }
7794 // Keep track of the Call array index needing a forward reference.
7795 // We will save the location of the ValueInfo needing an update, but
7796 // can only do so once the std::vector is finalized.
7797 if (VI == EmptyVI)
7798 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
7799 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
7800
7801 if (ParseToken(lltok::rparen, "expected ')' in call"))
7802 return true;
7803 } while (EatIfPresent(lltok::comma));
7804
7805 // Now that the Calls vector is finalized, it is safe to save the locations
7806 // of any forward GV references that need updating later.
7807 for (auto I : IdToIndexMap) {
7808 for (auto P : I.second) {
7809 assert(Calls[P.first].first == EmptyVI &&
7810 "Forward referenced ValueInfo expected to be empty");
7811 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7812 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7813 FwdRef.first->second.push_back(
7814 std::make_pair(&Calls[P.first].first, P.second));
7815 }
7816 }
7817
7818 if (ParseToken(lltok::rparen, "expected ')' in calls"))
7819 return true;
7820
7821 return false;
7822}
7823
7824/// Hotness
7825/// := ('unknown'|'cold'|'none'|'hot'|'critical')
7826bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
7827 switch (Lex.getKind()) {
7828 case lltok::kw_unknown:
7829 Hotness = CalleeInfo::HotnessType::Unknown;
7830 break;
7831 case lltok::kw_cold:
7832 Hotness = CalleeInfo::HotnessType::Cold;
7833 break;
7834 case lltok::kw_none:
7835 Hotness = CalleeInfo::HotnessType::None;
7836 break;
7837 case lltok::kw_hot:
7838 Hotness = CalleeInfo::HotnessType::Hot;
7839 break;
7840 case lltok::kw_critical:
7841 Hotness = CalleeInfo::HotnessType::Critical;
7842 break;
7843 default:
7844 return Error(Lex.getLoc(), "invalid call edge hotness");
7845 }
7846 Lex.Lex();
7847 return false;
7848}
7849
7850/// OptionalRefs
7851/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
7852bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
7853 assert(Lex.getKind() == lltok::kw_refs);
7854 Lex.Lex();
7855
7856 if (ParseToken(lltok::colon, "expected ':' in refs") |
7857 ParseToken(lltok::lparen, "expected '(' in refs"))
7858 return true;
7859
7860 IdToIndexMapType IdToIndexMap;
7861 // Parse each ref edge
7862 do {
7863 ValueInfo VI;
7864 LocTy Loc = Lex.getLoc();
7865 unsigned GVId;
7866 if (ParseGVReference(VI, GVId))
7867 return true;
7868
7869 // Keep track of the Refs array index needing a forward reference.
7870 // We will save the location of the ValueInfo needing an update, but
7871 // can only do so once the std::vector is finalized.
7872 if (VI == EmptyVI)
7873 IdToIndexMap[GVId].push_back(std::make_pair(Refs.size(), Loc));
7874 Refs.push_back(VI);
7875 } while (EatIfPresent(lltok::comma));
7876
7877 // Now that the Refs vector is finalized, it is safe to save the locations
7878 // of any forward GV references that need updating later.
7879 for (auto I : IdToIndexMap) {
7880 for (auto P : I.second) {
7881 assert(Refs[P.first] == EmptyVI &&
7882 "Forward referenced ValueInfo expected to be empty");
7883 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7884 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7885 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
7886 }
7887 }
7888
7889 if (ParseToken(lltok::rparen, "expected ')' in refs"))
7890 return true;
7891
7892 return false;
7893}
7894
7895/// OptionalTypeIdInfo
7896/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
7897/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
7898/// [',' TypeCheckedLoadConstVCalls]? ')'
7899bool LLParser::ParseOptionalTypeIdInfo(
7900 FunctionSummary::TypeIdInfo &TypeIdInfo) {
7901 assert(Lex.getKind() == lltok::kw_typeIdInfo);
7902 Lex.Lex();
7903
7904 if (ParseToken(lltok::colon, "expected ':' here") ||
7905 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7906 return true;
7907
7908 do {
7909 switch (Lex.getKind()) {
7910 case lltok::kw_typeTests:
7911 if (ParseTypeTests(TypeIdInfo.TypeTests))
7912 return true;
7913 break;
7914 case lltok::kw_typeTestAssumeVCalls:
7915 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
7916 TypeIdInfo.TypeTestAssumeVCalls))
7917 return true;
7918 break;
7919 case lltok::kw_typeCheckedLoadVCalls:
7920 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
7921 TypeIdInfo.TypeCheckedLoadVCalls))
7922 return true;
7923 break;
7924 case lltok::kw_typeTestAssumeConstVCalls:
7925 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
7926 TypeIdInfo.TypeTestAssumeConstVCalls))
7927 return true;
7928 break;
7929 case lltok::kw_typeCheckedLoadConstVCalls:
7930 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
7931 TypeIdInfo.TypeCheckedLoadConstVCalls))
7932 return true;
7933 break;
7934 default:
7935 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
7936 }
7937 } while (EatIfPresent(lltok::comma));
7938
7939 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7940 return true;
7941
7942 return false;
7943}
7944
7945/// TypeTests
7946/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
7947/// [',' (SummaryID | UInt64)]* ')'
7948bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
7949 assert(Lex.getKind() == lltok::kw_typeTests);
7950 Lex.Lex();
7951
7952 if (ParseToken(lltok::colon, "expected ':' here") ||
7953 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
7954 return true;
7955
7956 IdToIndexMapType IdToIndexMap;
7957 do {
7958 GlobalValue::GUID GUID = 0;
7959 if (Lex.getKind() == lltok::SummaryID) {
7960 unsigned ID = Lex.getUIntVal();
7961 LocTy Loc = Lex.getLoc();
7962 // Keep track of the TypeTests array index needing a forward reference.
7963 // We will save the location of the GUID needing an update, but
7964 // can only do so once the std::vector is finalized.
7965 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
7966 Lex.Lex();
7967 } else if (ParseUInt64(GUID))
7968 return true;
7969 TypeTests.push_back(GUID);
7970 } while (EatIfPresent(lltok::comma));
7971
7972 // Now that the TypeTests vector is finalized, it is safe to save the
7973 // locations of any forward GV references that need updating later.
7974 for (auto I : IdToIndexMap) {
7975 for (auto P : I.second) {
7976 assert(TypeTests[P.first] == 0 &&
7977 "Forward referenced type id GUID expected to be 0");
7978 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
7979 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
7980 FwdRef.first->second.push_back(
7981 std::make_pair(&TypeTests[P.first], P.second));
7982 }
7983 }
7984
7985 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
7986 return true;
7987
7988 return false;
7989}
7990
7991/// VFuncIdList
7992/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
7993bool LLParser::ParseVFuncIdList(
7994 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
7995 assert(Lex.getKind() == Kind);
7996 Lex.Lex();
7997
7998 if (ParseToken(lltok::colon, "expected ':' here") ||
7999 ParseToken(lltok::lparen, "expected '(' here"))
8000 return true;
8001
8002 IdToIndexMapType IdToIndexMap;
8003 do {
8004 FunctionSummary::VFuncId VFuncId;
8005 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8006 return true;
8007 VFuncIdList.push_back(VFuncId);
8008 } while (EatIfPresent(lltok::comma));
8009
8010 if (ParseToken(lltok::rparen, "expected ')' here"))
8011 return true;
8012
8013 // Now that the VFuncIdList vector is finalized, it is safe to save the
8014 // locations of any forward GV references that need updating later.
8015 for (auto I : IdToIndexMap) {
8016 for (auto P : I.second) {
8017 assert(VFuncIdList[P.first].GUID == 0 &&
8018 "Forward referenced type id GUID expected to be 0");
8019 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8020 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8021 FwdRef.first->second.push_back(
8022 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8023 }
8024 }
8025
8026 return false;
8027}
8028
8029/// ConstVCallList
8030/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8031bool LLParser::ParseConstVCallList(
8032 lltok::Kind Kind,
8033 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8034 assert(Lex.getKind() == Kind);
8035 Lex.Lex();
8036
8037 if (ParseToken(lltok::colon, "expected ':' here") ||
8038 ParseToken(lltok::lparen, "expected '(' here"))
8039 return true;
8040
8041 IdToIndexMapType IdToIndexMap;
8042 do {
8043 FunctionSummary::ConstVCall ConstVCall;
8044 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8045 return true;
8046 ConstVCallList.push_back(ConstVCall);
8047 } while (EatIfPresent(lltok::comma));
8048
8049 if (ParseToken(lltok::rparen, "expected ')' here"))
8050 return true;
8051
8052 // Now that the ConstVCallList vector is finalized, it is safe to save the
8053 // locations of any forward GV references that need updating later.
8054 for (auto I : IdToIndexMap) {
8055 for (auto P : I.second) {
8056 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8057 "Forward referenced type id GUID expected to be 0");
8058 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8059 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8060 FwdRef.first->second.push_back(
8061 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8062 }
8063 }
8064
8065 return false;
8066}
8067
8068/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008069/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008070bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8071 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008072 if (ParseToken(lltok::lparen, "expected '(' here") ||
8073 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8074 return true;
8075
8076 if (EatIfPresent(lltok::comma))
8077 if (ParseArgs(ConstVCall.Args))
8078 return true;
8079
8080 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008081 return true;
8082
8083 return false;
8084}
8085
8086/// VFuncId
8087/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8088/// 'offset' ':' UInt64 ')'
8089bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8090 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8091 assert(Lex.getKind() == lltok::kw_vFuncId);
8092 Lex.Lex();
8093
8094 if (ParseToken(lltok::colon, "expected ':' here") ||
8095 ParseToken(lltok::lparen, "expected '(' here"))
8096 return true;
8097
8098 if (Lex.getKind() == lltok::SummaryID) {
8099 VFuncId.GUID = 0;
8100 unsigned ID = Lex.getUIntVal();
8101 LocTy Loc = Lex.getLoc();
8102 // Keep track of the array index needing a forward reference.
8103 // We will save the location of the GUID needing an update, but
8104 // can only do so once the caller's std::vector is finalized.
8105 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8106 Lex.Lex();
8107 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8108 ParseToken(lltok::colon, "expected ':' here") ||
8109 ParseUInt64(VFuncId.GUID))
8110 return true;
8111
8112 if (ParseToken(lltok::comma, "expected ',' here") ||
8113 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8114 ParseToken(lltok::colon, "expected ':' here") ||
8115 ParseUInt64(VFuncId.Offset) ||
8116 ParseToken(lltok::rparen, "expected ')' here"))
8117 return true;
8118
8119 return false;
8120}
8121
8122/// GVFlags
8123/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8124/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8125/// 'dsoLocal' ':' Flag ')'
8126bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8127 assert(Lex.getKind() == lltok::kw_flags);
8128 Lex.Lex();
8129
8130 bool HasLinkage;
8131 if (ParseToken(lltok::colon, "expected ':' here") ||
8132 ParseToken(lltok::lparen, "expected '(' here") ||
8133 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8134 ParseToken(lltok::colon, "expected ':' here"))
8135 return true;
8136
8137 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8138 assert(HasLinkage && "Linkage not optional in summary entry");
8139 Lex.Lex();
8140
8141 unsigned Flag;
8142 if (ParseToken(lltok::comma, "expected ',' here") ||
8143 ParseToken(lltok::kw_notEligibleToImport,
8144 "expected 'notEligibleToImport' here") ||
8145 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8146 return true;
8147 GVFlags.NotEligibleToImport = Flag;
8148
8149 if (ParseToken(lltok::comma, "expected ',' here") ||
8150 ParseToken(lltok::kw_live, "expected 'live' here") ||
8151 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8152 return true;
8153 GVFlags.Live = Flag;
8154
8155 if (ParseToken(lltok::comma, "expected ',' here") ||
8156 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8157 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8158 return true;
8159 GVFlags.DSOLocal = Flag;
8160
8161 if (ParseToken(lltok::rparen, "expected ')' here"))
8162 return true;
8163
8164 return false;
8165}
8166
8167/// ModuleReference
8168/// ::= 'module' ':' UInt
8169bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8170 // Parse module id.
8171 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8172 ParseToken(lltok::colon, "expected ':' here") ||
8173 ParseToken(lltok::SummaryID, "expected module ID"))
8174 return true;
8175
8176 unsigned ModuleID = Lex.getUIntVal();
8177 auto I = ModuleIdMap.find(ModuleID);
8178 // We should have already parsed all module IDs
8179 assert(I != ModuleIdMap.end());
8180 ModulePath = I->second;
8181 return false;
8182}
8183
8184/// GVReference
8185/// ::= SummaryID
8186bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8187 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8188 return true;
8189
8190 GVId = Lex.getUIntVal();
8191
8192 // Check if we already have a VI for this GV
8193 if (GVId < NumberedValueInfos.size()) {
8194 assert(NumberedValueInfos[GVId] != EmptyVI);
8195 VI = NumberedValueInfos[GVId];
8196 } else
8197 // We will create a forward reference to the stored location.
8198 VI = EmptyVI;
8199
8200 return false;
8201}