blob: 9bb3ca145c2d4f02d03a36e4b441c1c2990d1380 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerac161bf2009-01-02 07:01:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000019#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000020#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000045#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000046#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000047#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000048#include <algorithm>
49#include <cassert>
50#include <cstring>
51#include <iterator>
52#include <vector>
53
Chris Lattnerac161bf2009-01-02 07:01:27 +000054using namespace llvm;
55
Chris Lattner229907c2011-07-18 04:54:35 +000056static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000057 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000061}
62
Chris Lattner3822f632009-01-02 08:05:26 +000063/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000064bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000065 // Prime the lexer.
66 Lex.Lex();
67
Mehdi Amini50af49f2016-04-02 03:46:17 +000068 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
Teresa Johnson63ee0e72018-06-26 13:56:49 +000073 return ParseTopLevelEntities() || ValidateEndOfModule() ||
74 ValidateEndOfIndex();
Chris Lattnerac161bf2009-01-02 07:01:27 +000075}
76
Alex Lorenz1de2acd2015-08-21 21:32:39 +000077bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000080 Lex.Lex();
81
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
88}
89
Quentin Colombetdafed5d2016-03-08 00:37:07 +000090bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000092 restoreParsingState(Slots);
93 Lex.Lex();
94
Quentin Colombetdafed5d2016-03-08 00:37:07 +000095 Read = 0;
96 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000097 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
102
Quentin Colombet81e72b42016-03-07 22:09:05 +0000103 return false;
104}
105
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000106void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
117}
118
Chris Lattnerac161bf2009-01-02 07:01:27 +0000119/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120/// module.
121bool LLParser::ValidateEndOfModule() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000122 if (!M)
123 return false;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000124 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000128 AttrBuilder B;
129
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000132
133 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000134 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000151 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000159 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000162 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000165 II->setAttributes(AS);
Craig Topper784929d2019-02-08 20:48:56 +0000166 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167 AttributeList AS = CBI->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 CBI->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000174 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175 AttrBuilder Attrs(GV->getAttributes());
176 Attrs.merge(B);
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000178 } else {
179 llvm_unreachable("invalid object with forward attribute group reference");
180 }
181 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000182
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses.empty())
186 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000188
David Majnemer19b51052015-02-11 07:43:56 +0000189 for (const auto &NT : NumberedTypes)
190 if (NT.second.second.isValid())
191 return Error(NT.second.second,
192 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000193
194 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196 if (I->second.second.isValid())
197 return Error(I->second.second,
198 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000199
David Majnemerdad0a642014-06-27 18:19:56 +0000200 if (!ForwardRefComdats.empty())
201 return Error(ForwardRefComdats.begin()->second,
202 "use of undefined comdat '$" +
203 ForwardRefComdats.begin()->first + "'");
204
Chris Lattnerac161bf2009-01-02 07:01:27 +0000205 if (!ForwardRefVals.empty())
206 return Error(ForwardRefVals.begin()->second.second,
207 "use of undefined value '@" + ForwardRefVals.begin()->first +
208 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000209
Chris Lattnerac161bf2009-01-02 07:01:27 +0000210 if (!ForwardRefValIDs.empty())
211 return Error(ForwardRefValIDs.begin()->second.second,
212 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000213 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000214
Devang Pateld2541152009-07-08 19:23:54 +0000215 if (!ForwardRefMDNodes.empty())
216 return Error(ForwardRefMDNodes.begin()->second.second,
217 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000218 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000219
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000220 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000221 for (auto &N : NumberedMetadata) {
222 if (N.second && !N.second->isResolved())
223 N.second->resolveCycles();
224 }
Devang Pateld2541152009-07-08 19:23:54 +0000225
Mehdi Aminie4709272016-09-14 22:29:59 +0000226 for (auto *Inst : InstsWithTBAATag) {
227 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
229 auto *UpgradedMD = UpgradeTBAANode(*MD);
230 if (MD != UpgradedMD)
231 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
232 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000233
Chris Lattnerac161bf2009-01-02 07:01:27 +0000234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000236 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000237
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242 Function *F = &*FI++;
243 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244 F->replaceAllUsesWith(Remangled.getValue());
245 F->eraseFromParent();
246 }
247 }
248
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000249 if (UpgradeDebugInfo)
250 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000251
Manman Renb5d7ff42016-05-25 23:14:48 +0000252 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000253 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000254
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000255 if (!Slots)
256 return false;
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots->GlobalValues = std::move(NumberedVals);
261 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000262 for (const auto &I : NamedTypes)
263 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264 for (const auto &I : NumberedTypes)
265 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000266
Chris Lattnerac161bf2009-01-02 07:01:27 +0000267 return false;
268}
269
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000270/// Do final validity and sanity checks at the end of the index.
271bool LLParser::ValidateEndOfIndex() {
272 if (!Index)
273 return false;
274
275 if (!ForwardRefValueInfos.empty())
276 return Error(ForwardRefValueInfos.begin()->second.front().second,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos.begin()->first) + "'");
279
280 if (!ForwardRefAliasees.empty())
281 return Error(ForwardRefAliasees.begin()->second.front().second,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees.begin()->first) + "'");
284
285 if (!ForwardRefTypeIds.empty())
286 return Error(ForwardRefTypeIds.begin()->second.front().second,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds.begin()->first) + "'");
289
290 return false;
291}
292
Chris Lattnerac161bf2009-01-02 07:01:27 +0000293//===----------------------------------------------------------------------===//
294// Top-Level Entities
295//===----------------------------------------------------------------------===//
296
297bool LLParser::ParseTopLevelEntities() {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000298 // If there is no Module, then parse just the summary index entries.
299 if (!M) {
300 while (true) {
301 switch (Lex.getKind()) {
302 case lltok::Eof:
303 return false;
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
306 return true;
307 break;
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
310 return true;
311 break;
312 default:
313 // Skip everything else
314 Lex.Lex();
315 }
316 }
317 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000318 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 switch (Lex.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 case lltok::kw_declare: if (ParseDeclare()) return true; break;
323 case lltok::kw_define: if (ParseDefine()) return true; break;
324 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000326 case lltok::kw_source_filename:
327 if (ParseSourceFileName())
328 return true;
329 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000330 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000331 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000333 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000334 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000335 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000336 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000337 case lltok::SummaryID:
338 if (ParseSummaryEntry())
339 return true;
340 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000341 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000342 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000343 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000345 if (ParseUseListOrderBB())
346 return true;
347 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348 }
349 }
350}
351
Chris Lattnerac161bf2009-01-02 07:01:27 +0000352/// toplevelentity
353/// ::= 'module' 'asm' STRINGCONSTANT
354bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module);
356 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000357
358 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000361
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000362 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000363 return false;
364}
365
366/// toplevelentity
367/// ::= 'target' 'triple' '=' STRINGCONSTANT
368/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000371 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372 switch (Lex.Lex()) {
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
375 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000379 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380 return false;
381 case lltok::kw_datalayout:
382 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 return false;
389 }
390}
391
Bill Wendling706d3d62012-11-28 08:41:48 +0000392/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000393/// ::= 'source_filename' '=' STRINGCONSTANT
394bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000396 Lex.Lex();
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000398 ParseStringConstant(SourceFileName))
Teresa Johnson83c517c2016-03-30 18:15:08 +0000399 return true;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000400 if (M)
401 M->setSourceFileName(SourceFileName);
Teresa Johnson83c517c2016-03-30 18:15:08 +0000402 return false;
403}
404
405/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000406/// ::= 'deplibs' '=' '[' ']'
407/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408/// FIXME: Remove in 4.0. Currently parse, but ignore.
409bool LLParser::ParseDepLibs() {
410 assert(Lex.getKind() == lltok::kw_deplibs);
411 Lex.Lex();
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414 return true;
415
416 if (EatIfPresent(lltok::rsquare))
417 return false;
418
419 do {
420 std::string Str;
421 if (ParseStringConstant(Str)) return true;
422 } while (EatIfPresent(lltok::comma));
423
424 return ParseToken(lltok::rsquare, "expected ']' at end of list");
425}
426
Dan Gohman466876b2009-08-12 23:32:33 +0000427/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000428/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000430 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000432 Lex.Lex(); // eat LocalVarID;
433
434 if (ParseToken(lltok::equal, "expected '=' after name") ||
435 ParseToken(lltok::kw_type, "expected 'type' after '='"))
436 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437
Craig Topper2617dcc2014-04-15 06:32:26 +0000438 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000439 if (ParseStructDefinition(TypeLoc, "",
440 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000442 if (!isa<StructType>(Result)) {
443 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
444 if (Entry.first)
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000449
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 return false;
451}
452
453/// toplevelentity
454/// ::= LocalVar '=' 'type' type
455bool LLParser::ParseNamedType() {
456 std::string Name = Lex.getStrVal();
457 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000458 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000459
Chris Lattner3822f632009-01-02 08:05:26 +0000460 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000462 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000463
Craig Topper2617dcc2014-04-15 06:32:26 +0000464 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000465 if (ParseStructDefinition(NameLoc, Name,
466 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000467
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000468 if (!isa<StructType>(Result)) {
469 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
470 if (Entry.first)
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000474 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000475
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000476 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000477}
478
Chris Lattnerac161bf2009-01-02 07:01:27 +0000479/// toplevelentity
480/// ::= 'declare' FunctionHeader
481bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare);
483 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000484
Peter Collingbourne21521892016-06-21 23:42:48 +0000485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
487 unsigned MDK;
488 MDNode *N;
489 if (ParseMetadataAttachment(MDK, N))
490 return true;
491 MDs.push_back({MDK, N});
492 }
493
Chris Lattnerac161bf2009-01-02 07:01:27 +0000494 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000495 if (ParseFunctionHeader(F, false))
496 return true;
497 for (auto &MD : MDs)
498 F->addMetadata(MD.first, *MD.second);
499 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000500}
501
502/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000503/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000504bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define);
506 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000507
Chris Lattnerac161bf2009-01-02 07:01:27 +0000508 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000509 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000510 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000511 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000512}
513
Chris Lattner3822f632009-01-02 08:05:26 +0000514/// ParseGlobalType
515/// ::= 'constant'
516/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000517bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
519 IsConstant = true;
520 else if (Lex.getKind() == lltok::kw_global)
521 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000522 else {
523 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000524 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000525 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000526 Lex.Lex();
527 return false;
528}
529
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000530bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr &UnnamedAddr) {
532 if (EatIfPresent(lltok::kw_unnamed_addr))
533 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
536 else
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
538 return false;
539}
540
Dan Gohman466876b2009-08-12 23:32:33 +0000541/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000542/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000543/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000545/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000546/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000547/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000549/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000550bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID = NumberedVals.size();
552 std::string Name;
553 LocTy NameLoc = Lex.getLoc();
554
555 // Handle the GlobalID form.
556 if (Lex.getKind() == lltok::GlobalID) {
557 if (Lex.getUIntVal() != VarID)
558 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000559 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000560 Lex.Lex(); // eat GlobalID;
561
562 if (ParseToken(lltok::equal, "expected '=' after name"))
563 return true;
564 }
565
566 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000567 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000568 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000569 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000570 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000574 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000575
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000576 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000577 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000578 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000579
580 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000581 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000582}
583
Chris Lattnerac161bf2009-01-02 07:01:27 +0000584/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000585/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000586/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000588/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000589bool LLParser::ParseNamedGlobal() {
590 assert(Lex.getKind() == lltok::GlobalVar);
591 LocTy NameLoc = Lex.getLoc();
592 std::string Name = Lex.getStrVal();
593 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000594
Chris Lattnerac161bf2009-01-02 07:01:27 +0000595 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000596 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000597 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000598 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000599 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000604 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000605
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000606 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000607 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000608 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000609
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000610 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000612}
613
David Majnemerdad0a642014-06-27 18:19:56 +0000614bool LLParser::parseComdat() {
615 assert(Lex.getKind() == lltok::ComdatVar);
616 std::string Name = Lex.getStrVal();
617 LocTy NameLoc = Lex.getLoc();
618 Lex.Lex();
619
620 if (ParseToken(lltok::equal, "expected '=' here"))
621 return true;
622
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
625
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
628 default:
629 return TokError("unknown selection kind");
630 case lltok::kw_any:
631 SK = Comdat::Any;
632 break;
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
635 break;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
638 break;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
641 break;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
644 break;
645 }
646 Lex.Lex();
647
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
653
654 Comdat *C;
655 if (I != ComdatSymTab.end())
656 C = &I->second;
657 else
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
660
661 return false;
662}
663
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000664// MDString:
665// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000666bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000667 std::string Str;
668 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000669 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000670 return false;
671}
672
673// MDNode:
674// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000675bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000676 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000677 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000678 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000679 if (ParseUInt32(MID))
680 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
Chris Lattner8eff0152010-04-01 05:14:45 +0000682 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000683 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000684 Result = NumberedMetadata[MID];
685 return false;
686 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000687
Chris Lattner8eff0152010-04-01 05:14:45 +0000688 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000689 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000690 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000691
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000692 Result = FwdRef.first.get();
693 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000694 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000695}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000696
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000697/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000698/// !foo = !{ !1, !2 }
699bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000700 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000701 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000702 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000703
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000704 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000705 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000706 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000707 return true;
708
Dan Gohman2637cc12010-07-21 23:38:33 +0000709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000710 if (Lex.getKind() != lltok::rbrace)
711 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000712 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex.getKind() == lltok::MetadataVar &&
717 Lex.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N, /*IsDistinct=*/false))
719 return true;
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721 ParseMDNodeID(N)) {
722 return true;
723 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000724 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000725 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000726
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000727 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000728}
729
Devang Patel39e64d42009-07-01 19:21:12 +0000730/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000731/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000732bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000733 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000734 Lex.Lex();
735 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000736
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000737 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000738 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000739 ParseToken(lltok::equal, "expected '=' here"))
740 return true;
741
742 // Detect common error, from old metadata syntax.
743 if (Lex.getKind() == lltok::Type)
744 return TokError("unexpected type in metadata definition");
745
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000746 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000747 if (Lex.getKind() == lltok::MetadataVar) {
748 if (ParseSpecializedMDNode(Init, IsDistinct))
749 return true;
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000752 return true;
753
Chris Lattnerfc58af22009-12-30 04:51:58 +0000754 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000755 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000756 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000757 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000758 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000759
Chris Lattnerfc58af22009-12-30 04:51:58 +0000760 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
761 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000762 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000763 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000764 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000765 }
766
Devang Patel39e64d42009-07-01 19:21:12 +0000767 return false;
768}
769
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000770// Skips a single module summary entry.
771bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000776 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777 Lex.getKind() != lltok::kw_typeid)
778 return TokError(
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780 Lex.Lex();
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783 return true;
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen = 1;
787 do {
788 switch (Lex.getKind()) {
789 case lltok::lparen:
790 NumOpenParen++;
791 break;
792 case lltok::rparen:
793 NumOpenParen--;
794 break;
795 case lltok::Eof:
796 return TokError("found end of file while parsing summary entry");
797 default:
798 // Skip everything in between parentheses.
799 break;
800 }
801 Lex.Lex();
802 } while (NumOpenParen > 0);
803 return false;
804}
805
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000806/// SummaryEntry
807/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000808bool LLParser::ParseSummaryEntry() {
809 assert(Lex.getKind() == lltok::SummaryID);
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000810 unsigned SummaryID = Lex.getUIntVal();
811
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex.setIgnoreColonInIdentifiers(true);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000815
816 Lex.Lex();
817 if (ParseToken(lltok::equal, "expected '=' here"))
818 return true;
819
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000820 // If we don't have an index object, skip the summary entry.
821 if (!Index)
822 return SkipModuleSummaryEntry();
823
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000824 bool result = false;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000825 switch (Lex.getKind()) {
826 case lltok::kw_gv:
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000827 result = ParseGVEntry(SummaryID);
828 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000829 case lltok::kw_module:
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000830 result = ParseModuleEntry(SummaryID);
831 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000832 case lltok::kw_typeid:
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000833 result = ParseTypeIdEntry(SummaryID);
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000834 break;
Teresa Johnsona7004362019-07-02 19:38:02 +0000835 case lltok::kw_typeidCompatibleVTable:
836 result = ParseTypeIdCompatibleVtableEntry(SummaryID);
837 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000838 default:
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000839 result = Error(Lex.getLoc(), "unexpected summary kind");
840 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000841 }
842 Lex.setIgnoreColonInIdentifiers(false);
Teresa Johnsonb3203ec2019-05-01 16:26:59 +0000843 return result;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000844}
845
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000846static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
847 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
848 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
849}
850
Rafael Espindolae4b02312018-01-11 22:15:05 +0000851// If there was an explicit dso_local, update GV. In the absence of an explicit
852// dso_local we keep the default value.
853static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
854 if (DSOLocal)
855 GV.setDSOLocal(true);
856}
857
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000858/// parseIndirectSymbol:
Fangrui Songf78650a2018-07-30 19:41:25 +0000859/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
Sean Fertilec70d28b2017-10-26 15:00:26 +0000860/// OptionalVisibility OptionalDLLStorageClass
861/// OptionalThreadLocal OptionalUnnamedAddr
Peter Collingbourne31fda092019-05-29 03:29:01 +0000862/// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
Rafael Espindola6b238632014-05-16 19:35:39 +0000863///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000864/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000865/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866///
Peter Collingbourne31fda092019-05-29 03:29:01 +0000867/// IndirectSymbolAttr
868/// ::= ',' 'partition' StringConstant
869///
Eric Christopher536f0a92015-05-28 23:07:39 +0000870/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000872bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
873 unsigned L, unsigned Visibility,
874 unsigned DLLStorageClass, bool DSOLocal,
875 GlobalVariable::ThreadLocalMode TLM,
876 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000877 bool IsAlias;
878 if (Lex.getKind() == lltok::kw_alias)
879 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000880 else if (Lex.getKind() == lltok::kw_ifunc)
881 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000882 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000883 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000884 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885
Rafael Espindola78527052013-10-06 15:10:43 +0000886 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
887
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000888 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000889 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000890
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000891 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000892 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000893 "symbol with local linkage must have default visibility");
894
David Blaikie2f408302015-09-11 03:22:04 +0000895 Type *Ty;
896 LocTy ExplicitTypeLoc = Lex.getLoc();
897 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000898 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000899 return true;
900
Rafael Espindola64c1e182014-06-03 02:41:57 +0000901 Constant *Aliasee;
902 LocTy AliaseeLoc = Lex.getLoc();
903 if (Lex.getKind() != lltok::kw_bitcast &&
904 Lex.getKind() != lltok::kw_getelementptr &&
905 Lex.getKind() != lltok::kw_addrspacecast &&
906 Lex.getKind() != lltok::kw_inttoptr) {
907 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000908 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000909 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000910 // The bitcast dest type is not present, it is implied by the dest type.
911 ValID ID;
912 if (ParseValID(ID))
913 return true;
914 if (ID.Kind != ValID::t_Constant)
915 return Error(AliaseeLoc, "invalid aliasee");
916 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000917 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
Rafael Espindola64c1e182014-06-03 02:41:57 +0000919 Type *AliaseeType = Aliasee->getType();
920 auto *PTy = dyn_cast<PointerType>(AliaseeType);
921 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000922 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000923 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000924
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000925 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000926 return Error(
927 ExplicitTypeLoc,
928 "explicit pointee type doesn't match operand's pointee type");
929
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000930 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
931 return Error(
932 ExplicitTypeLoc,
933 "explicit pointee type should be a function type");
934
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000935 GlobalValue *GVal = nullptr;
936
937 // See if the alias was forward referenced, if so, prepare to replace the
938 // forward reference.
939 if (!Name.empty()) {
940 GVal = M->getNamedValue(Name);
941 if (GVal) {
942 if (!ForwardRefVals.erase(Name))
943 return Error(NameLoc, "redefinition of global '@" + Name + "'");
944 }
945 } else {
946 auto I = ForwardRefValIDs.find(NumberedVals.size());
947 if (I != ForwardRefValIDs.end()) {
948 GVal = I->second.first;
949 ForwardRefValIDs.erase(I);
950 }
951 }
952
Chris Lattnerac161bf2009-01-02 07:01:27 +0000953 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000954 std::unique_ptr<GlobalIndirectSymbol> GA;
955 if (IsAlias)
956 GA.reset(GlobalAlias::create(Ty, AddrSpace,
957 (GlobalValue::LinkageTypes)Linkage, Name,
958 Aliasee, /*Parent*/ nullptr));
959 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000960 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
961 (GlobalValue::LinkageTypes)Linkage, Name,
962 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000963 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000964 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000965 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000966 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000967 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000968
Peter Collingbourne31fda092019-05-29 03:29:01 +0000969 // At this point we've parsed everything except for the IndirectSymbolAttrs.
970 // Now parse them if there are any.
971 while (Lex.getKind() == lltok::comma) {
972 Lex.Lex();
973
974 if (Lex.getKind() == lltok::kw_partition) {
975 Lex.Lex();
976 GA->setPartition(Lex.getStrVal());
977 if (ParseToken(lltok::StringConstant, "expected partition string"))
978 return true;
979 } else {
980 return TokError("unknown alias or ifunc property!");
981 }
982 }
983
Rafael Espindola54fc2982015-06-17 17:53:31 +0000984 if (Name.empty())
985 NumberedVals.push_back(GA.get());
986
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000987 if (GVal) {
988 // Verify that types agree.
989 if (GVal->getType() != GA->getType())
990 return Error(
991 ExplicitTypeLoc,
992 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000993
Chris Lattnerac161bf2009-01-02 07:01:27 +0000994 // If they agree, just RAUW the old value with the alias and remove the
995 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000996 GVal->replaceAllUsesWith(GA.get());
997 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000998 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000999
Chris Lattnerac161bf2009-01-02 07:01:27 +00001000 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001001 if (IsAlias)
1002 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1003 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001004 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00001005 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001006
Rafael Espindolaaa273822014-05-09 21:49:17 +00001007 // The module owns this now
1008 GA.release();
1009
Chris Lattnerac161bf2009-01-02 07:01:27 +00001010 return false;
1011}
1012
1013/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +00001014/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1015/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +00001016/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +00001017/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +00001018/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1019/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1020/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1021/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00001022///
Eric Christopher536f0a92015-05-28 23:07:39 +00001023/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +00001024/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001025///
1026bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1027 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001028 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001029 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001030 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00001031 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1032 return Error(NameLoc,
1033 "symbol with local linkage must have default visibility");
1034
Chris Lattnerac161bf2009-01-02 07:01:27 +00001035 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001036 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001037 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001039
Craig Topper2617dcc2014-04-15 06:32:26 +00001040 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001041 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001042 ParseOptionalToken(lltok::kw_externally_initialized,
1043 IsExternallyInitialized,
1044 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001045 ParseGlobalType(IsConstant) ||
1046 ParseType(Ty, TyLoc))
1047 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001048
Chris Lattnerac161bf2009-01-02 07:01:27 +00001049 // If the linkage is specified and is external, then no initializer is
1050 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +00001051 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +00001052 if (!HasLinkage ||
1053 !GlobalValue::isValidDeclarationLinkage(
1054 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001055 if (ParseGlobalValue(Ty, Init))
1056 return true;
1057 }
1058
David Majnemer49b3d9b2015-02-16 08:41:08 +00001059 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +00001060 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001061
David Majnemer598bd052014-12-09 05:56:09 +00001062 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001063
1064 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +00001065 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +00001066 GVal = M->getNamedValue(Name);
1067 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +00001068 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +00001069 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00001070 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +00001072 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00001073 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +00001074 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001075 ForwardRefValIDs.erase(I);
1076 }
1077 }
1078
David Majnemer598bd052014-12-09 05:56:09 +00001079 GlobalVariable *GV;
1080 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001081 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1082 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001083 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +00001085 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001086 return Error(TyLoc,
1087 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001088
David Majnemer598bd052014-12-09 05:56:09 +00001089 GV = cast<GlobalVariable>(GVal);
1090
Chris Lattnerac161bf2009-01-02 07:01:27 +00001091 // Move the forward-reference to the correct spot in the module.
1092 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1093 }
1094
1095 if (Name.empty())
1096 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001097
Chris Lattnerac161bf2009-01-02 07:01:27 +00001098 // Set the parsed properties on the global.
1099 if (Init)
1100 GV->setInitializer(Init);
1101 GV->setConstant(IsConstant);
1102 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001103 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001104 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001105 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001106 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001107 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001108 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001109
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110 // Parse attributes on the global.
1111 while (Lex.getKind() == lltok::comma) {
1112 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001113
Chris Lattnerac161bf2009-01-02 07:01:27 +00001114 if (Lex.getKind() == lltok::kw_section) {
1115 Lex.Lex();
1116 GV->setSection(Lex.getStrVal());
1117 if (ParseToken(lltok::StringConstant, "expected global section string"))
1118 return true;
Peter Collingbourne31fda092019-05-29 03:29:01 +00001119 } else if (Lex.getKind() == lltok::kw_partition) {
1120 Lex.Lex();
1121 GV->setPartition(Lex.getStrVal());
1122 if (ParseToken(lltok::StringConstant, "expected partition string"))
1123 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001124 } else if (Lex.getKind() == lltok::kw_align) {
1125 unsigned Alignment;
1126 if (ParseOptionalAlignment(Alignment)) return true;
1127 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001128 } else if (Lex.getKind() == lltok::MetadataVar) {
1129 if (ParseGlobalObjectMetadataAttachment(*GV))
1130 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001131 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001132 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001133 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001134 return true;
1135 if (C)
1136 GV->setComdat(C);
1137 else
1138 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001139 }
1140 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001141
Javed Absarf3d79042017-05-11 12:28:08 +00001142 AttrBuilder Attrs;
1143 LocTy BuiltinLoc;
1144 std::vector<unsigned> FwdRefAttrGrps;
1145 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1146 return true;
1147 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1148 GV->setAttributes(AttributeSet::get(Context, Attrs));
1149 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1150 }
1151
Chris Lattnerac161bf2009-01-02 07:01:27 +00001152 return false;
1153}
1154
Bill Wendling63b88192013-02-06 06:52:58 +00001155/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001156/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001157bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001158 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001159 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001160 Lex.Lex();
1161
David Majnemerb39e22b2014-12-09 18:33:57 +00001162 if (Lex.getKind() != lltok::AttrGrpID)
1163 return TokError("expected attribute group id");
1164
Bill Wendling63b88192013-02-06 06:52:58 +00001165 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001166 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001167 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001168 Lex.Lex();
1169
1170 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001171 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001172 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001173 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001174 ParseToken(lltok::rbrace, "expected end of attribute group"))
1175 return true;
1176
Bill Wendlingb32b0412013-02-08 06:32:06 +00001177 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001178 return Error(AttrGrpLoc, "attribute group has no attributes");
1179
1180 return false;
1181}
1182
Bill Wendling8b0321d2013-02-08 00:52:31 +00001183/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001184/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001185bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1186 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001187 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001188 bool HaveError = false;
1189
1190 B.clear();
1191
Bill Wendling63b88192013-02-06 06:52:58 +00001192 while (true) {
1193 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001194 if (Token == lltok::kw_builtin)
1195 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001196 switch (Token) {
1197 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001198 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001199 return Error(Lex.getLoc(), "unterminated attribute group");
1200 case lltok::rbrace:
1201 // Finished.
1202 return false;
1203
Bill Wendlingb32b0412013-02-08 06:32:06 +00001204 case lltok::AttrGrpID: {
1205 // Allow a function to reference an attribute group:
1206 //
1207 // define void @foo() #1 { ... }
1208 if (inAttrGrp)
1209 HaveError |=
1210 Error(Lex.getLoc(),
1211 "cannot have an attribute group reference in an attribute group");
1212
1213 unsigned AttrGrpNum = Lex.getUIntVal();
1214 if (inAttrGrp) break;
1215
1216 // Save the reference to the attribute group. We'll fill it in later.
1217 FwdRefAttrGrps.push_back(AttrGrpNum);
1218 break;
1219 }
Bill Wendling63b88192013-02-06 06:52:58 +00001220 // Target-dependent attributes:
1221 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001222 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001223 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001224 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001225 }
1226
1227 // Target-independent attributes:
1228 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001229 // As a hack, we allow function alignment to be initially parsed as an
1230 // attribute on a function declaration/definition or added to an attribute
1231 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001232 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001233 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001234 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001235 if (ParseToken(lltok::equal, "expected '=' here") ||
1236 ParseUInt32(Alignment))
1237 return true;
1238 } else {
1239 if (ParseOptionalAlignment(Alignment))
1240 return true;
1241 }
Bill Wendling63b88192013-02-06 06:52:58 +00001242 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001243 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001244 }
1245 case lltok::kw_alignstack: {
1246 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001247 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001248 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001249 if (ParseToken(lltok::equal, "expected '=' here") ||
1250 ParseUInt32(Alignment))
1251 return true;
1252 } else {
1253 if (ParseOptionalStackAlignment(Alignment))
1254 return true;
1255 }
Bill Wendling63b88192013-02-06 06:52:58 +00001256 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001257 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001258 }
George Burgess IV278199f2016-04-12 01:05:35 +00001259 case lltok::kw_allocsize: {
1260 unsigned ElemSizeArg;
1261 Optional<unsigned> NumElemsArg;
1262 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1263 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1264 return true;
1265 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1266 continue;
1267 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001268 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1269 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1270 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1271 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1272 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001273 case lltok::kw_inaccessiblememonly:
1274 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1275 case lltok::kw_inaccessiblemem_or_argmemonly:
1276 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001277 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1278 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1279 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1280 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1281 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1282 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
Brian Homerdingb4b21d82019-07-08 15:57:56 +00001283 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001284 case lltok::kw_noimplicitfloat:
1285 B.addAttribute(Attribute::NoImplicitFloat); break;
1286 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1287 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1288 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1289 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Stefan Stipanovic06263672019-07-11 21:37:40 +00001290 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001291 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001292 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001293 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001294 case lltok::kw_optforfuzzing:
1295 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001296 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1297 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1298 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1299 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1300 case lltok::kw_returns_twice:
1301 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001302 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001303 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1304 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1305 case lltok::kw_sspstrong:
1306 B.addAttribute(Attribute::StackProtectStrong); break;
1307 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001308 case lltok::kw_shadowcallstack:
1309 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001310 case lltok::kw_sanitize_address:
1311 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001312 case lltok::kw_sanitize_hwaddress:
1313 B.addAttribute(Attribute::SanitizeHWAddress); break;
Evgeniy Stepanovc5e7f562019-07-15 20:02:23 +00001314 case lltok::kw_sanitize_memtag:
1315 B.addAttribute(Attribute::SanitizeMemTag); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001316 case lltok::kw_sanitize_thread:
1317 B.addAttribute(Attribute::SanitizeThread); break;
1318 case lltok::kw_sanitize_memory:
1319 B.addAttribute(Attribute::SanitizeMemory); break;
Chandler Carruth664aa862018-09-04 12:38:00 +00001320 case lltok::kw_speculative_load_hardening:
1321 B.addAttribute(Attribute::SpeculativeLoadHardening);
1322 break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001323 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001324 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Johannes Doerfert3b775832019-06-27 15:51:40 +00001325 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001326 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001327
1328 // Error handling.
1329 case lltok::kw_inreg:
1330 case lltok::kw_signext:
1331 case lltok::kw_zeroext:
1332 HaveError |=
1333 Error(Lex.getLoc(),
1334 "invalid use of attribute on a function");
1335 break;
1336 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001337 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001338 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001339 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001340 case lltok::kw_nest:
1341 case lltok::kw_noalias:
1342 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001343 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001344 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001345 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001346 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001347 case lltok::kw_swiftself:
Matt Arsenaultcaf13162019-03-12 21:02:54 +00001348 case lltok::kw_immarg:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001349 HaveError |=
1350 Error(Lex.getLoc(),
1351 "invalid use of parameter-only attribute on a function");
1352 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001353 }
1354
1355 Lex.Lex();
1356 }
1357}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001358
1359//===----------------------------------------------------------------------===//
1360// GlobalValue Reference/Resolution Routines.
1361//===----------------------------------------------------------------------===//
1362
Karl Schimpf77729782015-09-03 18:06:44 +00001363static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1364 const std::string &Name) {
1365 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001366 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1367 PTy->getAddressSpace(), Name, M);
Karl Schimpf77729782015-09-03 18:06:44 +00001368 else
1369 return new GlobalVariable(*M, PTy->getElementType(), false,
1370 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1371 nullptr, GlobalVariable::NotThreadLocal,
1372 PTy->getAddressSpace());
1373}
1374
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001375Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1376 Value *Val, bool IsCall) {
1377 if (Val->getType() == Ty)
1378 return Val;
1379 // For calls we also accept variables in the program address space.
1380 Type *SuggestedTy = Ty;
1381 if (IsCall && isa<PointerType>(Ty)) {
1382 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1383 M->getDataLayout().getProgramAddressSpace());
1384 SuggestedTy = TyInProgAS;
1385 if (Val->getType() == TyInProgAS)
1386 return Val;
1387 }
1388 if (Ty->isLabelTy())
1389 Error(Loc, "'" + Name + "' is not a basic block");
1390 else
1391 Error(Loc, "'" + Name + "' defined with type '" +
1392 getTypeString(Val->getType()) + "' but expected '" +
1393 getTypeString(SuggestedTy) + "'");
1394 return nullptr;
1395}
1396
Chris Lattnerac161bf2009-01-02 07:01:27 +00001397/// GetGlobalVal - Get a value with the specified name or ID, creating a
1398/// forward reference record if needed. This can return null if the value
1399/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001400GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001401 LocTy Loc, bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001402 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001403 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001405 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001406 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001407
Chris Lattnerac161bf2009-01-02 07:01:27 +00001408 // Look this name up in the normal function symbol table.
1409 GlobalValue *Val =
1410 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001411
Chris Lattnerac161bf2009-01-02 07:01:27 +00001412 // If this is a forward reference for the value, see if we already created a
1413 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001414 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001415 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001416 if (I != ForwardRefVals.end())
1417 Val = I->second.first;
1418 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001419
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001421 if (Val)
1422 return cast_or_null<GlobalValue>(
1423 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001424
Chris Lattnerac161bf2009-01-02 07:01:27 +00001425 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001426 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001427 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1428 return FwdVal;
1429}
1430
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001431GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1432 bool IsCall) {
Chris Lattner229907c2011-07-18 04:54:35 +00001433 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001434 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001435 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001436 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001438
Craig Topper2617dcc2014-04-15 06:32:26 +00001439 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001440
Chris Lattnerac161bf2009-01-02 07:01:27 +00001441 // If this is a forward reference for the value, see if we already created a
1442 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001443 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001444 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001445 if (I != ForwardRefValIDs.end())
1446 Val = I->second.first;
1447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001448
Chris Lattnerac161bf2009-01-02 07:01:27 +00001449 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001450 if (Val)
1451 return cast_or_null<GlobalValue>(
1452 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001453
Chris Lattnerac161bf2009-01-02 07:01:27 +00001454 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001455 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001456 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1457 return FwdVal;
1458}
1459
Chris Lattnerac161bf2009-01-02 07:01:27 +00001460//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001461// Comdat Reference/Resolution Routines.
1462//===----------------------------------------------------------------------===//
1463
1464Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1465 // Look this name up in the comdat symbol table.
1466 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1467 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1468 if (I != ComdatSymTab.end())
1469 return &I->second;
1470
1471 // Otherwise, create a new forward reference for this value and remember it.
1472 Comdat *C = M->getOrInsertComdat(Name);
1473 ForwardRefComdats[Name] = Loc;
1474 return C;
1475}
1476
David Majnemerdad0a642014-06-27 18:19:56 +00001477//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001478// Helper Routines.
1479//===----------------------------------------------------------------------===//
1480
1481/// ParseToken - If the current token has the specified kind, eat it and return
1482/// success. Otherwise, emit the specified error and return failure.
1483bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1484 if (Lex.getKind() != T)
1485 return TokError(ErrMsg);
1486 Lex.Lex();
1487 return false;
1488}
1489
Chris Lattner3822f632009-01-02 08:05:26 +00001490/// ParseStringConstant
1491/// ::= StringConstant
1492bool LLParser::ParseStringConstant(std::string &Result) {
1493 if (Lex.getKind() != lltok::StringConstant)
1494 return TokError("expected string constant");
1495 Result = Lex.getStrVal();
1496 Lex.Lex();
1497 return false;
1498}
1499
1500/// ParseUInt32
1501/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001502bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1504 return TokError("expected integer");
1505 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1506 if (Val64 != unsigned(Val64))
1507 return TokError("expected 32-bit integer (too large)");
1508 Val = Val64;
1509 Lex.Lex();
1510 return false;
1511}
1512
Hal Finkelb0407ba2014-07-18 15:51:28 +00001513/// ParseUInt64
1514/// ::= uint64
1515bool LLParser::ParseUInt64(uint64_t &Val) {
1516 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1517 return TokError("expected integer");
1518 Val = Lex.getAPSIntVal().getLimitedValue();
1519 Lex.Lex();
1520 return false;
1521}
1522
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001523/// ParseTLSModel
1524/// := 'localdynamic'
1525/// := 'initialexec'
1526/// := 'localexec'
1527bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1528 switch (Lex.getKind()) {
1529 default:
1530 return TokError("expected localdynamic, initialexec or localexec");
1531 case lltok::kw_localdynamic:
1532 TLM = GlobalVariable::LocalDynamicTLSModel;
1533 break;
1534 case lltok::kw_initialexec:
1535 TLM = GlobalVariable::InitialExecTLSModel;
1536 break;
1537 case lltok::kw_localexec:
1538 TLM = GlobalVariable::LocalExecTLSModel;
1539 break;
1540 }
1541
1542 Lex.Lex();
1543 return false;
1544}
1545
1546/// ParseOptionalThreadLocal
1547/// := /*empty*/
1548/// := 'thread_local'
1549/// := 'thread_local' '(' tlsmodel ')'
1550bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1551 TLM = GlobalVariable::NotThreadLocal;
1552 if (!EatIfPresent(lltok::kw_thread_local))
1553 return false;
1554
1555 TLM = GlobalVariable::GeneralDynamicTLSModel;
1556 if (Lex.getKind() == lltok::lparen) {
1557 Lex.Lex();
1558 return ParseTLSModel(TLM) ||
1559 ParseToken(lltok::rparen, "expected ')' after thread local model");
1560 }
1561 return false;
1562}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001563
1564/// ParseOptionalAddrSpace
1565/// := /*empty*/
1566/// := 'addrspace' '(' uint32 ')'
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001567bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1568 AddrSpace = DefaultAS;
Chris Lattner3822f632009-01-02 08:05:26 +00001569 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001571 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001572 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001574}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575
Artur Pilipenko17376c42015-08-03 14:31:49 +00001576/// ParseStringAttribute
1577/// := StringConstant
1578/// := StringConstant '=' StringConstant
1579bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1580 std::string Attr = Lex.getStrVal();
1581 Lex.Lex();
1582 std::string Val;
1583 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1584 return true;
1585 B.addAttribute(Attr, Val);
1586 return false;
1587}
1588
Bill Wendling34c2eb22012-12-04 23:40:58 +00001589/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1590bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1591 bool HaveError = false;
1592
1593 B.clear();
1594
Eugene Zelenko1804a772016-08-25 00:45:04 +00001595 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001596 lltok::Kind Token = Lex.getKind();
1597 switch (Token) {
1598 default: // End of attributes.
1599 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001600 case lltok::StringConstant: {
1601 if (ParseStringAttribute(B))
1602 return true;
1603 continue;
1604 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001605 case lltok::kw_align: {
1606 unsigned Alignment;
1607 if (ParseOptionalAlignment(Alignment))
1608 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001609 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001610 continue;
1611 }
Tim Northoverb7141202019-05-30 18:48:23 +00001612 case lltok::kw_byval: {
1613 Type *Ty;
1614 if (ParseByValWithOptionalType(Ty))
1615 return true;
1616 B.addByValAttr(Ty);
1617 continue;
1618 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001619 case lltok::kw_dereferenceable: {
1620 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001621 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001622 return true;
1623 B.addDereferenceableAttr(Bytes);
1624 continue;
1625 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001626 case lltok::kw_dereferenceable_or_null: {
1627 uint64_t Bytes;
1628 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1629 return true;
1630 B.addDereferenceableOrNullAttr(Bytes);
1631 continue;
1632 }
Reid Klecknera534a382013-12-19 02:14:12 +00001633 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001634 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1635 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1636 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1637 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001638 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001639 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1640 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001641 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001642 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1643 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001644 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001645 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001646 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001647 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Matt Arsenaultcaf13162019-03-12 21:02:54 +00001648 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001649
Stephen Lin7577ed52013-04-20 13:16:13 +00001650 case lltok::kw_alignstack:
1651 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001652 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001653 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001654 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001655 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001656 case lltok::kw_minsize:
1657 case lltok::kw_naked:
1658 case lltok::kw_nobuiltin:
1659 case lltok::kw_noduplicate:
1660 case lltok::kw_noimplicitfloat:
1661 case lltok::kw_noinline:
1662 case lltok::kw_nonlazybind:
1663 case lltok::kw_noredzone:
1664 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001665 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001666 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001667 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001668 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001669 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001670 case lltok::kw_returns_twice:
1671 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001672 case lltok::kw_sanitize_hwaddress:
Evgeniy Stepanovc5e7f562019-07-15 20:02:23 +00001673 case lltok::kw_sanitize_memtag:
Stephen Lin7577ed52013-04-20 13:16:13 +00001674 case lltok::kw_sanitize_memory:
1675 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001676 case lltok::kw_speculative_load_hardening:
Stephen Lin7577ed52013-04-20 13:16:13 +00001677 case lltok::kw_ssp:
1678 case lltok::kw_sspreq:
1679 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001680 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001681 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001682 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001683 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001684 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1685 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001687
Bill Wendling34c2eb22012-12-04 23:40:58 +00001688 Lex.Lex();
1689 }
1690}
1691
1692/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1693bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1694 bool HaveError = false;
1695
1696 B.clear();
1697
Eugene Zelenko1804a772016-08-25 00:45:04 +00001698 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001699 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001700 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001701 default: // End of attributes.
1702 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001703 case lltok::StringConstant: {
1704 if (ParseStringAttribute(B))
1705 return true;
1706 continue;
1707 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001708 case lltok::kw_dereferenceable: {
1709 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001710 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001711 return true;
1712 B.addDereferenceableAttr(Bytes);
1713 continue;
1714 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001715 case lltok::kw_dereferenceable_or_null: {
1716 uint64_t Bytes;
1717 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1718 return true;
1719 B.addDereferenceableOrNullAttr(Bytes);
1720 continue;
1721 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001722 case lltok::kw_align: {
1723 unsigned Alignment;
1724 if (ParseOptionalAlignment(Alignment))
1725 return true;
1726 B.addAlignmentAttr(Alignment);
1727 continue;
1728 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001729 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1730 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001731 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001732 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1733 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001734
Bill Wendling34c2eb22012-12-04 23:40:58 +00001735 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001736 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001737 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001738 case lltok::kw_nest:
1739 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001740 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001741 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001742 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001743 case lltok::kw_swiftself:
Matt Arsenaultcaf13162019-03-12 21:02:54 +00001744 case lltok::kw_immarg:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001745 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001746 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001747
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001748 case lltok::kw_alignstack:
1749 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001750 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001751 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001752 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001753 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001754 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001755 case lltok::kw_minsize:
1756 case lltok::kw_naked:
1757 case lltok::kw_nobuiltin:
1758 case lltok::kw_noduplicate:
1759 case lltok::kw_noimplicitfloat:
1760 case lltok::kw_noinline:
1761 case lltok::kw_nonlazybind:
1762 case lltok::kw_noredzone:
1763 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001764 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001765 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001766 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001767 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001768 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001769 case lltok::kw_returns_twice:
1770 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001771 case lltok::kw_sanitize_hwaddress:
Evgeniy Stepanovc5e7f562019-07-15 20:02:23 +00001772 case lltok::kw_sanitize_memtag:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001773 case lltok::kw_sanitize_memory:
1774 case lltok::kw_sanitize_thread:
Chandler Carruth664aa862018-09-04 12:38:00 +00001775 case lltok::kw_speculative_load_hardening:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001776 case lltok::kw_ssp:
1777 case lltok::kw_sspreq:
1778 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001779 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001780 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001781 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001782 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001783 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001784 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001785
1786 case lltok::kw_readnone:
1787 case lltok::kw_readonly:
1788 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001789 }
1790
Chris Lattnerac161bf2009-01-02 07:01:27 +00001791 Lex.Lex();
1792 }
1793}
1794
Rafael Espindolac6269912016-05-10 17:16:45 +00001795static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1796 HasLinkage = true;
1797 switch (Kind) {
1798 default:
1799 HasLinkage = false;
1800 return GlobalValue::ExternalLinkage;
1801 case lltok::kw_private:
1802 return GlobalValue::PrivateLinkage;
1803 case lltok::kw_internal:
1804 return GlobalValue::InternalLinkage;
1805 case lltok::kw_weak:
1806 return GlobalValue::WeakAnyLinkage;
1807 case lltok::kw_weak_odr:
1808 return GlobalValue::WeakODRLinkage;
1809 case lltok::kw_linkonce:
1810 return GlobalValue::LinkOnceAnyLinkage;
1811 case lltok::kw_linkonce_odr:
1812 return GlobalValue::LinkOnceODRLinkage;
1813 case lltok::kw_available_externally:
1814 return GlobalValue::AvailableExternallyLinkage;
1815 case lltok::kw_appending:
1816 return GlobalValue::AppendingLinkage;
1817 case lltok::kw_common:
1818 return GlobalValue::CommonLinkage;
1819 case lltok::kw_extern_weak:
1820 return GlobalValue::ExternalWeakLinkage;
1821 case lltok::kw_external:
1822 return GlobalValue::ExternalLinkage;
1823 }
1824}
1825
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826/// ParseOptionalLinkage
1827/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001828/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001829/// ::= 'internal'
1830/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001831/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001832/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001833/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001834/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001835/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001836/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001837/// ::= 'extern_weak'
1838/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001839bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1840 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001841 unsigned &DLLStorageClass,
1842 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001843 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1844 if (HasLinkage)
1845 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001846 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001847 ParseOptionalVisibility(Visibility);
1848 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001849
1850 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1851 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1852 }
1853
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 return false;
1855}
1856
Sean Fertilec70d28b2017-10-26 15:00:26 +00001857void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1858 switch (Lex.getKind()) {
1859 default:
1860 DSOLocal = false;
1861 break;
1862 case lltok::kw_dso_local:
1863 DSOLocal = true;
1864 Lex.Lex();
1865 break;
1866 case lltok::kw_dso_preemptable:
1867 DSOLocal = false;
1868 Lex.Lex();
1869 break;
1870 }
1871}
1872
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873/// ParseOptionalVisibility
1874/// ::= /*empty*/
1875/// ::= 'default'
1876/// ::= 'hidden'
1877/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001878///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001879void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001880 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001881 default:
1882 Res = GlobalValue::DefaultVisibility;
1883 return;
1884 case lltok::kw_default:
1885 Res = GlobalValue::DefaultVisibility;
1886 break;
1887 case lltok::kw_hidden:
1888 Res = GlobalValue::HiddenVisibility;
1889 break;
1890 case lltok::kw_protected:
1891 Res = GlobalValue::ProtectedVisibility;
1892 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 }
1894 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001895}
1896
Nico Rieck7157bb72014-01-14 15:22:47 +00001897/// ParseOptionalDLLStorageClass
1898/// ::= /*empty*/
1899/// ::= 'dllimport'
1900/// ::= 'dllexport'
1901///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001902void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001903 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001904 default:
1905 Res = GlobalValue::DefaultStorageClass;
1906 return;
1907 case lltok::kw_dllimport:
1908 Res = GlobalValue::DLLImportStorageClass;
1909 break;
1910 case lltok::kw_dllexport:
1911 Res = GlobalValue::DLLExportStorageClass;
1912 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001913 }
1914 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001915}
1916
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917/// ParseOptionalCallingConv
1918/// ::= /*empty*/
1919/// ::= 'ccc'
1920/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001921/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922/// ::= 'coldcc'
1923/// ::= 'x86_stdcallcc'
1924/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001925/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001926/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001927/// ::= 'arm_apcscc'
1928/// ::= 'arm_aapcscc'
1929/// ::= 'arm_aapcs_vfpcc'
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001930/// ::= 'aarch64_vector_pcs'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001931/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001932/// ::= 'avr_intrcc'
1933/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001934/// ::= 'ptx_kernel'
1935/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001936/// ::= 'spir_func'
1937/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001938/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001939/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001940/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001941/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001942/// ::= 'preserve_mostcc'
1943/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001944/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001945/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001946/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001947/// ::= 'hhvmcc'
1948/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001949/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001950/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001951/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001952/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001953/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001954/// ::= 'amdgpu_gs'
1955/// ::= 'amdgpu_ps'
1956/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001957/// ::= 'amdgpu_kernel'
Reid Klecknerf9b67b82019-10-07 22:28:58 +00001958/// ::= 'tailcc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001960///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001961bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001962 switch (Lex.getKind()) {
1963 default: CC = CallingConv::C; return false;
1964 case lltok::kw_ccc: CC = CallingConv::C; break;
1965 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1966 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1967 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1968 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001969 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001970 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001971 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001972 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1973 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1974 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00001975 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001976 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001977 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1978 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001979 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1980 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001981 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1982 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001983 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001984 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001985 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001986 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001987 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001988 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1989 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001990 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001991 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001992 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001993 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1994 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001995 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001996 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001997 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001998 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001999 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00002000 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2001 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2002 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00002003 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Reid Klecknerf9b67b82019-10-07 22:28:58 +00002004 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00002005 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00002006 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00002007 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00002008 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002009 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002010
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 Lex.Lex();
2012 return false;
2013}
2014
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00002015/// ParseMetadataAttachment
2016/// ::= !dbg !42
2017bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2018 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2019
2020 std::string Name = Lex.getStrVal();
2021 Kind = M->getMDKindID(Name);
2022 Lex.Lex();
2023
2024 return ParseMDNode(MD);
2025}
2026
Chris Lattner5c427632009-12-30 05:31:19 +00002027/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00002028/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00002029bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00002030 do {
2031 if (Lex.getKind() != lltok::MetadataVar)
2032 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00002033
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00002034 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00002035 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00002036 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00002037 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002038
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00002039 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00002040 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00002041 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00002042
Chris Lattner596760d2009-12-29 21:25:40 +00002043 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00002044 } while (EatIfPresent(lltok::comma));
2045 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00002046}
2047
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002048/// ParseGlobalObjectMetadataAttachment
2049/// ::= !dbg !57
2050bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2051 unsigned MDK;
2052 MDNode *N;
2053 if (ParseMetadataAttachment(MDK, N))
2054 return true;
2055
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002056 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002057 return false;
2058}
2059
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002060/// ParseOptionalFunctionMetadata
2061/// ::= (!dbg !57)*
2062bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002063 while (Lex.getKind() == lltok::MetadataVar)
2064 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002065 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002066 return false;
2067}
2068
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069/// ParseOptionalAlignment
2070/// ::= /* empty */
2071/// ::= 'align' 4
2072bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2073 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002074 if (!EatIfPresent(lltok::kw_align))
2075 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00002076 LocTy AlignLoc = Lex.getLoc();
2077 if (ParseUInt32(Alignment)) return true;
2078 if (!isPowerOf2_32(Alignment))
2079 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00002080 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00002081 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00002082 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083}
2084
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002085/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00002086/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002087/// ::= AttrKind '(' 4 ')'
2088///
2089/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2090bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2091 uint64_t &Bytes) {
2092 assert((AttrKind == lltok::kw_dereferenceable ||
2093 AttrKind == lltok::kw_dereferenceable_or_null) &&
2094 "contract!");
2095
Hal Finkelb0407ba2014-07-18 15:51:28 +00002096 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00002097 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00002098 return false;
2099 LocTy ParenLoc = Lex.getLoc();
2100 if (!EatIfPresent(lltok::lparen))
2101 return Error(ParenLoc, "expected '('");
2102 LocTy DerefLoc = Lex.getLoc();
2103 if (ParseUInt64(Bytes)) return true;
2104 ParenLoc = Lex.getLoc();
2105 if (!EatIfPresent(lltok::rparen))
2106 return Error(ParenLoc, "expected ')'");
2107 if (!Bytes)
2108 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2109 return false;
2110}
2111
Chris Lattnerb2f39502009-12-30 05:44:30 +00002112/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002113/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00002114/// ::= ',' align 4
2115///
2116/// This returns with AteExtraComma set to true if it ate an excess comma at the
2117/// end.
2118bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2119 bool &AteExtraComma) {
2120 AteExtraComma = false;
2121 while (EatIfPresent(lltok::comma)) {
2122 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00002123 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00002124 AteExtraComma = true;
2125 return false;
2126 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002127
Chris Lattner95b0ff42010-04-23 00:50:50 +00002128 if (Lex.getKind() != lltok::kw_align)
2129 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00002130
Chris Lattner95b0ff42010-04-23 00:50:50 +00002131 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00002132 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002133
Devang Patelea8a4b92009-09-17 23:04:48 +00002134 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135}
2136
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002137/// ParseOptionalCommaAddrSpace
2138/// ::=
2139/// ::= ',' addrspace(1)
2140///
2141/// This returns with AteExtraComma set to true if it ate an excess comma at the
2142/// end.
2143bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2144 LocTy &Loc,
2145 bool &AteExtraComma) {
2146 AteExtraComma = false;
2147 while (EatIfPresent(lltok::comma)) {
2148 // Metadata at the end is an early exit.
2149 if (Lex.getKind() == lltok::MetadataVar) {
2150 AteExtraComma = true;
2151 return false;
2152 }
2153
2154 Loc = Lex.getLoc();
2155 if (Lex.getKind() != lltok::kw_addrspace)
2156 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2157
2158 if (ParseOptionalAddrSpace(AddrSpace))
2159 return true;
2160 }
2161
2162 return false;
2163}
2164
George Burgess IV278199f2016-04-12 01:05:35 +00002165bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2166 Optional<unsigned> &HowManyArg) {
2167 Lex.Lex();
2168
2169 auto StartParen = Lex.getLoc();
2170 if (!EatIfPresent(lltok::lparen))
2171 return Error(StartParen, "expected '('");
2172
2173 if (ParseUInt32(BaseSizeArg))
2174 return true;
2175
2176 if (EatIfPresent(lltok::comma)) {
2177 auto HowManyAt = Lex.getLoc();
2178 unsigned HowMany;
2179 if (ParseUInt32(HowMany))
2180 return true;
2181 if (HowMany == BaseSizeArg)
2182 return Error(HowManyAt,
2183 "'allocsize' indices can't refer to the same parameter");
2184 HowManyArg = HowMany;
2185 } else
2186 HowManyArg = None;
2187
2188 auto EndParen = Lex.getLoc();
2189 if (!EatIfPresent(lltok::rparen))
2190 return Error(EndParen, "expected ')'");
2191 return false;
2192}
2193
Eli Friedmanfee02c62011-07-25 23:16:38 +00002194/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002195/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002196/// else: ::=
2197///
2198/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002199bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002200 AtomicOrdering &Ordering) {
2201 if (!isAtomic)
2202 return false;
2203
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002204 return ParseScope(SSID) || ParseOrdering(Ordering);
2205}
Tim Northovere94a5182014-03-11 10:48:52 +00002206
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002207/// ParseScope
2208/// ::= syncscope("singlethread" | "<target scope>")?
2209///
2210/// This sets synchronization scope ID to the ID of the parsed value.
2211bool LLParser::ParseScope(SyncScope::ID &SSID) {
2212 SSID = SyncScope::System;
2213 if (EatIfPresent(lltok::kw_syncscope)) {
2214 auto StartParenAt = Lex.getLoc();
2215 if (!EatIfPresent(lltok::lparen))
2216 return Error(StartParenAt, "Expected '(' in syncscope");
2217
2218 std::string SSN;
2219 auto SSNAt = Lex.getLoc();
2220 if (ParseStringConstant(SSN))
2221 return Error(SSNAt, "Expected synchronization scope name");
2222
2223 auto EndParenAt = Lex.getLoc();
2224 if (!EatIfPresent(lltok::rparen))
2225 return Error(EndParenAt, "Expected ')' in syncscope");
2226
2227 SSID = Context.getOrInsertSyncScopeID(SSN);
2228 }
2229
2230 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002231}
2232
2233/// ParseOrdering
2234/// ::= AtomicOrdering
2235///
2236/// This sets Ordering to the parsed value.
2237bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002238 switch (Lex.getKind()) {
2239 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002240 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2241 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2242 // Not specified yet:
2243 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2244 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2245 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2246 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2247 case lltok::kw_seq_cst:
2248 Ordering = AtomicOrdering::SequentiallyConsistent;
2249 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002250 }
2251 Lex.Lex();
2252 return false;
2253}
2254
Charles Davisbe5557e2010-02-12 00:31:15 +00002255/// ParseOptionalStackAlignment
2256/// ::= /* empty */
2257/// ::= 'alignstack' '(' 4 ')'
2258bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2259 Alignment = 0;
2260 if (!EatIfPresent(lltok::kw_alignstack))
2261 return false;
2262 LocTy ParenLoc = Lex.getLoc();
2263 if (!EatIfPresent(lltok::lparen))
2264 return Error(ParenLoc, "expected '('");
2265 LocTy AlignLoc = Lex.getLoc();
2266 if (ParseUInt32(Alignment)) return true;
2267 ParenLoc = Lex.getLoc();
2268 if (!EatIfPresent(lltok::rparen))
2269 return Error(ParenLoc, "expected ')'");
2270 if (!isPowerOf2_32(Alignment))
2271 return Error(AlignLoc, "stack alignment is not a power of two");
2272 return false;
2273}
Devang Patelea8a4b92009-09-17 23:04:48 +00002274
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002275/// ParseIndexList - This parses the index list for an insert/extractvalue
2276/// instruction. This sets AteExtraComma in the case where we eat an extra
2277/// comma at the end of the line and find that it is followed by metadata.
2278/// Clients that don't allow metadata can call the version of this function that
2279/// only takes one argument.
2280///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281/// ParseIndexList
2282/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002283///
2284bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2285 bool &AteExtraComma) {
2286 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002287
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 if (Lex.getKind() != lltok::comma)
2289 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Chris Lattner3822f632009-01-02 08:05:26 +00002291 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002292 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002293 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002294 AteExtraComma = true;
2295 return false;
2296 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002297 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002298 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299 Indices.push_back(Idx);
2300 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002301
Chris Lattnerac161bf2009-01-02 07:01:27 +00002302 return false;
2303}
2304
2305//===----------------------------------------------------------------------===//
2306// Type Parsing.
2307//===----------------------------------------------------------------------===//
2308
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002309/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002310bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002311 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 switch (Lex.getKind()) {
2313 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002314 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002316 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002318 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 // Type ::= StructType
2322 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002323 return true;
2324 break;
2325 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002327 Lex.Lex(); // eat the lsquare.
2328 if (ParseArrayVectorType(Result, false))
2329 return true;
2330 break;
2331 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002332 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002333 Lex.Lex();
2334 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002336 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 } else if (ParseArrayVectorType(Result, true))
2339 return true;
2340 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002341 case lltok::LocalVar: {
2342 // Type ::= %foo
2343 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002344
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002345 // If the type hasn't been defined yet, create a forward definition and
2346 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002347 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002348 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002352 Lex.Lex();
2353 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002354 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002355
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002356 case lltok::LocalVarID: {
2357 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002359
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002360 // If the type hasn't been defined yet, create a forward definition and
2361 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002362 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002363 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002364 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002365 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002366 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 Lex.Lex();
2368 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002369 }
2370 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002371
2372 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002373 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 switch (Lex.getKind()) {
2375 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002376 default:
2377 if (!AllowVoid && Result->isVoidTy())
2378 return Error(TypeLoc, "void type only allowed for function results");
2379 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002381 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 if (Result->isVoidTy())
2386 return TokError("pointers to void are invalid - use i8* instead");
2387 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002388 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002389 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390 Lex.Lex();
2391 break;
2392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002395 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002396 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002397 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002398 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002399 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002400 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002401 unsigned AddrSpace;
2402 if (ParseOptionalAddrSpace(AddrSpace) ||
2403 ParseToken(lltok::star, "expected '*' in address space"))
2404 return true;
2405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 break;
2408 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002409
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2411 case lltok::lparen:
2412 if (ParseFunctionType(Result))
2413 return true;
2414 break;
2415 }
2416 }
2417}
2418
2419/// ParseParameterList
2420/// ::= '(' ')'
2421/// ::= '(' Arg (',' Arg)* ')'
2422/// Arg
2423/// ::= Type OptionalAttributes Value OptionalAttributes
2424bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002425 PerFunctionState &PFS, bool IsMustTailCall,
2426 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002427 if (ParseToken(lltok::lparen, "expected '(' in call"))
2428 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002429
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 while (Lex.getKind() != lltok::rparen) {
2431 // If this isn't the first argument, we need a comma.
2432 if (!ArgList.empty() &&
2433 ParseToken(lltok::comma, "expected ',' in argument list"))
2434 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Reid Kleckner83498642014-08-26 00:33:28 +00002436 // Parse an ellipsis if this is a musttail call in a variadic function.
2437 if (Lex.getKind() == lltok::dotdotdot) {
2438 const char *Msg = "unexpected ellipsis in argument list for ";
2439 if (!IsMustTailCall)
2440 return TokError(Twine(Msg) + "non-musttail call");
2441 if (!InVarArgsFunc)
2442 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2443 Lex.Lex(); // Lex the '...', it is purely for readability.
2444 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2445 }
2446
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 // Parse the argument.
2448 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002449 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002450 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002451 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002452 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002454
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002455 if (ArgTy->isMetadataTy()) {
2456 if (ParseMetadataAsValue(V, PFS))
2457 return true;
2458 } else {
2459 // Otherwise, handle normal operands.
2460 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2461 return true;
2462 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002463 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002464 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 }
2466
Reid Kleckner83498642014-08-26 00:33:28 +00002467 if (IsMustTailCall && InVarArgsFunc)
2468 return TokError("expected '...' at end of argument list for musttail call "
2469 "in varargs function");
2470
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471 Lex.Lex(); // Lex the ')'.
2472 return false;
2473}
2474
Tim Northoverb7141202019-05-30 18:48:23 +00002475/// ParseByValWithOptionalType
2476/// ::= byval
2477/// ::= byval(<ty>)
2478bool LLParser::ParseByValWithOptionalType(Type *&Result) {
2479 Result = nullptr;
2480 if (!EatIfPresent(lltok::kw_byval))
2481 return true;
2482 if (!EatIfPresent(lltok::lparen))
2483 return false;
2484 if (ParseType(Result))
2485 return true;
2486 if (!EatIfPresent(lltok::rparen))
2487 return Error(Lex.getLoc(), "expected ')'");
2488 return false;
2489}
2490
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002491/// ParseOptionalOperandBundles
2492/// ::= /*empty*/
2493/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2494///
2495/// OperandBundle
2496/// ::= bundle-tag '(' ')'
2497/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2498///
2499/// bundle-tag ::= String Constant
2500bool LLParser::ParseOptionalOperandBundles(
2501 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2502 LocTy BeginLoc = Lex.getLoc();
2503 if (!EatIfPresent(lltok::lsquare))
2504 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002506 while (Lex.getKind() != lltok::rsquare) {
2507 // If this isn't the first operand bundle, we need a comma.
2508 if (!BundleList.empty() &&
2509 ParseToken(lltok::comma, "expected ',' in input list"))
2510 return true;
2511
2512 std::string Tag;
2513 if (ParseStringConstant(Tag))
2514 return true;
2515
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002516 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2517 return true;
2518
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002519 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002520 while (Lex.getKind() != lltok::rparen) {
2521 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002522 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002523 ParseToken(lltok::comma, "expected ',' in input list"))
2524 return true;
2525
2526 Type *Ty = nullptr;
2527 Value *Input = nullptr;
2528 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2529 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002530 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002531 }
2532
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002533 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2534
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002535 Lex.Lex(); // Lex the ')'.
2536 }
2537
2538 if (BundleList.empty())
2539 return Error(BeginLoc, "operand bundle set must not be empty");
2540
2541 Lex.Lex(); // Lex the ']'.
2542 return false;
2543}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544
Chris Lattner2ed06b42009-01-05 18:34:07 +00002545/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002546/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002547/// ::= '(' ArgTypeListI ')'
2548/// ArgTypeListI
2549/// ::= /*empty*/
2550/// ::= '...'
2551/// ::= ArgTypeList ',' '...'
2552/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002553///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002554bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2555 bool &isVarArg){
Tim Northovera009a602019-08-03 14:28:34 +00002556 unsigned CurValID = 0;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 isVarArg = false;
2558 assert(Lex.getKind() == lltok::lparen);
2559 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002560
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 if (Lex.getKind() == lltok::rparen) {
2562 // empty
2563 } else if (Lex.getKind() == lltok::dotdotdot) {
2564 isVarArg = true;
2565 Lex.Lex();
2566 } else {
2567 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002568 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002569 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002571
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002572 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002573 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002574
Chris Lattnerfdd87902009-10-05 05:54:46 +00002575 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002576 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002577
Chris Lattnerdef19492011-06-17 06:36:20 +00002578 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 Name = Lex.getStrVal();
2580 Lex.Lex();
Tim Northovera009a602019-08-03 14:28:34 +00002581 } else if (Lex.getKind() == lltok::LocalVarID) {
2582 if (Lex.getUIntVal() != CurValID)
2583 return Error(TypeLoc, "argument expected to be numbered '%" +
2584 Twine(CurValID) + "'");
2585 ++CurValID;
2586 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 }
Chris Lattner3822f632009-01-02 08:05:26 +00002588
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002589 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002590 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002591
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002592 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002593 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002594 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Chris Lattner3822f632009-01-02 08:05:26 +00002596 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002597 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002598 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 break;
2601 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002602
Chris Lattnerac161bf2009-01-02 07:01:27 +00002603 // Otherwise must be an argument type.
2604 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002605 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002606
Chris Lattnerfdd87902009-10-05 05:54:46 +00002607 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002608 return Error(TypeLoc, "argument can not have void type");
2609
Chris Lattnerdef19492011-06-17 06:36:20 +00002610 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002611 Name = Lex.getStrVal();
2612 Lex.Lex();
2613 } else {
Tim Northovera009a602019-08-03 14:28:34 +00002614 if (Lex.getKind() == lltok::LocalVarID) {
2615 if (Lex.getUIntVal() != CurValID)
2616 return Error(TypeLoc, "argument expected to be numbered '%" +
2617 Twine(CurValID) + "'");
2618 Lex.Lex();
2619 }
2620 ++CurValID;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 Name = "";
2622 }
Chris Lattner3822f632009-01-02 08:05:26 +00002623
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002624 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002625 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002627 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002628 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002629 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 }
2631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattner3822f632009-01-02 08:05:26 +00002633 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002635
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636/// ParseFunctionType
2637/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002638bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 assert(Lex.getKind() == lltok::lparen);
2640
Chris Lattnerce473c72009-01-05 08:04:33 +00002641 if (!FunctionType::isValidReturnType(Result))
2642 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002644 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002646 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002648
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 // Reject names on the arguments lists.
2650 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2651 if (!ArgList[i].Name.empty())
2652 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002653 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002654 return Error(ArgList[i].Loc,
2655 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657
Jay Foadb804a2b2011-07-12 14:06:48 +00002658 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002660 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002662 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 return false;
2664}
2665
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002666/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2667/// other structs.
2668bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2669 SmallVector<Type*, 8> Elts;
2670 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002671
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002672 Result = StructType::get(Context, Elts, Packed);
2673 return false;
2674}
2675
2676/// ParseStructDefinition - Parse a struct in a 'type' definition.
2677bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2678 std::pair<Type*, LocTy> &Entry,
2679 Type *&ResultTy) {
2680 // If the type was already defined, diagnose the redefinition.
2681 if (Entry.first && !Entry.second.isValid())
2682 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002683
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002684 // If we have opaque, just return without filling in the definition for the
2685 // struct. This counts as a definition as far as the .ll file goes.
2686 if (EatIfPresent(lltok::kw_opaque)) {
2687 // This type is being defined, so clear the location to indicate this.
2688 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002689
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002690 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002691 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002692 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002693 ResultTy = Entry.first;
2694 return false;
2695 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002696
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002697 // If the type starts with '<', then it is either a packed struct or a vector.
2698 bool isPacked = EatIfPresent(lltok::less);
2699
2700 // If we don't have a struct, then we have a random type alias, which we
2701 // accept for compatibility with old files. These types are not allowed to be
2702 // forward referenced and not allowed to be recursive.
2703 if (Lex.getKind() != lltok::lbrace) {
2704 if (Entry.first)
2705 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002706
Craig Topper2617dcc2014-04-15 06:32:26 +00002707 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002708 if (isPacked)
2709 return ParseArrayVectorType(ResultTy, true);
2710 return ParseType(ResultTy);
2711 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002712
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002713 // This type is being defined, so clear the location to indicate this.
2714 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002715
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002716 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002717 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002718 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002719
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002720 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002721
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002722 SmallVector<Type*, 8> Body;
2723 if (ParseStructBody(Body) ||
2724 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2725 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002726
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002727 STy->setBody(Body, isPacked);
2728 ResultTy = STy;
2729 return false;
2730}
2731
Chris Lattnerac161bf2009-01-02 07:01:27 +00002732/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002733/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002735/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002736/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002737/// ::= '<' '{' Type (',' Type)* '}' '>'
2738bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 assert(Lex.getKind() == lltok::lbrace);
2740 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002742 // Handle the empty struct.
2743 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002745
Chris Lattnerf880ca22009-03-09 04:49:14 +00002746 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002747 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002748 if (ParseType(Ty)) return true;
2749 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002751 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002752 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753
Chris Lattner3822f632009-01-02 08:05:26 +00002754 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002755 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002756 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002757
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002758 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002759 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002760
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002761 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002762 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002763
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002764 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002765}
2766
2767/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2768/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002769/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002770/// ::= '[' APSINTVAL 'x' Types ']'
2771/// ::= '<' APSINTVAL 'x' Types '>'
Graham Hunter957c40d2019-07-05 12:48:16 +00002772/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002773bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Graham Hunter957c40d2019-07-05 12:48:16 +00002774 bool Scalable = false;
2775
2776 if (isVector && Lex.getKind() == lltok::kw_vscale) {
2777 Lex.Lex(); // consume the 'vscale'
2778 if (ParseToken(lltok::kw_x, "expected 'x' after vscale"))
2779 return true;
2780
2781 Scalable = true;
2782 }
2783
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2785 Lex.getAPSIntVal().getBitWidth() > 64)
2786 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 LocTy SizeLoc = Lex.getLoc();
2789 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002790 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002791
Chris Lattner3822f632009-01-02 08:05:26 +00002792 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2793 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002794
2795 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002796 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002797 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002798
Chris Lattner3822f632009-01-02 08:05:26 +00002799 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2800 "expected end of sequential type"))
2801 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002802
Chris Lattnerac161bf2009-01-02 07:01:27 +00002803 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002804 if (Size == 0)
2805 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 if ((unsigned)Size != Size)
2807 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002808 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002809 return Error(TypeLoc, "invalid vector element type");
Graham Hunter957c40d2019-07-05 12:48:16 +00002810 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002812 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002814 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 }
2816 return false;
2817}
2818
2819//===----------------------------------------------------------------------===//
2820// Function Semantic Analysis.
2821//===----------------------------------------------------------------------===//
2822
Chris Lattner3432c622009-10-28 03:39:23 +00002823LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2824 int functionNumber)
2825 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826
2827 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002828 for (Argument &A : F.args())
2829 if (!A.hasName())
2830 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831}
2832
2833LLParser::PerFunctionState::~PerFunctionState() {
2834 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002835
David Blaikie9ebdc692015-09-21 21:07:50 +00002836 for (const auto &P : ForwardRefVals) {
2837 if (isa<BasicBlock>(P.second.first))
2838 continue;
2839 P.second.first->replaceAllUsesWith(
2840 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002841 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002842 }
2843
2844 for (const auto &P : ForwardRefValIDs) {
2845 if (isa<BasicBlock>(P.second.first))
2846 continue;
2847 P.second.first->replaceAllUsesWith(
2848 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002849 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002850 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851}
2852
Chris Lattner3432c622009-10-28 03:39:23 +00002853bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002854 if (!ForwardRefVals.empty())
2855 return P.Error(ForwardRefVals.begin()->second.second,
2856 "use of undefined value '%" + ForwardRefVals.begin()->first +
2857 "'");
2858 if (!ForwardRefValIDs.empty())
2859 return P.Error(ForwardRefValIDs.begin()->second.second,
2860 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002861 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002862 return false;
2863}
2864
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865/// GetVal - Get a value with the specified name or ID, creating a
2866/// forward reference record if needed. This can return null if the value
2867/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002868Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002869 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002871 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002872
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 // If this is a forward reference for the value, see if we already created a
2874 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002875 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002876 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002877 if (I != ForwardRefVals.end())
2878 Val = I->second.first;
2879 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002880
Chris Lattnerac161bf2009-01-02 07:01:27 +00002881 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002882 if (Val)
2883 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002884
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002886 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002888 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002890
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 // Otherwise, create a new forward reference for this value and remember it.
2892 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002893 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002894 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002895 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002896 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002897 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002898
Chris Lattnerac161bf2009-01-02 07:01:27 +00002899 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2900 return FwdVal;
2901}
2902
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002903Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2904 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002905 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002906 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002907
Chris Lattnerac161bf2009-01-02 07:01:27 +00002908 // If this is a forward reference for the value, see if we already created a
2909 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002910 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002911 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002912 if (I != ForwardRefValIDs.end())
2913 Val = I->second.first;
2914 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002915
Chris Lattnerac161bf2009-01-02 07:01:27 +00002916 // If we have the value in the symbol table or fwd-ref table, return it.
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002917 if (Val)
2918 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002919
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002920 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002921 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002922 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002924
Chris Lattnerac161bf2009-01-02 07:01:27 +00002925 // Otherwise, create a new forward reference for this value and remember it.
2926 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002927 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002928 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002929 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002930 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002932
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2934 return FwdVal;
2935}
2936
2937/// SetInstName - After an instruction is parsed and inserted into its
2938/// basic block, this installs its name.
2939bool LLParser::PerFunctionState::SetInstName(int NameID,
2940 const std::string &NameStr,
2941 LocTy NameLoc, Instruction *Inst) {
2942 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002943 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 if (NameID != -1 || !NameStr.empty())
2945 return P.Error(NameLoc, "instructions returning void cannot have a name");
2946 return false;
2947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002948
Chris Lattnerac161bf2009-01-02 07:01:27 +00002949 // If this was a numbered instruction, verify that the instruction is the
2950 // expected value and resolve any forward references.
2951 if (NameStr.empty()) {
2952 // If neither a name nor an ID was specified, just use the next ID.
2953 if (NameID == -1)
2954 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002955
Chris Lattnerac161bf2009-01-02 07:01:27 +00002956 if (unsigned(NameID) != NumberedVals.size())
2957 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002958 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959
David Blaikie9ebdc692015-09-21 21:07:50 +00002960 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002961 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002962 Value *Sentinel = FI->second.first;
2963 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002964 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002965 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002966
2967 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002968 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 ForwardRefValIDs.erase(FI);
2970 }
2971
2972 NumberedVals.push_back(Inst);
2973 return false;
2974 }
2975
2976 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002977 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002979 Value *Sentinel = FI->second.first;
2980 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002981 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002982 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002983
2984 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002985 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 ForwardRefVals.erase(FI);
2987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002988
Chris Lattnerac161bf2009-01-02 07:01:27 +00002989 // Set the name on the instruction.
2990 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002991
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002992 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002993 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 NameStr + "'");
2995 return false;
2996}
2997
2998/// GetBB - Get a basic block with the specified name or ID, creating a
2999/// forward reference record if needed.
3000BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
3001 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003002 return dyn_cast_or_null<BasicBlock>(
3003 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004}
3005
3006BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003007 return dyn_cast_or_null<BasicBlock>(
3008 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003009}
3010
3011/// DefineBB - Define the specified basic block, which is either named or
3012/// unnamed. If there is an error, this returns null otherwise it returns
3013/// the block being defined.
3014BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
James Y Knightc0e6b8a2019-03-22 18:27:13 +00003015 int NameID, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003016 BasicBlock *BB;
James Y Knightc0e6b8a2019-03-22 18:27:13 +00003017 if (Name.empty()) {
3018 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3019 P.Error(Loc, "label expected to be numbered '" +
3020 Twine(NumberedVals.size()) + "'");
3021 return nullptr;
3022 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 BB = GetBB(NumberedVals.size(), Loc);
James Y Knightc0e6b8a2019-03-22 18:27:13 +00003024 if (!BB) {
3025 P.Error(Loc, "unable to create block numbered '" +
3026 Twine(NumberedVals.size()) + "'");
3027 return nullptr;
3028 }
3029 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 BB = GetBB(Name, Loc);
James Y Knightc0e6b8a2019-03-22 18:27:13 +00003031 if (!BB) {
3032 P.Error(Loc, "unable to create block named '" + Name + "'");
3033 return nullptr;
3034 }
3035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003036
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 // Move the block to the end of the function. Forward ref'd blocks are
3038 // inserted wherever they happen to be referenced.
3039 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003040
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 // Remove the block from forward ref sets.
3042 if (Name.empty()) {
3043 ForwardRefValIDs.erase(NumberedVals.size());
3044 NumberedVals.push_back(BB);
3045 } else {
3046 // BB forward references are already in the function symbol table.
3047 ForwardRefVals.erase(Name);
3048 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003049
Chris Lattnerac161bf2009-01-02 07:01:27 +00003050 return BB;
3051}
3052
3053//===----------------------------------------------------------------------===//
3054// Constants.
3055//===----------------------------------------------------------------------===//
3056
3057/// ParseValID - Parse an abstract value that doesn't necessarily have a
3058/// type implied. For example, if we parse "4" we don't know what integer type
3059/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00003060/// sanity. PFS is used to convert function-local operands of metadata (since
3061/// metadata operands are not just parsed here but also converted to values).
3062/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00003063bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064 ID.Loc = Lex.getLoc();
3065 switch (Lex.getKind()) {
3066 default: return TokError("expected value token");
3067 case lltok::GlobalID: // @42
3068 ID.UIntVal = Lex.getUIntVal();
3069 ID.Kind = ValID::t_GlobalID;
3070 break;
3071 case lltok::GlobalVar: // @foo
3072 ID.StrVal = Lex.getStrVal();
3073 ID.Kind = ValID::t_GlobalName;
3074 break;
3075 case lltok::LocalVarID: // %42
3076 ID.UIntVal = Lex.getUIntVal();
3077 ID.Kind = ValID::t_LocalID;
3078 break;
3079 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00003080 ID.StrVal = Lex.getStrVal();
3081 ID.Kind = ValID::t_LocalName;
3082 break;
3083 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003085 ID.Kind = ValID::t_APSInt;
3086 break;
3087 case lltok::APFloat:
3088 ID.APFloatVal = Lex.getAPFloatVal();
3089 ID.Kind = ValID::t_APFloat;
3090 break;
3091 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00003092 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 ID.Kind = ValID::t_Constant;
3094 break;
3095 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00003096 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 ID.Kind = ValID::t_Constant;
3098 break;
3099 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3100 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3101 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00003102 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003103
Chris Lattnerac161bf2009-01-02 07:01:27 +00003104 case lltok::lbrace: {
3105 // ValID ::= '{' ConstVector '}'
3106 Lex.Lex();
3107 SmallVector<Constant*, 16> Elts;
3108 if (ParseGlobalValueVector(Elts) ||
3109 ParseToken(lltok::rbrace, "expected end of struct constant"))
3110 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003111
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003112 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003113 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00003114 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3115 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003116 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003117 return false;
3118 }
3119 case lltok::less: {
3120 // ValID ::= '<' ConstVector '>' --> Vector.
3121 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3122 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00003123 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003124
Chris Lattnerac161bf2009-01-02 07:01:27 +00003125 SmallVector<Constant*, 16> Elts;
3126 LocTy FirstEltLoc = Lex.getLoc();
3127 if (ParseGlobalValueVector(Elts) ||
3128 (isPackedStruct &&
3129 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3130 ParseToken(lltok::greater, "expected end of constant"))
3131 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003132
Chris Lattnerac161bf2009-01-02 07:01:27 +00003133 if (isPackedStruct) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003134 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
David Blaikieadbda4b2015-08-03 20:08:41 +00003135 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3136 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003137 ID.UIntVal = Elts.size();
3138 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003139 return false;
3140 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003141
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 if (Elts.empty())
3143 return Error(ID.Loc, "constant vector must not be empty");
3144
Duncan Sands9dff9be2010-02-15 16:12:20 +00003145 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003146 !Elts[0]->getType()->isFloatingPointTy() &&
3147 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003149 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003150
Chris Lattnerac161bf2009-01-02 07:01:27 +00003151 // Verify that all the vector elements have the same type.
3152 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3153 if (Elts[i]->getType() != Elts[0]->getType())
3154 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003155 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003156 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003157
Chris Lattner69229312011-02-15 00:14:00 +00003158 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003159 ID.Kind = ValID::t_Constant;
3160 return false;
3161 }
3162 case lltok::lsquare: { // Array Constant
3163 Lex.Lex();
3164 SmallVector<Constant*, 16> Elts;
3165 LocTy FirstEltLoc = Lex.getLoc();
3166 if (ParseGlobalValueVector(Elts) ||
3167 ParseToken(lltok::rsquare, "expected end of array constant"))
3168 return true;
3169
3170 // Handle empty element.
3171 if (Elts.empty()) {
3172 // Use undef instead of an array because it's inconvenient to determine
3173 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003174 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003175 return false;
3176 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003177
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003179 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003180 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003181
Owen Anderson4056ca92009-07-29 22:17:13 +00003182 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003183
Chris Lattnerac161bf2009-01-02 07:01:27 +00003184 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003185 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003186 if (Elts[i]->getType() != Elts[0]->getType())
3187 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003188 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003189 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003191
Jay Foad83be3612011-06-22 09:24:39 +00003192 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003193 ID.Kind = ValID::t_Constant;
3194 return false;
3195 }
3196 case lltok::kw_c: // c "foo"
3197 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003198 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3199 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003200 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3201 ID.Kind = ValID::t_Constant;
3202 return false;
3203
3204 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003205 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3206 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003207 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003208 Lex.Lex();
3209 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003210 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003211 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003212 ParseStringConstant(ID.StrVal) ||
3213 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003214 ParseToken(lltok::StringConstant, "expected constraint string"))
3215 return true;
3216 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003217 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003218 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003219 ID.Kind = ValID::t_InlineAsm;
3220 return false;
3221 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Chris Lattner3432c622009-10-28 03:39:23 +00003223 case lltok::kw_blockaddress: {
3224 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3225 Lex.Lex();
3226
3227 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003228
Chris Lattner3432c622009-10-28 03:39:23 +00003229 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3230 ParseValID(Fn) ||
3231 ParseToken(lltok::comma, "expected comma in block address expression")||
3232 ParseValID(Label) ||
3233 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3234 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003235
Chris Lattner3432c622009-10-28 03:39:23 +00003236 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3237 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003238 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003239 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003240
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003241 // Try to find the function (but skip it if it's forward-referenced).
3242 GlobalValue *GV = nullptr;
3243 if (Fn.Kind == ValID::t_GlobalID) {
3244 if (Fn.UIntVal < NumberedVals.size())
3245 GV = NumberedVals[Fn.UIntVal];
3246 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3247 GV = M->getNamedValue(Fn.StrVal);
3248 }
3249 Function *F = nullptr;
3250 if (GV) {
3251 // Confirm that it's actually a function with a definition.
3252 if (!isa<Function>(GV))
3253 return Error(Fn.Loc, "expected function name in blockaddress");
3254 F = cast<Function>(GV);
3255 if (F->isDeclaration())
3256 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3257 }
3258
3259 if (!F) {
3260 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003261 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003262 ForwardRefBlockAddresses.insert(std::make_pair(
3263 std::move(Fn),
3264 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003265 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3266 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003267 if (!FwdRef)
3268 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3269 GlobalValue::InternalLinkage, nullptr, "");
3270 ID.ConstantVal = FwdRef;
3271 ID.Kind = ValID::t_Constant;
3272 return false;
3273 }
3274
3275 // We found the function; now find the basic block. Don't use PFS, since we
3276 // might be inside a constant expression.
3277 BasicBlock *BB;
3278 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3279 if (Label.Kind == ValID::t_LocalID)
3280 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3281 else
3282 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3283 if (!BB)
3284 return Error(Label.Loc, "referenced value is not a basic block");
3285 } else {
3286 if (Label.Kind == ValID::t_LocalID)
3287 return Error(Label.Loc, "cannot take address of numeric label after "
3288 "the function is defined");
3289 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003290 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003291 if (!BB)
3292 return Error(Label.Loc, "referenced value is not a basic block");
3293 }
3294
3295 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003296 ID.Kind = ValID::t_Constant;
3297 return false;
3298 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003299
Chris Lattnerac161bf2009-01-02 07:01:27 +00003300 case lltok::kw_trunc:
3301 case lltok::kw_zext:
3302 case lltok::kw_sext:
3303 case lltok::kw_fptrunc:
3304 case lltok::kw_fpext:
3305 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003306 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003307 case lltok::kw_uitofp:
3308 case lltok::kw_sitofp:
3309 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003310 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003311 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003312 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003313 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003314 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003315 Constant *SrcVal;
3316 Lex.Lex();
3317 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3318 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003319 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 ParseType(DestTy) ||
3321 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3322 return true;
3323 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3324 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003325 getTypeString(SrcVal->getType()) + "' to '" +
3326 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003327 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003328 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003329 ID.Kind = ValID::t_Constant;
3330 return false;
3331 }
3332 case lltok::kw_extractvalue: {
3333 Lex.Lex();
3334 Constant *Val;
3335 SmallVector<unsigned, 4> Indices;
3336 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3337 ParseGlobalTypeAndValue(Val) ||
3338 ParseIndexList(Indices) ||
3339 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3340 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003341
Chris Lattner392be582010-02-12 20:49:41 +00003342 if (!Val->getType()->isAggregateType())
3343 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003344 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003345 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003346 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003347 ID.Kind = ValID::t_Constant;
3348 return false;
3349 }
3350 case lltok::kw_insertvalue: {
3351 Lex.Lex();
3352 Constant *Val0, *Val1;
3353 SmallVector<unsigned, 4> Indices;
3354 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3355 ParseGlobalTypeAndValue(Val0) ||
3356 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3357 ParseGlobalTypeAndValue(Val1) ||
3358 ParseIndexList(Indices) ||
3359 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3360 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003361 if (!Val0->getType()->isAggregateType())
3362 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003363 Type *IndexedType =
3364 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3365 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003366 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003367 if (IndexedType != Val1->getType())
3368 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3369 getTypeString(Val1->getType()) +
3370 "' instead of '" + getTypeString(IndexedType) +
3371 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003372 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003373 ID.Kind = ValID::t_Constant;
3374 return false;
3375 }
3376 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003377 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003378 unsigned PredVal, Opc = Lex.getUIntVal();
3379 Constant *Val0, *Val1;
3380 Lex.Lex();
3381 if (ParseCmpPredicate(PredVal, Opc) ||
3382 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3383 ParseGlobalTypeAndValue(Val0) ||
3384 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3385 ParseGlobalTypeAndValue(Val1) ||
3386 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3387 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003388
Chris Lattnerac161bf2009-01-02 07:01:27 +00003389 if (Val0->getType() != Val1->getType())
3390 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003391
Chris Lattnerac161bf2009-01-02 07:01:27 +00003392 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003393
Chris Lattnerac161bf2009-01-02 07:01:27 +00003394 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003395 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003396 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003397 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003398 } else {
3399 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003400 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003401 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003402 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003403 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003404 }
3405 ID.Kind = ValID::t_Constant;
3406 return false;
3407 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00003408
3409 // Unary Operators.
3410 case lltok::kw_fneg: {
3411 unsigned Opc = Lex.getUIntVal();
3412 Constant *Val;
3413 Lex.Lex();
3414 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3415 ParseGlobalTypeAndValue(Val) ||
3416 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3417 return true;
3418
3419 // Check that the type is valid for the operator.
3420 switch (Opc) {
3421 case Instruction::FNeg:
3422 if (!Val->getType()->isFPOrFPVectorTy())
3423 return Error(ID.Loc, "constexpr requires fp operands");
3424 break;
3425 default: llvm_unreachable("Unknown unary operator!");
3426 }
3427 unsigned Flags = 0;
3428 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3429 ID.ConstantVal = C;
3430 ID.Kind = ValID::t_Constant;
3431 return false;
3432 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003433 // Binary Operators.
3434 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003435 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003436 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003437 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003438 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003439 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003440 case lltok::kw_udiv:
3441 case lltok::kw_sdiv:
3442 case lltok::kw_fdiv:
3443 case lltok::kw_urem:
3444 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003445 case lltok::kw_frem:
3446 case lltok::kw_shl:
3447 case lltok::kw_lshr:
3448 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003449 bool NUW = false;
3450 bool NSW = false;
3451 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003452 unsigned Opc = Lex.getUIntVal();
3453 Constant *Val0, *Val1;
3454 Lex.Lex();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003455 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3456 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003457 if (EatIfPresent(lltok::kw_nuw))
3458 NUW = true;
3459 if (EatIfPresent(lltok::kw_nsw)) {
3460 NSW = true;
3461 if (EatIfPresent(lltok::kw_nuw))
3462 NUW = true;
3463 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003464 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3465 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003466 if (EatIfPresent(lltok::kw_exact))
3467 Exact = true;
3468 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003469 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3470 ParseGlobalTypeAndValue(Val0) ||
3471 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3472 ParseGlobalTypeAndValue(Val1) ||
3473 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3474 return true;
3475 if (Val0->getType() != Val1->getType())
3476 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohmana2414ea2010-05-03 22:44:19 +00003477 // Check that the type is valid for the operator.
3478 switch (Opc) {
3479 case Instruction::Add:
3480 case Instruction::Sub:
3481 case Instruction::Mul:
3482 case Instruction::UDiv:
3483 case Instruction::SDiv:
3484 case Instruction::URem:
3485 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003486 case Instruction::Shl:
3487 case Instruction::AShr:
3488 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003489 if (!Val0->getType()->isIntOrIntVectorTy())
3490 return Error(ID.Loc, "constexpr requires integer operands");
3491 break;
3492 case Instruction::FAdd:
3493 case Instruction::FSub:
3494 case Instruction::FMul:
3495 case Instruction::FDiv:
3496 case Instruction::FRem:
3497 if (!Val0->getType()->isFPOrFPVectorTy())
3498 return Error(ID.Loc, "constexpr requires fp operands");
3499 break;
3500 default: llvm_unreachable("Unknown binary operator!");
3501 }
Dan Gohman1b849082009-09-07 23:54:19 +00003502 unsigned Flags = 0;
3503 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3504 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003505 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003506 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003507 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003508 ID.Kind = ValID::t_Constant;
3509 return false;
3510 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003511
Chris Lattnerac161bf2009-01-02 07:01:27 +00003512 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003513 case lltok::kw_and:
3514 case lltok::kw_or:
3515 case lltok::kw_xor: {
3516 unsigned Opc = Lex.getUIntVal();
3517 Constant *Val0, *Val1;
3518 Lex.Lex();
3519 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3520 ParseGlobalTypeAndValue(Val0) ||
3521 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3522 ParseGlobalTypeAndValue(Val1) ||
3523 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3524 return true;
3525 if (Val0->getType() != Val1->getType())
3526 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003527 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003528 return Error(ID.Loc,
3529 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003530 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003531 ID.Kind = ValID::t_Constant;
3532 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003533 }
3534
Chris Lattnerac161bf2009-01-02 07:01:27 +00003535 case lltok::kw_getelementptr:
3536 case lltok::kw_shufflevector:
3537 case lltok::kw_insertelement:
3538 case lltok::kw_extractelement:
3539 case lltok::kw_select: {
3540 unsigned Opc = Lex.getUIntVal();
3541 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003542 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003543 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003544 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003545
Dan Gohman1639c392009-07-27 21:53:46 +00003546 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003547 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003548
3549 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3550 return true;
3551
3552 LocTy ExplicitTypeLoc = Lex.getLoc();
3553 if (Opc == Instruction::GetElementPtr) {
3554 if (ParseType(Ty) ||
3555 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3556 return true;
3557 }
3558
Peter Collingbourned93620b2016-11-10 22:34:55 +00003559 Optional<unsigned> InRangeOp;
3560 if (ParseGlobalValueVector(
3561 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003562 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3563 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003564
Chris Lattnerac161bf2009-01-02 07:01:27 +00003565 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003566 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003567 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003568 return Error(ID.Loc, "base of getelementptr must be a pointer");
3569
3570 Type *BaseType = Elts[0]->getType();
3571 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003572 if (Ty != BasePointerType->getElementType())
3573 return Error(
3574 ExplicitTypeLoc,
3575 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003576
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003577 unsigned GEPWidth =
3578 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3579
Jay Foaded8db7d2011-07-21 14:31:17 +00003580 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003581 for (Constant *Val : Indices) {
3582 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003583 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003584 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003585 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003586 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003587 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003588 return Error(
3589 ID.Loc,
3590 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003591 // GEPWidth may have been unknown because the base is a scalar,
3592 // but it is known now.
3593 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003594 }
3595 }
3596
Craig Toppere3dcce92015-08-01 22:20:21 +00003597 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003598 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003599 return Error(ID.Loc, "base element of getelementptr must be sized");
3600
David Blaikie4a2e73b2015-04-02 18:55:32 +00003601 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003602 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003603
3604 if (InRangeOp) {
3605 if (*InRangeOp == 0)
3606 return Error(ID.Loc,
3607 "inrange keyword may not appear on pointer operand");
3608 --*InRangeOp;
3609 }
3610
3611 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3612 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003613 } else if (Opc == Instruction::Select) {
3614 if (Elts.size() != 3)
3615 return Error(ID.Loc, "expected three operands to select");
3616 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3617 Elts[2]))
3618 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003619 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003620 } else if (Opc == Instruction::ShuffleVector) {
3621 if (Elts.size() != 3)
3622 return Error(ID.Loc, "expected three operands to shufflevector");
3623 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3624 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003625 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003626 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003627 } else if (Opc == Instruction::ExtractElement) {
3628 if (Elts.size() != 2)
3629 return Error(ID.Loc, "expected two operands to extractelement");
3630 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3631 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003632 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003633 } else {
3634 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3635 if (Elts.size() != 3)
3636 return Error(ID.Loc, "expected three operands to insertelement");
3637 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3638 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003639 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003640 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003641 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003642
Chris Lattnerac161bf2009-01-02 07:01:27 +00003643 ID.Kind = ValID::t_Constant;
3644 return false;
3645 }
3646 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003647
Chris Lattnerac161bf2009-01-02 07:01:27 +00003648 Lex.Lex();
3649 return false;
3650}
3651
3652/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003653bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003654 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003655 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003656 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003657 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003658 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003659 if (V && !(C = dyn_cast<Constant>(V)))
3660 return Error(ID.Loc, "global values must be constants");
3661 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003662}
3663
Victor Hernandez9d75c962010-01-11 22:31:58 +00003664bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003665 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003666 return ParseType(Ty) ||
3667 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003668}
3669
Rafael Espindola83a362c2015-01-06 22:55:16 +00003670bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003671 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003672
3673 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003674 if (!EatIfPresent(lltok::kw_comdat))
3675 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003676
3677 if (EatIfPresent(lltok::lparen)) {
3678 if (Lex.getKind() != lltok::ComdatVar)
3679 return TokError("expected comdat variable");
3680 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3681 Lex.Lex();
3682 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3683 return true;
3684 } else {
3685 if (GlobalName.empty())
3686 return TokError("comdat cannot be unnamed");
3687 C = getComdat(GlobalName, KwLoc);
3688 }
3689
David Majnemerdad0a642014-06-27 18:19:56 +00003690 return false;
3691}
3692
Victor Hernandez9d75c962010-01-11 22:31:58 +00003693/// ParseGlobalValueVector
3694/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003695/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3696bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3697 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003698 // Empty list.
3699 if (Lex.getKind() == lltok::rbrace ||
3700 Lex.getKind() == lltok::rsquare ||
3701 Lex.getKind() == lltok::greater ||
3702 Lex.getKind() == lltok::rparen)
3703 return false;
3704
Peter Collingbourned93620b2016-11-10 22:34:55 +00003705 do {
3706 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3707 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003708
Peter Collingbourned93620b2016-11-10 22:34:55 +00003709 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003710 if (ParseGlobalTypeAndValue(C)) return true;
3711 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003712 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003713
3714 return false;
3715}
3716
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003717bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003718 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003719 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003720 return true;
3721
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003722 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003723 return false;
3724}
3725
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003726/// MDNode:
3727/// ::= !{ ... }
3728/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003729/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003730bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003731 if (Lex.getKind() == lltok::MetadataVar)
3732 return ParseSpecializedMDNode(N);
3733
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003734 return ParseToken(lltok::exclaim, "expected '!' here") ||
3735 ParseMDNodeTail(N);
3736}
3737
3738bool LLParser::ParseMDNodeTail(MDNode *&N) {
3739 // !{ ... }
3740 if (Lex.getKind() == lltok::lbrace)
3741 return ParseMDTuple(N);
3742
3743 // !42
3744 return ParseMDNodeID(N);
3745}
3746
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003747namespace {
3748
3749/// Structure to represent an optional metadata field.
3750template <class FieldTy> struct MDFieldImpl {
3751 typedef MDFieldImpl ImplTy;
3752 FieldTy Val;
3753 bool Seen;
3754
3755 void assign(FieldTy Val) {
3756 Seen = true;
3757 this->Val = std::move(Val);
3758 }
3759
3760 explicit MDFieldImpl(FieldTy Default)
3761 : Val(std::move(Default)), Seen(false) {}
3762};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003763
Sander de Smalenfdf40912018-01-24 09:56:07 +00003764/// Structure to represent an optional metadata field that
3765/// can be of either type (A or B) and encapsulates the
3766/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3767/// to reimplement the specifics for representing each Field.
3768template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3769 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3770 FieldTypeA A;
3771 FieldTypeB B;
3772 bool Seen;
3773
3774 enum {
3775 IsInvalid = 0,
3776 IsTypeA = 1,
3777 IsTypeB = 2
3778 } WhatIs;
3779
3780 void assign(FieldTypeA A) {
3781 Seen = true;
3782 this->A = std::move(A);
3783 WhatIs = IsTypeA;
3784 }
3785
3786 void assign(FieldTypeB B) {
3787 Seen = true;
3788 this->B = std::move(B);
3789 WhatIs = IsTypeB;
3790 }
3791
3792 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3793 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3794 WhatIs(IsInvalid) {}
3795};
3796
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003797struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3798 uint64_t Max;
3799
3800 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3801 : ImplTy(Default), Max(Max) {}
3802};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003803
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003804struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003805 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003806};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003807
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003808struct ColumnField : public MDUnsignedField {
3809 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3810};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003811
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003812struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003813 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003814 DwarfTagField(dwarf::Tag DefaultTag)
3815 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003816};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003817
Amjad Abouda9bcf162015-12-10 12:56:35 +00003818struct DwarfMacinfoTypeField : public MDUnsignedField {
3819 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3820 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3821 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3822};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003823
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003824struct DwarfAttEncodingField : public MDUnsignedField {
3825 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3826};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003827
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003828struct DwarfVirtualityField : public MDUnsignedField {
3829 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3830};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003831
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003832struct DwarfLangField : public MDUnsignedField {
3833 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3834};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003835
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003836struct DwarfCCField : public MDUnsignedField {
3837 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3838};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003839
Adrian Prantlb939a252016-03-31 23:56:58 +00003840struct EmissionKindField : public MDUnsignedField {
3841 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3842};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003843
David Blaikie66cf14d2018-08-16 21:29:55 +00003844struct NameTableKindField : public MDUnsignedField {
3845 NameTableKindField()
3846 : MDUnsignedField(
3847 0, (unsigned)
3848 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3849};
3850
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003851struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3852 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003853};
3854
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00003855struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3856 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3857};
3858
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003859struct MDSignedField : public MDFieldImpl<int64_t> {
3860 int64_t Min;
3861 int64_t Max;
3862
3863 MDSignedField(int64_t Default = 0)
3864 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3865 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3866 : ImplTy(Default), Min(Min), Max(Max) {}
3867};
3868
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003869struct MDBoolField : public MDFieldImpl<bool> {
3870 MDBoolField(bool Default = false) : ImplTy(Default) {}
3871};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003872
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003873struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003874 bool AllowNull;
3875
3876 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003877};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003878
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003879struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3880 MDConstant() : ImplTy(nullptr) {}
3881};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003882
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003883struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003884 bool AllowEmpty;
3885 MDStringField(bool AllowEmpty = true)
3886 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003887};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003888
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003889struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3890 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3891};
3892
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003893struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003894 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3895};
3896
Sander de Smalenfdf40912018-01-24 09:56:07 +00003897struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3898 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3899 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3900
3901 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3902 bool AllowNull = true)
3903 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3904
3905 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3906 bool isMDField() const { return WhatIs == IsTypeB; }
3907 int64_t getMDSignedValue() const {
3908 assert(isMDSignedField() && "Wrong field type");
3909 return A.Val;
3910 }
3911 Metadata *getMDFieldValue() const {
3912 assert(isMDField() && "Wrong field type");
3913 return B.Val;
3914 }
3915};
3916
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003917struct MDSignedOrUnsignedField
3918 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3919 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3920
3921 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3922 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3923 int64_t getMDSignedValue() const {
3924 assert(isMDSignedField() && "Wrong field type");
3925 return A.Val;
3926 }
3927 uint64_t getMDUnsignedValue() const {
3928 assert(isMDUnsignedField() && "Wrong field type");
3929 return B.Val;
3930 }
3931};
3932
Eugene Zelenko1804a772016-08-25 00:45:04 +00003933} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003934
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003935namespace llvm {
3936
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003937template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003938bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003939 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003940 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3941 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003942
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003943 auto &U = Lex.getAPSIntVal();
3944 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003945 return TokError("value for '" + Name + "' too large, limit is " +
3946 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003947 Result.assign(U.getZExtValue());
3948 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003949 Lex.Lex();
3950 return false;
3951}
3952
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003953template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003954bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3955 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3956}
3957template <>
3958bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3959 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3960}
3961
3962template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003963bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3964 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003965 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003966
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003967 if (Lex.getKind() != lltok::DwarfTag)
3968 return TokError("expected DWARF tag");
3969
3970 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3971 if (Tag == dwarf::DW_TAG_invalid)
3972 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003973 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003974
3975 Result.assign(Tag);
3976 Lex.Lex();
3977 return false;
3978}
3979
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003980template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003981bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003982 DwarfMacinfoTypeField &Result) {
3983 if (Lex.getKind() == lltok::APSInt)
3984 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3985
3986 if (Lex.getKind() != lltok::DwarfMacinfo)
3987 return TokError("expected DWARF macinfo type");
3988
3989 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3990 if (Macinfo == dwarf::DW_MACINFO_invalid)
3991 return TokError(
3992 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3993 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3994
3995 Result.assign(Macinfo);
3996 Lex.Lex();
3997 return false;
3998}
3999
4000template <>
4001bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004002 DwarfVirtualityField &Result) {
4003 if (Lex.getKind() == lltok::APSInt)
4004 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4005
4006 if (Lex.getKind() != lltok::DwarfVirtuality)
4007 return TokError("expected DWARF virtuality code");
4008
4009 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00004010 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004011 return TokError("invalid DWARF virtuality code" + Twine(" '") +
4012 Lex.getStrVal() + "'");
4013 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4014 Result.assign(Virtuality);
4015 Lex.Lex();
4016 return false;
4017}
4018
4019template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004020bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4021 if (Lex.getKind() == lltok::APSInt)
4022 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4023
4024 if (Lex.getKind() != lltok::DwarfLang)
4025 return TokError("expected DWARF language");
4026
4027 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4028 if (!Lang)
4029 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4030 "'");
4031 assert(Lang <= Result.Max && "Expected valid DWARF language");
4032 Result.assign(Lang);
4033 Lex.Lex();
4034 return false;
4035}
4036
4037template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004038bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4039 if (Lex.getKind() == lltok::APSInt)
4040 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4041
4042 if (Lex.getKind() != lltok::DwarfCC)
4043 return TokError("expected DWARF calling convention");
4044
4045 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4046 if (!CC)
4047 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
4048 "'");
4049 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4050 Result.assign(CC);
4051 Lex.Lex();
4052 return false;
4053}
4054
4055template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00004056bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
4057 if (Lex.getKind() == lltok::APSInt)
4058 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4059
4060 if (Lex.getKind() != lltok::EmissionKind)
4061 return TokError("expected emission kind");
4062
4063 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4064 if (!Kind)
4065 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4066 "'");
4067 assert(*Kind <= Result.Max && "Expected valid emission kind");
4068 Result.assign(*Kind);
4069 Lex.Lex();
4070 return false;
4071}
Fangrui Songf78650a2018-07-30 19:41:25 +00004072
Adrian Prantlb939a252016-03-31 23:56:58 +00004073template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004074bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
David Blaikie66cf14d2018-08-16 21:29:55 +00004075 NameTableKindField &Result) {
4076 if (Lex.getKind() == lltok::APSInt)
4077 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4078
4079 if (Lex.getKind() != lltok::NameTableKind)
4080 return TokError("expected nameTable kind");
4081
4082 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4083 if (!Kind)
4084 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4085 "'");
4086 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4087 Result.assign((unsigned)*Kind);
4088 Lex.Lex();
4089 return false;
4090}
4091
4092template <>
4093bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004094 DwarfAttEncodingField &Result) {
4095 if (Lex.getKind() == lltok::APSInt)
4096 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4097
4098 if (Lex.getKind() != lltok::DwarfAttEncoding)
4099 return TokError("expected DWARF type attribute encoding");
4100
4101 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4102 if (!Encoding)
4103 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4104 Lex.getStrVal() + "'");
4105 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4106 Result.assign(Encoding);
4107 Lex.Lex();
4108 return false;
4109}
4110
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004111/// DIFlagField
4112/// ::= uint32
4113/// ::= DIFlagVector
4114/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4115template <>
4116bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004117
4118 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004119 auto parseFlag = [&](DINode::DIFlags &Val) {
4120 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4121 uint32_t TempVal = static_cast<uint32_t>(Val);
4122 bool Res = ParseUInt32(TempVal);
4123 Val = static_cast<DINode::DIFlags>(TempVal);
4124 return Res;
4125 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004126
4127 if (Lex.getKind() != lltok::DIFlag)
4128 return TokError("expected debug info flag");
4129
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004130 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004131 if (!Val)
4132 return TokError(Twine("invalid debug info flag flag '") +
4133 Lex.getStrVal() + "'");
4134 Lex.Lex();
4135 return false;
4136 };
4137
4138 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004139 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004140 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00004141 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004142 if (parseFlag(Val))
4143 return true;
4144 Combined |= Val;
4145 } while (EatIfPresent(lltok::bar));
4146
4147 Result.assign(Combined);
4148 return false;
4149}
4150
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004151/// DISPFlagField
4152/// ::= uint32
4153/// ::= DISPFlagVector
4154/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4155template <>
4156bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4157
4158 // Parser for a single flag.
4159 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4160 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4161 uint32_t TempVal = static_cast<uint32_t>(Val);
4162 bool Res = ParseUInt32(TempVal);
4163 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4164 return Res;
4165 }
4166
4167 if (Lex.getKind() != lltok::DISPFlag)
4168 return TokError("expected debug info flag");
4169
4170 Val = DISubprogram::getFlag(Lex.getStrVal());
4171 if (!Val)
4172 return TokError(Twine("invalid subprogram debug info flag '") +
4173 Lex.getStrVal() + "'");
4174 Lex.Lex();
4175 return false;
4176 };
4177
4178 // Parse the flags and combine them together.
4179 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4180 do {
4181 DISubprogram::DISPFlags Val;
4182 if (parseFlag(Val))
4183 return true;
4184 Combined |= Val;
4185 } while (EatIfPresent(lltok::bar));
4186
4187 Result.assign(Combined);
4188 return false;
4189}
4190
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004191template <>
4192bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004193 MDSignedField &Result) {
4194 if (Lex.getKind() != lltok::APSInt)
4195 return TokError("expected signed integer");
4196
4197 auto &S = Lex.getAPSIntVal();
4198 if (S < Result.Min)
4199 return TokError("value for '" + Name + "' too small, limit is " +
4200 Twine(Result.Min));
4201 if (S > Result.Max)
4202 return TokError("value for '" + Name + "' too large, limit is " +
4203 Twine(Result.Max));
4204 Result.assign(S.getExtValue());
4205 assert(Result.Val >= Result.Min && "Expected value in range");
4206 assert(Result.Val <= Result.Max && "Expected value in range");
4207 Lex.Lex();
4208 return false;
4209}
4210
4211template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004212bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4213 switch (Lex.getKind()) {
4214 default:
4215 return TokError("expected 'true' or 'false'");
4216 case lltok::kw_true:
4217 Result.assign(true);
4218 break;
4219 case lltok::kw_false:
4220 Result.assign(false);
4221 break;
4222 }
4223 Lex.Lex();
4224 return false;
4225}
4226
4227template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004228bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004229 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004230 if (!Result.AllowNull)
4231 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004232 Lex.Lex();
4233 Result.assign(nullptr);
4234 return false;
4235 }
4236
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004237 Metadata *MD;
4238 if (ParseMetadata(MD, nullptr))
4239 return true;
4240
4241 Result.assign(MD);
4242 return false;
4243}
4244
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004245template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00004246bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4247 MDSignedOrMDField &Result) {
4248 // Try to parse a signed int.
4249 if (Lex.getKind() == lltok::APSInt) {
4250 MDSignedField Res = Result.A;
4251 if (!ParseMDField(Loc, Name, Res)) {
4252 Result.assign(Res);
4253 return false;
4254 }
4255 return true;
4256 }
4257
4258 // Otherwise, try to parse as an MDField.
4259 MDField Res = Result.B;
4260 if (!ParseMDField(Loc, Name, Res)) {
4261 Result.assign(Res);
4262 return false;
4263 }
4264
4265 return true;
4266}
4267
4268template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004269bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4270 MDSignedOrUnsignedField &Result) {
4271 if (Lex.getKind() != lltok::APSInt)
4272 return false;
4273
4274 if (Lex.getAPSIntVal().isSigned()) {
4275 MDSignedField Res = Result.A;
4276 if (ParseMDField(Loc, Name, Res))
4277 return true;
4278 Result.assign(Res);
4279 return false;
4280 }
4281
4282 MDUnsignedField Res = Result.B;
4283 if (ParseMDField(Loc, Name, Res))
4284 return true;
4285 Result.assign(Res);
4286 return false;
4287}
4288
4289template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004290bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004291 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004292 std::string S;
4293 if (ParseStringConstant(S))
4294 return true;
4295
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004296 if (!Result.AllowEmpty && S.empty())
4297 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4298
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004299 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004300 return false;
4301}
4302
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004303template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004304bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4305 SmallVector<Metadata *, 4> MDs;
4306 if (ParseMDNodeVector(MDs))
4307 return true;
4308
4309 Result.assign(std::move(MDs));
4310 return false;
4311}
4312
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004313template <>
4314bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4315 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004316 Optional<DIFile::ChecksumKind> CSKind =
4317 DIFile::getChecksumKind(Lex.getStrVal());
4318
4319 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004320 return TokError(
4321 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4322
Scott Linder71603842018-02-12 19:45:54 +00004323 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004324 Lex.Lex();
4325 return false;
4326}
4327
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004328} // end namespace llvm
4329
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004330template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004331bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004332 do {
4333 if (Lex.getKind() != lltok::LabelStr)
4334 return TokError("expected field label here");
4335
4336 if (parseField())
4337 return true;
4338 } while (EatIfPresent(lltok::comma));
4339
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004340 return false;
4341}
4342
4343template <class ParserTy>
4344bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4345 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4346 Lex.Lex();
4347
4348 if (ParseToken(lltok::lparen, "expected '(' here"))
4349 return true;
4350 if (Lex.getKind() != lltok::rparen)
4351 if (ParseMDFieldsImplBody(parseField))
4352 return true;
4353
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004354 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004355 return ParseToken(lltok::rparen, "expected ')' here");
4356}
4357
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004358template <class FieldTy>
4359bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4360 if (Result.Seen)
4361 return TokError("field '" + Name + "' cannot be specified more than once");
4362
4363 LocTy Loc = Lex.getLoc();
4364 Lex.Lex();
4365 return ParseMDField(Loc, Name, Result);
4366}
4367
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004368bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4369 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004370
4371#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004372 if (Lex.getStrVal() == #CLASS) \
4373 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004374#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004375
4376 return TokError("expected metadata type");
4377}
4378
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004379#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4380#define NOP_FIELD(NAME, TYPE, INIT)
4381#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4382 if (!NAME.Seen) \
4383 return Error(ClosingLoc, "missing required field '" #NAME "'");
4384#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004385 if (Lex.getStrVal() == #NAME) \
4386 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004387#define PARSE_MD_FIELDS() \
4388 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4389 do { \
4390 LocTy ClosingLoc; \
4391 if (ParseMDFieldsImpl([&]() -> bool { \
4392 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4393 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4394 }, ClosingLoc)) \
4395 return true; \
4396 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4397 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004398#define GET_OR_DISTINCT(CLASS, ARGS) \
4399 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004400
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004401/// ParseDILocationFields:
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004402/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4403/// isImplicitCode: true)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004406 OPTIONAL(line, LineField, ); \
4407 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004408 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004409 OPTIONAL(inlinedAt, MDField, ); \
4410 OPTIONAL(isImplicitCode, MDBoolField, (false));
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004411 PARSE_MD_FIELDS();
4412#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004413
Calixte Denizeteb7f6022018-09-20 08:53:06 +00004414 Result =
4415 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4416 inlinedAt.Val, isImplicitCode.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004417 return false;
4418}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004419
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004420/// ParseGenericDINode:
4421/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4422bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004423#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004424 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004425 OPTIONAL(header, MDStringField, ); \
4426 OPTIONAL(operands, MDFieldList, );
4427 PARSE_MD_FIELDS();
4428#undef VISIT_MD_FIELDS
4429
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004430 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004431 (Context, tag.Val, header.Val, operands.Val));
4432 return false;
4433}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004434
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004435/// ParseDISubrange:
4436/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004437/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004438bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004439#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004440 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004441 OPTIONAL(lowerBound, MDSignedField, );
4442 PARSE_MD_FIELDS();
4443#undef VISIT_MD_FIELDS
4444
Sander de Smalenfdf40912018-01-24 09:56:07 +00004445 if (count.isMDSignedField())
4446 Result = GET_OR_DISTINCT(
4447 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4448 else if (count.isMDField())
4449 Result = GET_OR_DISTINCT(
4450 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4451 else
4452 return true;
4453
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004454 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004455}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004456
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004457/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004458/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004459bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004460#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004461 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004462 REQUIRED(value, MDSignedOrUnsignedField, ); \
4463 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004464 PARSE_MD_FIELDS();
4465#undef VISIT_MD_FIELDS
4466
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004467 if (isUnsigned.Val && value.isMDSignedField())
4468 return TokError("unsigned enumerator with negative value");
4469
4470 int64_t Value = value.isMDSignedField()
4471 ? value.getMDSignedValue()
4472 : static_cast<int64_t>(value.getMDUnsignedValue());
4473 Result =
4474 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4475
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004476 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004477}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004478
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004479/// ParseDIBasicType:
Adrian Prantl55f42622018-08-14 19:35:34 +00004480/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4481/// encoding: DW_ATE_encoding, flags: 0)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004482bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004483#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004484 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004485 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004486 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Adrian Prantl55f42622018-08-14 19:35:34 +00004488 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4489 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004490 PARSE_MD_FIELDS();
4491#undef VISIT_MD_FIELDS
4492
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004493 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Adrian Prantl55f42622018-08-14 19:35:34 +00004494 align.Val, encoding.Val, flags.Val));
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004495 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004496}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004497
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004498/// ParseDIDerivedType:
4499/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004500/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004501/// align: 32, offset: 0, flags: 0, extraData: !3,
4502/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004503bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004504#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4505 REQUIRED(tag, DwarfTagField, ); \
4506 OPTIONAL(name, MDStringField, ); \
4507 OPTIONAL(file, MDField, ); \
4508 OPTIONAL(line, LineField, ); \
4509 OPTIONAL(scope, MDField, ); \
4510 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004511 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004512 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004513 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004514 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004515 OPTIONAL(extraData, MDField, ); \
4516 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004517 PARSE_MD_FIELDS();
4518#undef VISIT_MD_FIELDS
4519
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004520 Optional<unsigned> DWARFAddressSpace;
4521 if (dwarfAddressSpace.Val != UINT32_MAX)
4522 DWARFAddressSpace = dwarfAddressSpace.Val;
4523
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004524 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004525 (Context, tag.Val, name.Val, file.Val, line.Val,
4526 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004527 offset.Val, DWARFAddressSpace, flags.Val,
4528 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004529 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004530}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004531
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004532bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004533#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4534 REQUIRED(tag, DwarfTagField, ); \
4535 OPTIONAL(name, MDStringField, ); \
4536 OPTIONAL(file, MDField, ); \
4537 OPTIONAL(line, LineField, ); \
4538 OPTIONAL(scope, MDField, ); \
4539 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004540 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004541 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004542 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004543 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004544 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004545 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004546 OPTIONAL(vtableHolder, MDField, ); \
4547 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004548 OPTIONAL(identifier, MDStringField, ); \
4549 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004550 PARSE_MD_FIELDS();
4551#undef VISIT_MD_FIELDS
4552
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004553 // If this has an identifier try to build an ODR type.
4554 if (identifier.Val)
4555 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004556 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4557 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4558 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004559 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004560 Result = CT;
4561 return false;
4562 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004563
4564 // Create a new node, and save it in the context if it belongs in the type
4565 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004566 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004567 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004568 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4569 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004570 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4571 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004572 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004573}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004574
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004575bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004576#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004577 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004578 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004579 REQUIRED(types, MDField, );
4580 PARSE_MD_FIELDS();
4581#undef VISIT_MD_FIELDS
4582
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004583 Result = GET_OR_DISTINCT(DISubroutineType,
4584 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004585 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004586}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004587
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004588/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004589/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004590/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004591/// checksum: "000102030405060708090a0b0c0d0e0f",
4592/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004593bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004594 // The default constructed value for checksumkind is required, but will never
4595 // be used, as the parser checks if the field was actually Seen before using
4596 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004597#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4598 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004599 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004600 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004601 OPTIONAL(checksum, MDStringField, ); \
4602 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004603 PARSE_MD_FIELDS();
4604#undef VISIT_MD_FIELDS
4605
Scott Linder71603842018-02-12 19:45:54 +00004606 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4607 if (checksumkind.Seen && checksum.Seen)
4608 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4609 else if (checksumkind.Seen || checksum.Seen)
4610 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4611
Scott Linder16c7bda2018-02-23 23:01:06 +00004612 Optional<MDString *> OptSource;
4613 if (source.Seen)
4614 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004615 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004616 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004617 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004618}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004619
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004620/// ParseDICompileUnit:
4621/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004622/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004623/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004624/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004625/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004626bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004627 if (!IsDistinct)
4628 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4629
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004630#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4631 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004632 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004633 OPTIONAL(producer, MDStringField, ); \
4634 OPTIONAL(isOptimized, MDBoolField, ); \
4635 OPTIONAL(flags, MDStringField, ); \
4636 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4637 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004638 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004639 OPTIONAL(enums, MDField, ); \
4640 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004641 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004642 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004643 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004644 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004645 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004646 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
David Blaikiebb279112018-11-13 20:08:10 +00004647 OPTIONAL(nameTableKind, NameTableKindField, ); \
4648 OPTIONAL(debugBaseAddress, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004649 PARSE_MD_FIELDS();
4650#undef VISIT_MD_FIELDS
4651
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004652 Result = DICompileUnit::getDistinct(
4653 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4654 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004655 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
David Blaikiebb279112018-11-13 20:08:10 +00004656 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4657 debugBaseAddress.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004658 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004659}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004660
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004661/// ParseDISubprogram:
4662/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004663/// file: !1, line: 7, type: !2, isLocal: false,
4664/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004665/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004666/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004667/// spFlags: 10, isOptimized: false, templateParams: !4,
4668/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004669bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004670 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004671#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4672 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004673 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004674 OPTIONAL(linkageName, MDStringField, ); \
4675 OPTIONAL(file, MDField, ); \
4676 OPTIONAL(line, LineField, ); \
4677 OPTIONAL(type, MDField, ); \
4678 OPTIONAL(isLocal, MDBoolField, ); \
4679 OPTIONAL(isDefinition, MDBoolField, (true)); \
4680 OPTIONAL(scopeLine, LineField, ); \
4681 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004682 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004683 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004684 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004685 OPTIONAL(flags, DIFlagField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004686 OPTIONAL(spFlags, DISPFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004687 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004688 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004689 OPTIONAL(templateParams, MDField, ); \
4690 OPTIONAL(declaration, MDField, ); \
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004691 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004692 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004693 PARSE_MD_FIELDS();
4694#undef VISIT_MD_FIELDS
4695
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004696 // An explicit spFlags field takes precedence over individual fields in
4697 // older IR versions.
4698 DISubprogram::DISPFlags SPFlags =
4699 spFlags.Seen ? spFlags.Val
4700 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4701 isOptimized.Val, virtuality.Val);
4702 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004703 return Lex.Error(
4704 Loc,
Paul Robinsonadcdc1b2018-11-28 21:14:32 +00004705 "missing 'distinct', required for !DISubprogram that is a Definition");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004706 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004707 DISubprogram,
4708 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
Paul Robinsoncda54212018-11-19 18:29:28 +00004709 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4710 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004711 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004712 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004713}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004714
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004715/// ParseDILexicalBlock:
4716/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4717bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004718#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004719 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004720 OPTIONAL(file, MDField, ); \
4721 OPTIONAL(line, LineField, ); \
4722 OPTIONAL(column, ColumnField, );
4723 PARSE_MD_FIELDS();
4724#undef VISIT_MD_FIELDS
4725
4726 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004727 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004728 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004729}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004730
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004731/// ParseDILexicalBlockFile:
4732/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4733bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004734#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004735 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004736 OPTIONAL(file, MDField, ); \
4737 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4738 PARSE_MD_FIELDS();
4739#undef VISIT_MD_FIELDS
4740
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004741 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004742 (Context, scope.Val, file.Val, discriminator.Val));
4743 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004744}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004745
Adrian Prantl6ed57062019-04-08 19:13:55 +00004746/// ParseDICommonBlock:
4747/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4748bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4749#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4750 REQUIRED(scope, MDField, ); \
4751 OPTIONAL(declaration, MDField, ); \
4752 OPTIONAL(name, MDStringField, ); \
4753 OPTIONAL(file, MDField, ); \
4754 OPTIONAL(line, LineField, );
4755 PARSE_MD_FIELDS();
4756#undef VISIT_MD_FIELDS
4757
4758 Result = GET_OR_DISTINCT(DICommonBlock,
4759 (Context, scope.Val, declaration.Val, name.Val,
4760 file.Val, line.Val));
4761 return false;
4762}
4763
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004764/// ParseDINamespace:
4765/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4766bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004767#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4768 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004769 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004770 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004771 PARSE_MD_FIELDS();
4772#undef VISIT_MD_FIELDS
4773
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004774 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004775 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004776 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004777}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004778
Amjad Abouda9bcf162015-12-10 12:56:35 +00004779/// ParseDIMacro:
4780/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4781bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4782#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4783 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004784 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004785 REQUIRED(name, MDStringField, ); \
4786 OPTIONAL(value, MDStringField, );
4787 PARSE_MD_FIELDS();
4788#undef VISIT_MD_FIELDS
4789
4790 Result = GET_OR_DISTINCT(DIMacro,
4791 (Context, type.Val, line.Val, name.Val, value.Val));
4792 return false;
4793}
4794
4795/// ParseDIMacroFile:
4796/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4797bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4798#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4799 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004800 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004801 REQUIRED(file, MDField, ); \
4802 OPTIONAL(nodes, MDField, );
4803 PARSE_MD_FIELDS();
4804#undef VISIT_MD_FIELDS
4805
4806 Result = GET_OR_DISTINCT(DIMacroFile,
4807 (Context, type.Val, line.Val, file.Val, nodes.Val));
4808 return false;
4809}
4810
Adrian Prantlab1243f2015-06-29 23:03:47 +00004811/// ParseDIModule:
4812/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4813/// includePath: "/usr/include", isysroot: "/")
4814bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4815#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4816 REQUIRED(scope, MDField, ); \
4817 REQUIRED(name, MDStringField, ); \
4818 OPTIONAL(configMacros, MDStringField, ); \
4819 OPTIONAL(includePath, MDStringField, ); \
4820 OPTIONAL(isysroot, MDStringField, );
4821 PARSE_MD_FIELDS();
4822#undef VISIT_MD_FIELDS
4823
4824 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4825 configMacros.Val, includePath.Val, isysroot.Val));
4826 return false;
4827}
4828
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004829/// ParseDITemplateTypeParameter:
4830/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4831bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004832#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004833 OPTIONAL(name, MDStringField, ); \
4834 REQUIRED(type, MDField, );
4835 PARSE_MD_FIELDS();
4836#undef VISIT_MD_FIELDS
4837
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004838 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004839 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004840 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004841}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004842
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004843/// ParseDITemplateValueParameter:
4844/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004845/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004846bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004847#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004848 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004849 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004850 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004851 REQUIRED(value, MDField, );
4852 PARSE_MD_FIELDS();
4853#undef VISIT_MD_FIELDS
4854
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004855 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004856 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004857 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004858}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004859
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004860/// ParseDIGlobalVariable:
4861/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004862/// file: !1, line: 7, type: !2, isLocal: false,
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004863/// isDefinition: true, templateParams: !3,
4864/// declaration: !4, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004865bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004866#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004867 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004868 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004869 OPTIONAL(linkageName, MDStringField, ); \
4870 OPTIONAL(file, MDField, ); \
4871 OPTIONAL(line, LineField, ); \
4872 OPTIONAL(type, MDField, ); \
4873 OPTIONAL(isLocal, MDBoolField, ); \
4874 OPTIONAL(isDefinition, MDBoolField, (true)); \
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004875 OPTIONAL(templateParams, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004876 OPTIONAL(declaration, MDField, ); \
4877 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004878 PARSE_MD_FIELDS();
4879#undef VISIT_MD_FIELDS
4880
Matthew Vossf8ab35a2018-10-03 18:44:53 +00004881 Result =
4882 GET_OR_DISTINCT(DIGlobalVariable,
4883 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4884 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4885 declaration.Val, templateParams.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004886 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004887}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004888
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004889/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004890/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004891/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4892/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004893/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004894/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4895/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004896bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004897#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004898 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004899 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004900 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004901 OPTIONAL(file, MDField, ); \
4902 OPTIONAL(line, LineField, ); \
4903 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004904 OPTIONAL(flags, DIFlagField, ); \
4905 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004906 PARSE_MD_FIELDS();
4907#undef VISIT_MD_FIELDS
4908
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004909 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004910 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004911 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004912 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004913}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004914
Shiva Chen2c864552018-05-09 02:40:45 +00004915/// ParseDILabel:
4916/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4917bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4918#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4919 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4920 REQUIRED(name, MDStringField, ); \
4921 REQUIRED(file, MDField, ); \
4922 REQUIRED(line, LineField, );
4923 PARSE_MD_FIELDS();
4924#undef VISIT_MD_FIELDS
4925
4926 Result = GET_OR_DISTINCT(DILabel,
4927 (Context, scope.Val, name.Val, file.Val, line.Val));
4928 return false;
4929}
4930
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004931/// ParseDIExpression:
4932/// ::= !DIExpression(0, 7, -1)
4933bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004934 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4935 Lex.Lex();
4936
4937 if (ParseToken(lltok::lparen, "expected '(' here"))
4938 return true;
4939
4940 SmallVector<uint64_t, 8> Elements;
4941 if (Lex.getKind() != lltok::rparen)
4942 do {
4943 if (Lex.getKind() == lltok::DwarfOp) {
4944 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4945 Lex.Lex();
4946 Elements.push_back(Op);
4947 continue;
4948 }
4949 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4950 }
4951
Markus Lavinb86ce212019-03-19 13:16:28 +00004952 if (Lex.getKind() == lltok::DwarfAttEncoding) {
4953 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4954 Lex.Lex();
4955 Elements.push_back(Op);
4956 continue;
4957 }
4958 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4959 }
4960
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004961 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4962 return TokError("expected unsigned integer");
4963
4964 auto &U = Lex.getAPSIntVal();
4965 if (U.ugt(UINT64_MAX))
4966 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4967 Elements.push_back(U.getZExtValue());
4968 Lex.Lex();
4969 } while (EatIfPresent(lltok::comma));
4970
4971 if (ParseToken(lltok::rparen, "expected ')' here"))
4972 return true;
4973
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004974 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004975 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004976}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004977
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004978/// ParseDIGlobalVariableExpression:
4979/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4980bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4981 bool IsDistinct) {
4982#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4983 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004984 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004985 PARSE_MD_FIELDS();
4986#undef VISIT_MD_FIELDS
4987
4988 Result =
4989 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4990 return false;
4991}
4992
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004993/// ParseDIObjCProperty:
4994/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004995/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004996bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004998 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004999 OPTIONAL(file, MDField, ); \
5000 OPTIONAL(line, LineField, ); \
5001 OPTIONAL(setter, MDStringField, ); \
5002 OPTIONAL(getter, MDStringField, ); \
5003 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5004 OPTIONAL(type, MDField, );
5005 PARSE_MD_FIELDS();
5006#undef VISIT_MD_FIELDS
5007
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00005008 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00005009 (Context, name.Val, file.Val, line.Val, setter.Val,
5010 getter.Val, attributes.Val, type.Val));
5011 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00005012}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00005013
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00005014/// ParseDIImportedEntity:
5015/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00005016/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00005017bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00005018#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5019 REQUIRED(tag, DwarfTagField, ); \
5020 REQUIRED(scope, MDField, ); \
5021 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00005022 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00005023 OPTIONAL(line, LineField, ); \
5024 OPTIONAL(name, MDStringField, );
5025 PARSE_MD_FIELDS();
5026#undef VISIT_MD_FIELDS
5027
Adrian Prantld63bfd22017-07-19 00:09:54 +00005028 Result = GET_OR_DISTINCT(
5029 DIImportedEntity,
5030 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00005031 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00005032}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00005033
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00005034#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00005035#undef NOP_FIELD
5036#undef REQUIRE_FIELD
5037#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00005038
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005039/// ParseMetadataAsValue
5040/// ::= metadata i32 %local
5041/// ::= metadata i32 @global
5042/// ::= metadata i32 7
5043/// ::= metadata !0
5044/// ::= metadata !{...}
5045/// ::= metadata !"string"
5046bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5047 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005048 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005049 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005050 return true;
5051
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005052 V = MetadataAsValue::get(Context, MD);
5053 return false;
5054}
5055
5056/// ParseValueAsMetadata
5057/// ::= i32 %local
5058/// ::= i32 @global
5059/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00005060bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5061 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005062 Type *Ty;
5063 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00005064 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005065 return true;
5066 if (Ty->isMetadataTy())
5067 return Error(Loc, "invalid metadata-value-metadata roundtrip");
5068
5069 Value *V;
5070 if (ParseValue(Ty, V, PFS))
5071 return true;
5072
5073 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005074 return false;
5075}
5076
5077/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005078/// ::= i32 %local
5079/// ::= i32 @global
5080/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00005081/// ::= !42
5082/// ::= !{...}
5083/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00005084/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005085bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00005086 if (Lex.getKind() == lltok::MetadataVar) {
5087 MDNode *N;
5088 if (ParseSpecializedMDNode(N))
5089 return true;
5090 MD = N;
5091 return false;
5092 }
5093
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005094 // ValueAsMetadata:
5095 // <type> <value>
5096 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00005097 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005098
5099 // '!'.
5100 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5101 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00005102
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00005103 // MDString:
5104 // ::= '!' STRINGCONSTANT
5105 if (Lex.getKind() == lltok::StringConstant) {
5106 MDString *S;
5107 if (ParseMDString(S))
5108 return true;
5109 MD = S;
5110 return false;
5111 }
5112
Dan Gohman8939ba332010-07-14 18:26:50 +00005113 // MDNode:
5114 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00005115 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00005116 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00005117 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005118 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00005119 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00005120 return false;
5121}
5122
Victor Hernandez9d75c962010-01-11 22:31:58 +00005123//===----------------------------------------------------------------------===//
5124// Function Parsing.
5125//===----------------------------------------------------------------------===//
5126
Chris Lattner229907c2011-07-18 04:54:35 +00005127bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005128 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00005129 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Chris Lattnerac161bf2009-01-02 07:01:27 +00005132 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005134 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005135 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005136 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00005138 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005139 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005140 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00005141 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00005142 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00005143 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00005144 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5145 (ID.UIntVal >> 1) & 1,
5146 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00005147 return false;
5148 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 case ValID::t_GlobalName:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005150 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005151 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005152 case ValID::t_GlobalID:
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005153 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00005154 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005155 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00005156 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00005158 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00005159 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 return false;
5161 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00005162 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005163 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5164 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005165
Dan Gohman518cda42011-12-17 00:04:22 +00005166 // The lexer has no type info, so builds all half, float, and double FP
5167 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005168 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005169 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00005170 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005171 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005172 &Ignored);
5173 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00005174 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00005175 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 }
Owen Anderson69c464d2009-07-27 20:59:43 +00005177 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005178
Chris Lattner8f57d29e2009-01-05 18:24:23 +00005179 if (V->getType() != Ty)
5180 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005181 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005182
Chris Lattnerac161bf2009-01-02 07:01:27 +00005183 return false;
5184 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00005185 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005187 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 return false;
5189 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00005190 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005191 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00005192 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005193 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00005195 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00005196 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00005197 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00005198 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00005199 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00005201 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00005202 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005203 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00005204 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005205 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00005206 case ValID::t_None:
5207 if (!Ty->isTokenTy())
5208 return Error(ID.Loc, "invalid type for none constant");
5209 V = Constant::getNullValue(Ty);
5210 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005211 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00005212 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005213 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00005214
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 V = ID.ConstantVal;
5216 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005217 case ValID::t_ConstantStruct:
5218 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00005219 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005220 if (ST->getNumElements() != ID.UIntVal)
5221 return Error(ID.Loc,
5222 "initializer with struct type has wrong # elements");
5223 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5224 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005226 // Verify that the elements are compatible with the structtype.
5227 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5228 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5229 return Error(ID.Loc, "element " + Twine(i) +
5230 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005231
David Blaikieadbda4b2015-08-03 20:08:41 +00005232 V = ConstantStruct::get(
5233 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005234 } else
5235 return Error(ID.Loc, "constant expression type mismatch");
5236 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00005238 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005240
Alex Lorenzd2255952015-07-17 22:07:03 +00005241bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5242 C = nullptr;
5243 ValID ID;
5244 auto Loc = Lex.getLoc();
5245 if (ParseValID(ID, /*PFS=*/nullptr))
5246 return true;
5247 switch (ID.Kind) {
5248 case ValID::t_APSInt:
5249 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00005250 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00005251 case ValID::t_Constant:
5252 case ValID::t_ConstantStruct:
5253 case ValID::t_PackedConstantStruct: {
5254 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005255 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00005256 return true;
5257 assert(isa<Constant>(V) && "Expected a constant value");
5258 C = cast<Constant>(V);
5259 return false;
5260 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00005261 case ValID::t_Null:
5262 C = Constant::getNullValue(Ty);
5263 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00005264 default:
5265 return Error(Loc, "expected a constant value");
5266 }
5267}
5268
David Majnemer8a1c45d2015-12-12 05:38:55 +00005269bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005270 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005271 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005272 return ParseValID(ID, PFS) ||
5273 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274}
5275
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005276bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005277 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005278 return ParseType(Ty) ||
5279 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280}
5281
Chris Lattner3ed871f2009-10-27 19:13:16 +00005282bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5283 PerFunctionState &PFS) {
5284 Value *V;
5285 Loc = Lex.getLoc();
5286 if (ParseTypeAndValue(V, PFS)) return true;
5287 if (!isa<BasicBlock>(V))
5288 return Error(Loc, "expected a basic block");
5289 BB = cast<BasicBlock>(V);
5290 return false;
5291}
5292
Chris Lattnerac161bf2009-01-02 07:01:27 +00005293/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00005294/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5295/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005296/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5297/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5299 // Parse the linkage.
5300 LocTy LinkageLoc = Lex.getLoc();
5301 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005302 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005303 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005304 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005305 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005306 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005307 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005308 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005310 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5311 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005312 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005313 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 return true;
5315
5316 // Verify that the linkage is ok.
5317 switch ((GlobalValue::LinkageTypes)Linkage) {
5318 case GlobalValue::ExternalLinkage:
5319 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005320 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321 if (isDefine)
5322 return Error(LinkageLoc, "invalid linkage for function definition");
5323 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005324 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005325 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005326 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005327 case GlobalValue::LinkOnceAnyLinkage:
5328 case GlobalValue::LinkOnceODRLinkage:
5329 case GlobalValue::WeakAnyLinkage:
5330 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005331 if (!isDefine)
5332 return Error(LinkageLoc, "invalid linkage for function declaration");
5333 break;
5334 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005335 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336 return Error(LinkageLoc, "invalid function linkage type");
5337 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005338
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005339 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5340 return Error(LinkageLoc,
5341 "symbol with local linkage must have default visibility");
5342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005343 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005344 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005345
Chris Lattnerac161bf2009-01-02 07:01:27 +00005346 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005347
5348 std::string FunctionName;
5349 if (Lex.getKind() == lltok::GlobalVar) {
5350 FunctionName = Lex.getStrVal();
5351 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5352 unsigned NameID = Lex.getUIntVal();
5353
5354 if (NameID != NumberedVals.size())
5355 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005356 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005357 } else {
5358 return TokError("expected function name");
5359 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005360
Chris Lattner3822f632009-01-02 08:05:26 +00005361 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005362
Chris Lattner3822f632009-01-02 08:05:26 +00005363 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005364 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005365
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005366 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005367 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005368 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005369 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005370 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 std::string Section;
Peter Collingbourne31fda092019-05-29 03:29:01 +00005372 std::string Partition;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005374 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005375 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005376 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005377 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005378 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005379 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005380 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005382 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005383 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005384 ParseOptionalProgramAddrSpace(AddrSpace) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005385 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005386 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005387 (EatIfPresent(lltok::kw_section) &&
5388 ParseStringConstant(Section)) ||
Peter Collingbourne31fda092019-05-29 03:29:01 +00005389 (EatIfPresent(lltok::kw_partition) &&
5390 ParseStringConstant(Partition)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005391 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005392 ParseOptionalAlignment(Alignment) ||
5393 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005394 ParseStringConstant(GC)) ||
5395 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005396 ParseGlobalTypeAndValue(Prefix)) ||
5397 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005398 ParseGlobalTypeAndValue(Prologue)) ||
5399 (EatIfPresent(lltok::kw_personality) &&
5400 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005401 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005402
Michael Gottesman41748d72013-06-27 00:25:01 +00005403 if (FuncAttrs.contains(Attribute::Builtin))
5404 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005405
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005407 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005408 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005409 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005410 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005411
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412 // Okay, if we got here, the function is syntactically valid. Convert types
5413 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005414 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005415 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Chris Lattnerac161bf2009-01-02 07:01:27 +00005417 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005418 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005419 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005420 }
5421
Reid Kleckner7f720332017-04-13 00:58:09 +00005422 AttributeList PAL =
5423 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5424 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005425
Bill Wendling749a43d2012-12-30 13:50:49 +00005426 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005427 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5428
Chris Lattner229907c2011-07-18 04:54:35 +00005429 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005430 FunctionType::get(RetType, ParamTypeList, isVarArg);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005431 PointerType *PFT = PointerType::get(FT, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005432
Craig Topper2617dcc2014-04-15 06:32:26 +00005433 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434 if (!FunctionName.empty()) {
5435 // If this was a definition of a forward reference, remove the definition
5436 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005437 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 if (FRVI != ForwardRefVals.end()) {
5439 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005440 if (!Fn)
5441 return Error(FRVI->second.second, "invalid forward reference to "
5442 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005443 if (Fn->getType() != PFT)
5444 return Error(FRVI->second.second, "invalid forward reference to "
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005445 "function '" + FunctionName + "' with wrong type: "
5446 "expected '" + getTypeString(PFT) + "' but was '" +
5447 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448 ForwardRefVals.erase(FRVI);
5449 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005450 // Reject redefinitions.
5451 return Error(NameLoc, "invalid redefinition of function '" +
5452 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005453 } else if (M->getNamedValue(FunctionName)) {
5454 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005456
Dan Gohman399d6ae2009-08-29 23:37:49 +00005457 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005458 // If this is a definition of a forward referenced function, make sure the
5459 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005460 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005461 if (I != ForwardRefValIDs.end()) {
5462 Fn = cast<Function>(I->second.first);
5463 if (Fn->getType() != PFT)
5464 return Error(NameLoc, "type of definition and forward reference of '@" +
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005465 Twine(NumberedVals.size()) + "' disagree: "
5466 "expected '" + getTypeString(PFT) + "' but was '" +
5467 getTypeString(Fn->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005468 ForwardRefValIDs.erase(I);
5469 }
5470 }
5471
Craig Topper2617dcc2014-04-15 06:32:26 +00005472 if (!Fn)
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005473 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5474 FunctionName, M);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005475 else // Move the forward-reference to the correct spot in the module.
5476 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5477
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00005478 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5479
Chris Lattnerac161bf2009-01-02 07:01:27 +00005480 if (FunctionName.empty())
5481 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005482
Chris Lattnerac161bf2009-01-02 07:01:27 +00005483 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005484 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005485 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005486 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005487 Fn->setCallingConv(CC);
5488 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005489 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005490 Fn->setAlignment(Alignment);
5491 Fn->setSection(Section);
Peter Collingbourne31fda092019-05-29 03:29:01 +00005492 Fn->setPartition(Partition);
David Majnemerdad0a642014-06-27 18:19:56 +00005493 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005494 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005495 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005496 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005497 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005498 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005499
Chris Lattnerac161bf2009-01-02 07:01:27 +00005500 // Add all of the arguments we parsed to the function.
5501 Function::arg_iterator ArgIt = Fn->arg_begin();
5502 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5503 // If the argument has a name, insert it into the argument symbol table.
5504 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005505
Chris Lattnerac161bf2009-01-02 07:01:27 +00005506 // Set the name, if it conflicted, it will be auto-renamed.
5507 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005508
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005509 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005510 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5511 ArgList[i].Name + "'");
5512 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005513
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005514 if (isDefine)
5515 return false;
5516
Robin Morisset039781e2014-08-29 21:53:01 +00005517 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005518 ValID ID;
5519 if (FunctionName.empty()) {
5520 ID.Kind = ValID::t_GlobalID;
5521 ID.UIntVal = NumberedVals.size() - 1;
5522 } else {
5523 ID.Kind = ValID::t_GlobalName;
5524 ID.StrVal = FunctionName;
5525 }
5526 auto Blocks = ForwardRefBlockAddresses.find(ID);
5527 if (Blocks != ForwardRefBlockAddresses.end())
5528 return Error(Blocks->first.Loc,
5529 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005530 return false;
5531}
5532
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005533bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5534 ValID ID;
5535 if (FunctionNumber == -1) {
5536 ID.Kind = ValID::t_GlobalName;
5537 ID.StrVal = F.getName();
5538 } else {
5539 ID.Kind = ValID::t_GlobalID;
5540 ID.UIntVal = FunctionNumber;
5541 }
5542
5543 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5544 if (Blocks == P.ForwardRefBlockAddresses.end())
5545 return false;
5546
5547 for (const auto &I : Blocks->second) {
5548 const ValID &BBID = I.first;
5549 GlobalValue *GV = I.second;
5550
5551 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5552 "Expected local id or name");
5553 BasicBlock *BB;
5554 if (BBID.Kind == ValID::t_LocalName)
5555 BB = GetBB(BBID.StrVal, BBID.Loc);
5556 else
5557 BB = GetBB(BBID.UIntVal, BBID.Loc);
5558 if (!BB)
5559 return P.Error(BBID.Loc, "referenced value is not a basic block");
5560
5561 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5562 GV->eraseFromParent();
5563 }
5564
5565 P.ForwardRefBlockAddresses.erase(Blocks);
5566 return false;
5567}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005568
5569/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005570/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005571bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005572 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005573 return TokError("expected '{' in function body");
5574 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005575
Chris Lattner3432c622009-10-28 03:39:23 +00005576 int FunctionNumber = -1;
5577 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005578
Chris Lattner3432c622009-10-28 03:39:23 +00005579 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005580
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005581 // Resolve block addresses and allow basic blocks to be forward-declared
5582 // within this function.
5583 if (PFS.resolveForwardRefBlockAddresses())
5584 return true;
5585 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5586
Chris Lattnerbbddd962010-01-09 19:20:07 +00005587 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005588 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005589 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005590
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005591 while (Lex.getKind() != lltok::rbrace &&
5592 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005593 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005594
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005595 while (Lex.getKind() != lltok::rbrace)
5596 if (ParseUseListOrder(&PFS))
5597 return true;
5598
Chris Lattnerac161bf2009-01-02 07:01:27 +00005599 // Eat the }.
5600 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005601
Chris Lattnerac161bf2009-01-02 07:01:27 +00005602 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005603 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005604}
5605
5606/// ParseBasicBlock
James Y Knightc0e6b8a2019-03-22 18:27:13 +00005607/// ::= (LabelStr|LabelID)? Instruction*
Chris Lattnerac161bf2009-01-02 07:01:27 +00005608bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5609 // If this basic block starts out with a name, remember it.
5610 std::string Name;
James Y Knightc0e6b8a2019-03-22 18:27:13 +00005611 int NameID = -1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005612 LocTy NameLoc = Lex.getLoc();
5613 if (Lex.getKind() == lltok::LabelStr) {
5614 Name = Lex.getStrVal();
5615 Lex.Lex();
James Y Knightc0e6b8a2019-03-22 18:27:13 +00005616 } else if (Lex.getKind() == lltok::LabelID) {
5617 NameID = Lex.getUIntVal();
5618 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005620
James Y Knightc0e6b8a2019-03-22 18:27:13 +00005621 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005622 if (!BB)
James Y Knightc0e6b8a2019-03-22 18:27:13 +00005623 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005624
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005626
Chris Lattnerac161bf2009-01-02 07:01:27 +00005627 // Parse the instructions in this block until we get a terminator.
5628 Instruction *Inst;
5629 do {
5630 // This instruction may have three possibilities for a name: a) none
5631 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5632 LocTy NameLoc = Lex.getLoc();
5633 int NameID = -1;
5634 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005635
Chris Lattnerac161bf2009-01-02 07:01:27 +00005636 if (Lex.getKind() == lltok::LocalVarID) {
5637 NameID = Lex.getUIntVal();
5638 Lex.Lex();
5639 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5640 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005641 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005642 NameStr = Lex.getStrVal();
5643 Lex.Lex();
5644 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5645 return true;
5646 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005647
Chris Lattner77b89dc2009-12-30 05:23:43 +00005648 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005649 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005650 case InstError: return true;
5651 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005652 BB->getInstList().push_back(Inst);
5653
Chris Lattner77b89dc2009-12-30 05:23:43 +00005654 // With a normal result, we check to see if the instruction is followed by
5655 // a comma and metadata.
5656 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005657 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005658 return true;
5659 break;
5660 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005661 BB->getInstList().push_back(Inst);
5662
Chris Lattner77b89dc2009-12-30 05:23:43 +00005663 // If the instruction parser ate an extra comma at the end of it, it
5664 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005665 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005666 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005667 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005668 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005669
Chris Lattnerac161bf2009-01-02 07:01:27 +00005670 // Set the name on the instruction.
5671 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005672 } while (!Inst->isTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005673
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 return false;
5675}
5676
5677//===----------------------------------------------------------------------===//
5678// Instruction Parsing.
5679//===----------------------------------------------------------------------===//
5680
5681/// ParseInstruction - Parse one of the many different instructions.
5682///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005683int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5684 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005685 lltok::Kind Token = Lex.getKind();
5686 if (Token == lltok::Eof)
5687 return TokError("found end of file when expecting more instructions");
5688 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005689 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005690 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005691
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 switch (Token) {
5693 default: return Error(Loc, "expected instruction opcode");
5694 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005695 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005696 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5697 case lltok::kw_br: return ParseBr(Inst, PFS);
5698 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005699 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005701 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005702 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5703 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005704 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5705 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005706 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Craig Topper784929d2019-02-08 20:48:56 +00005707 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
Cameron McInallycbde0d92018-11-13 18:15:47 +00005708 // Unary Operators.
5709 case lltok::kw_fneg: {
5710 FastMathFlags FMF = EatFastMathFlagsIfPresent();
Craig Topper82796952019-05-05 17:19:19 +00005711 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
Cameron McInallycbde0d92018-11-13 18:15:47 +00005712 if (Res != 0)
5713 return Res;
5714 if (FMF.any())
5715 Inst->setFastMathFlags(FMF);
5716 return false;
5717 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005718 // Binary Operators.
5719 case lltok::kw_add:
5720 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005721 case lltok::kw_mul:
5722 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005723 bool NUW = EatIfPresent(lltok::kw_nuw);
5724 bool NSW = EatIfPresent(lltok::kw_nsw);
5725 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005726
Craig Topper82796952019-05-05 17:19:19 +00005727 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005728
Chris Lattnera676c0f2011-02-07 16:40:21 +00005729 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5730 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5731 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005732 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005733 case lltok::kw_fadd:
5734 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005735 case lltok::kw_fmul:
5736 case lltok::kw_fdiv:
5737 case lltok::kw_frem: {
5738 FastMathFlags FMF = EatFastMathFlagsIfPresent();
Craig Topper82796952019-05-05 17:19:19 +00005739 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
Michael Ilseman92053172012-11-27 00:42:44 +00005740 if (Res != 0)
5741 return Res;
5742 if (FMF.any())
5743 Inst->setFastMathFlags(FMF);
5744 return 0;
5745 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005746
Chris Lattner35315d02011-02-06 21:44:57 +00005747 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005748 case lltok::kw_udiv:
5749 case lltok::kw_lshr:
5750 case lltok::kw_ashr: {
5751 bool Exact = EatIfPresent(lltok::kw_exact);
5752
Craig Topper82796952019-05-05 17:19:19 +00005753 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
Chris Lattnera676c0f2011-02-07 16:40:21 +00005754 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5755 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005756 }
5757
Chris Lattnerac161bf2009-01-02 07:01:27 +00005758 case lltok::kw_urem:
Craig Topper82796952019-05-05 17:19:19 +00005759 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5760 /*IsFP*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005761 case lltok::kw_and:
5762 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005763 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005764 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5765 case lltok::kw_fcmp: {
5766 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5767 int Res = ParseCompare(Inst, PFS, KeywordVal);
5768 if (Res != 0)
5769 return Res;
5770 if (FMF.any())
5771 Inst->setFastMathFlags(FMF);
5772 return 0;
5773 }
5774
Chris Lattnerac161bf2009-01-02 07:01:27 +00005775 // Casts.
5776 case lltok::kw_trunc:
5777 case lltok::kw_zext:
5778 case lltok::kw_sext:
5779 case lltok::kw_fptrunc:
5780 case lltok::kw_fpext:
5781 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005782 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005783 case lltok::kw_uitofp:
5784 case lltok::kw_sitofp:
5785 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005786 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005787 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005788 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 // Other.
Sanjay Patel5a4f7cf2019-05-22 15:50:46 +00005790 case lltok::kw_select: {
5791 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5792 int Res = ParseSelect(Inst, PFS);
5793 if (Res != 0)
5794 return Res;
5795 if (FMF.any()) {
5796 if (!Inst->getType()->isFPOrFPVectorTy())
5797 return Error(Loc, "fast-math-flags specified for select without "
5798 "floating-point scalar or vector return type");
5799 Inst->setFastMathFlags(FMF);
5800 }
5801 return 0;
5802 }
Chris Lattnerb55ab542009-01-05 08:18:44 +00005803 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005804 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5805 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5806 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
Sanjay Patel6d4ea222019-09-25 14:35:02 +00005807 case lltok::kw_phi: {
5808 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5809 int Res = ParsePHI(Inst, PFS);
5810 if (Res != 0)
5811 return Res;
5812 if (FMF.any()) {
5813 if (!Inst->getType()->isFPOrFPVectorTy())
5814 return Error(Loc, "fast-math-flags specified for phi without "
5815 "floating-point scalar or vector return type");
5816 Inst->setFastMathFlags(FMF);
5817 }
5818 return 0;
5819 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005820 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005821 // Call.
5822 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5823 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5824 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005825 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005826 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005827 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005828 case lltok::kw_load: return ParseLoad(Inst, PFS);
5829 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005830 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5831 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005832 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5834 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5835 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5836 }
5837}
5838
5839/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5840bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005841 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005842 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005843 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5845 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5846 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5847 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5848 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5849 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5850 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5851 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5852 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5853 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5854 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5855 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5856 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5857 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5858 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5859 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5860 }
5861 } else {
5862 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005863 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005864 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5865 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5866 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5867 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5868 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5869 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5870 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5871 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5872 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5873 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5874 }
5875 }
5876 Lex.Lex();
5877 return false;
5878}
5879
5880//===----------------------------------------------------------------------===//
5881// Terminator Instructions.
5882//===----------------------------------------------------------------------===//
5883
5884/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005885/// ::= 'ret' void (',' !dbg, !1)*
5886/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005887bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005888 PerFunctionState &PFS) {
5889 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005890 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005891 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005892
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005893 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005894
Chris Lattnerfdd87902009-10-05 05:54:46 +00005895 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005896 if (!ResType->isVoidTy())
5897 return Error(TypeLoc, "value doesn't match function result type '" +
5898 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005899
Owen Anderson55f1c092009-08-13 21:58:54 +00005900 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005901 return false;
5902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005903
Chris Lattnerac161bf2009-01-02 07:01:27 +00005904 Value *RV;
5905 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005907 if (ResType != RV->getType())
5908 return Error(TypeLoc, "value doesn't match function result type '" +
5909 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005910
Owen Anderson55f1c092009-08-13 21:58:54 +00005911 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005912 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005913}
5914
Chris Lattnerac161bf2009-01-02 07:01:27 +00005915/// ParseBr
5916/// ::= 'br' TypeAndValue
5917/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5918bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5919 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005920 Value *Op0;
5921 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005922 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005923
Chris Lattnerac161bf2009-01-02 07:01:27 +00005924 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5925 Inst = BranchInst::Create(BB);
5926 return false;
5927 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005928
Owen Anderson55f1c092009-08-13 21:58:54 +00005929 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005930 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005931
Chris Lattnerac161bf2009-01-02 07:01:27 +00005932 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005933 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005934 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005935 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005936 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005937
Chris Lattner3ed871f2009-10-27 19:13:16 +00005938 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005939 return false;
5940}
5941
5942/// ParseSwitch
5943/// Instruction
5944/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5945/// JumpTable
5946/// ::= (TypeAndValue ',' TypeAndValue)*
5947bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5948 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005949 Value *Cond;
5950 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005951 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5952 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005953 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005954 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5955 return true;
5956
Duncan Sands19d0b472010-02-16 11:11:14 +00005957 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005958 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005959
Chris Lattnerac161bf2009-01-02 07:01:27 +00005960 // Parse the jump table pairs.
5961 SmallPtrSet<Value*, 32> SeenCases;
5962 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5963 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005964 Value *Constant;
5965 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005966
Chris Lattnerac161bf2009-01-02 07:01:27 +00005967 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5968 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005969 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005970 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005971
David Blaikie70573dc2014-11-19 07:49:26 +00005972 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005973 return Error(CondLoc, "duplicate case value in switch");
5974 if (!isa<ConstantInt>(Constant))
5975 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Chris Lattner3ed871f2009-10-27 19:13:16 +00005977 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005978 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005979
Chris Lattnerac161bf2009-01-02 07:01:27 +00005980 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005981
Chris Lattner3ed871f2009-10-27 19:13:16 +00005982 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005983 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5984 SI->addCase(Table[i].first, Table[i].second);
5985 Inst = SI;
5986 return false;
5987}
5988
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005989/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005990/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005991/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5992bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005993 LocTy AddrLoc;
5994 Value *Address;
5995 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005996 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5997 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005998 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005999
Duncan Sands19d0b472010-02-16 11:11:14 +00006000 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00006001 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006002
Chris Lattner3ed871f2009-10-27 19:13:16 +00006003 // Parse the destination list.
6004 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006005
Chris Lattner3ed871f2009-10-27 19:13:16 +00006006 if (Lex.getKind() != lltok::rsquare) {
6007 BasicBlock *DestBB;
6008 if (ParseTypeAndBasicBlock(DestBB, PFS))
6009 return true;
6010 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006011
Chris Lattner3ed871f2009-10-27 19:13:16 +00006012 while (EatIfPresent(lltok::comma)) {
6013 if (ParseTypeAndBasicBlock(DestBB, PFS))
6014 return true;
6015 DestList.push_back(DestBB);
6016 }
6017 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006018
Chris Lattner3ed871f2009-10-27 19:13:16 +00006019 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6020 return true;
6021
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00006022 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00006023 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6024 IBI->addDestination(DestList[i]);
6025 Inst = IBI;
6026 return false;
6027}
6028
Chris Lattnerac161bf2009-01-02 07:01:27 +00006029/// ParseInvoke
6030/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6031/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6032bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6033 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00006034 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006035 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00006036 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006037 unsigned CC;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006038 unsigned InvokeAddrSpace;
Craig Topper2617dcc2014-04-15 06:32:26 +00006039 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006040 LocTy RetTypeLoc;
6041 ValID CalleeID;
6042 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006043 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006044
Chris Lattner3ed871f2009-10-27 19:13:16 +00006045 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006046 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006047 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006048 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006049 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00006050 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6051 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006052 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006053 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00006054 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006055 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00006056 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006057 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006058
Chris Lattnerac161bf2009-01-02 07:01:27 +00006059 // If RetType is a non-function pointer type, then this is the short syntax
6060 // for the call, which means that RetType is just the return type. Infer the
6061 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00006062 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6063 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006064 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006065 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6067 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006068
Chris Lattnerac161bf2009-01-02 07:01:27 +00006069 if (!FunctionType::isValidReturnType(RetType))
6070 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006071
Owen Anderson4056ca92009-07-29 22:17:13 +00006072 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006074
David Blaikie41ba2b42015-07-27 23:32:19 +00006075 CalleeID.FTy = Ty;
6076
Chris Lattnerac161bf2009-01-02 07:01:27 +00006077 // Look up the callee.
6078 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006079 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6080 Callee, &PFS, /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00006081 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006082
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006083 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00006084 SmallVector<Value *, 8> Args;
6085 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006086
Chris Lattnerac161bf2009-01-02 07:01:27 +00006087 // Loop through FunctionType's arguments and ensure they are specified
6088 // correctly. Also, gather any parameter attributes.
6089 FunctionType::param_iterator I = Ty->param_begin();
6090 FunctionType::param_iterator E = Ty->param_end();
6091 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006092 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006093 if (I != E) {
6094 ExpectedTy = *I++;
6095 } else if (!Ty->isVarArg()) {
6096 return Error(ArgList[i].Loc, "too many arguments specified");
6097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006098
Chris Lattnerac161bf2009-01-02 07:01:27 +00006099 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6100 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006101 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006102 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00006103 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006105
Chris Lattnerac161bf2009-01-02 07:01:27 +00006106 if (I != E)
6107 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006108
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006109 if (FnAttrs.hasAlignmentAttr())
6110 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006111
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006112 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006113 AttributeList PAL =
6114 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6115 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006116
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006117 InvokeInst *II =
6118 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006119 II->setCallingConv(CC);
6120 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006121 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006122 Inst = II;
6123 return false;
6124}
6125
Bill Wendlingf891bf82011-07-31 06:30:59 +00006126/// ParseResume
6127/// ::= 'resume' TypeAndValue
6128bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
6129 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00006130 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
6131 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132
Bill Wendlingf891bf82011-07-31 06:30:59 +00006133 ResumeInst *RI = ResumeInst::Create(Exn);
6134 Inst = RI;
6135 return false;
6136}
Chris Lattnerac161bf2009-01-02 07:01:27 +00006137
David Majnemer654e1302015-07-31 17:58:14 +00006138bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
6139 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006140 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00006141 return true;
6142
6143 while (Lex.getKind() != lltok::rsquare) {
6144 // If this isn't the first argument, we need a comma.
6145 if (!Args.empty() &&
6146 ParseToken(lltok::comma, "expected ',' in argument list"))
6147 return true;
6148
6149 // Parse the argument.
6150 LocTy ArgLoc;
6151 Type *ArgTy = nullptr;
6152 if (ParseType(ArgTy, ArgLoc))
6153 return true;
6154
6155 Value *V;
6156 if (ArgTy->isMetadataTy()) {
6157 if (ParseMetadataAsValue(V, PFS))
6158 return true;
6159 } else {
6160 if (ParseValue(ArgTy, V, PFS))
6161 return true;
6162 }
6163 Args.push_back(V);
6164 }
6165
6166 Lex.Lex(); // Lex the ']'.
6167 return false;
6168}
6169
6170/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006171/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00006172bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006173 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00006174
David Majnemer8a1c45d2015-12-12 05:38:55 +00006175 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6176 return true;
6177
6178 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006179 return true;
David Majnemer654e1302015-07-31 17:58:14 +00006180
6181 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6182 return true;
6183
6184 BasicBlock *UnwindBB = nullptr;
6185 if (Lex.getKind() == lltok::kw_to) {
6186 Lex.Lex();
6187 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6188 return true;
6189 } else {
6190 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6191 return true;
6192 }
6193 }
6194
David Majnemer8a1c45d2015-12-12 05:38:55 +00006195 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00006196 return false;
6197}
6198
6199/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00006200/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006201bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006202 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00006203
David Majnemer8a1c45d2015-12-12 05:38:55 +00006204 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6205 return true;
6206
6207 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00006208 return true;
6209
David Majnemer0bc0eef2015-08-15 02:46:08 +00006210 BasicBlock *BB;
6211 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6212 ParseTypeAndBasicBlock(BB, PFS))
6213 return true;
6214
David Majnemer8a1c45d2015-12-12 05:38:55 +00006215 Inst = CatchReturnInst::Create(CatchPad, BB);
6216 return false;
6217}
6218
6219/// ParseCatchSwitch
6220/// ::= 'catchswitch' within Parent
6221bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6222 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00006223
6224 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6225 return true;
6226
6227 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6228 Lex.getKind() != lltok::LocalVarID)
6229 return TokError("expected scope value for catchswitch");
6230
6231 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6232 return true;
6233
6234 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6235 return true;
6236
6237 SmallVector<BasicBlock *, 32> Table;
6238 do {
6239 BasicBlock *DestBB;
6240 if (ParseTypeAndBasicBlock(DestBB, PFS))
6241 return true;
6242 Table.push_back(DestBB);
6243 } while (EatIfPresent(lltok::comma));
6244
6245 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6246 return true;
6247
6248 if (ParseToken(lltok::kw_unwind,
6249 "expected 'unwind' after catchswitch scope"))
6250 return true;
6251
6252 BasicBlock *UnwindBB = nullptr;
6253 if (EatIfPresent(lltok::kw_to)) {
6254 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6255 return true;
6256 } else {
6257 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6258 return true;
6259 }
6260
6261 auto *CatchSwitch =
6262 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6263 for (BasicBlock *DestBB : Table)
6264 CatchSwitch->addHandler(DestBB);
6265 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00006266 return false;
6267}
6268
6269/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006270/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00006271bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006272 Value *CatchSwitch = nullptr;
6273
6274 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6275 return true;
6276
6277 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6278 return TokError("expected scope value for catchpad");
6279
6280 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6281 return true;
6282
David Majnemer654e1302015-07-31 17:58:14 +00006283 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006284 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006285 return true;
6286
David Majnemer8a1c45d2015-12-12 05:38:55 +00006287 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00006288 return false;
6289}
6290
David Majnemer654e1302015-07-31 17:58:14 +00006291/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00006292/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00006293bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00006294 Value *ParentPad = nullptr;
6295
6296 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6297 return true;
6298
6299 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6300 Lex.getKind() != lltok::LocalVarID)
6301 return TokError("expected scope value for cleanuppad");
6302
6303 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6304 return true;
6305
David Majnemer654e1302015-07-31 17:58:14 +00006306 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00006307 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00006308 return true;
6309
David Majnemer8a1c45d2015-12-12 05:38:55 +00006310 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00006311 return false;
6312}
6313
Chris Lattnerac161bf2009-01-02 07:01:27 +00006314//===----------------------------------------------------------------------===//
Cameron McInallycbde0d92018-11-13 18:15:47 +00006315// Unary Operators.
6316//===----------------------------------------------------------------------===//
6317
6318/// ParseUnaryOp
6319/// ::= UnaryOp TypeAndValue ',' Value
6320///
Craig Topper82796952019-05-05 17:19:19 +00006321/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6322/// operand is allowed.
Cameron McInallycbde0d92018-11-13 18:15:47 +00006323bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
Craig Topper82796952019-05-05 17:19:19 +00006324 unsigned Opc, bool IsFP) {
Cameron McInallycbde0d92018-11-13 18:15:47 +00006325 LocTy Loc; Value *LHS;
6326 if (ParseTypeAndValue(LHS, Loc, PFS))
6327 return true;
6328
Craig Topper82796952019-05-05 17:19:19 +00006329 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6330 : LHS->getType()->isIntOrIntVectorTy();
Cameron McInallycbde0d92018-11-13 18:15:47 +00006331
6332 if (!Valid)
6333 return Error(Loc, "invalid operand type for instruction");
6334
6335 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6336 return false;
6337}
6338
Craig Topper784929d2019-02-08 20:48:56 +00006339/// ParseCallBr
6340/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6341/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6342/// '[' LabelList ']'
6343bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6344 LocTy CallLoc = Lex.getLoc();
6345 AttrBuilder RetAttrs, FnAttrs;
6346 std::vector<unsigned> FwdRefAttrGrps;
6347 LocTy NoBuiltinLoc;
6348 unsigned CC;
6349 Type *RetType = nullptr;
6350 LocTy RetTypeLoc;
6351 ValID CalleeID;
6352 SmallVector<ParamInfo, 16> ArgList;
6353 SmallVector<OperandBundleDef, 2> BundleList;
6354
6355 BasicBlock *DefaultDest;
6356 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6357 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6358 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6359 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6360 NoBuiltinLoc) ||
6361 ParseOptionalOperandBundles(BundleList, PFS) ||
6362 ParseToken(lltok::kw_to, "expected 'to' in callbr") ||
6363 ParseTypeAndBasicBlock(DefaultDest, PFS) ||
6364 ParseToken(lltok::lsquare, "expected '[' in callbr"))
6365 return true;
6366
6367 // Parse the destination list.
6368 SmallVector<BasicBlock *, 16> IndirectDests;
6369
6370 if (Lex.getKind() != lltok::rsquare) {
6371 BasicBlock *DestBB;
6372 if (ParseTypeAndBasicBlock(DestBB, PFS))
6373 return true;
6374 IndirectDests.push_back(DestBB);
6375
6376 while (EatIfPresent(lltok::comma)) {
6377 if (ParseTypeAndBasicBlock(DestBB, PFS))
6378 return true;
6379 IndirectDests.push_back(DestBB);
6380 }
6381 }
6382
6383 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6384 return true;
6385
6386 // If RetType is a non-function pointer type, then this is the short syntax
6387 // for the call, which means that RetType is just the return type. Infer the
6388 // rest of the function argument types from the arguments that are present.
6389 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6390 if (!Ty) {
6391 // Pull out the types of all of the arguments...
6392 std::vector<Type *> ParamTypes;
6393 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6394 ParamTypes.push_back(ArgList[i].V->getType());
6395
6396 if (!FunctionType::isValidReturnType(RetType))
6397 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6398
6399 Ty = FunctionType::get(RetType, ParamTypes, false);
6400 }
6401
6402 CalleeID.FTy = Ty;
6403
6404 // Look up the callee.
6405 Value *Callee;
6406 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6407 /*IsCall=*/true))
6408 return true;
6409
6410 if (isa<InlineAsm>(Callee) && !Ty->getReturnType()->isVoidTy())
6411 return Error(RetTypeLoc, "asm-goto outputs not supported");
6412
6413 // Set up the Attribute for the function.
6414 SmallVector<Value *, 8> Args;
6415 SmallVector<AttributeSet, 8> ArgAttrs;
6416
6417 // Loop through FunctionType's arguments and ensure they are specified
6418 // correctly. Also, gather any parameter attributes.
6419 FunctionType::param_iterator I = Ty->param_begin();
6420 FunctionType::param_iterator E = Ty->param_end();
6421 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6422 Type *ExpectedTy = nullptr;
6423 if (I != E) {
6424 ExpectedTy = *I++;
6425 } else if (!Ty->isVarArg()) {
6426 return Error(ArgList[i].Loc, "too many arguments specified");
6427 }
6428
6429 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6430 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6431 getTypeString(ExpectedTy) + "'");
6432 Args.push_back(ArgList[i].V);
6433 ArgAttrs.push_back(ArgList[i].Attrs);
6434 }
6435
6436 if (I != E)
6437 return Error(CallLoc, "not enough parameters specified for call");
6438
6439 if (FnAttrs.hasAlignmentAttr())
6440 return Error(CallLoc, "callbr instructions may not have an alignment");
6441
6442 // Finish off the Attribute and check them
6443 AttributeList PAL =
6444 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6445 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6446
6447 CallBrInst *CBI =
6448 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6449 BundleList);
6450 CBI->setCallingConv(CC);
6451 CBI->setAttributes(PAL);
6452 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6453 Inst = CBI;
6454 return false;
6455}
6456
Cameron McInallycbde0d92018-11-13 18:15:47 +00006457//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00006458// Binary Operators.
6459//===----------------------------------------------------------------------===//
6460
6461/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006462/// ::= ArithmeticOps TypeAndValue ',' Value
6463///
Craig Topper82796952019-05-05 17:19:19 +00006464/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6465/// operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00006466bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Craig Topper82796952019-05-05 17:19:19 +00006467 unsigned Opc, bool IsFP) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006468 LocTy Loc; Value *LHS, *RHS;
6469 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6470 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6471 ParseValue(LHS->getType(), RHS, PFS))
6472 return true;
6473
Craig Topper82796952019-05-05 17:19:19 +00006474 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6475 : LHS->getType()->isIntOrIntVectorTy();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006476
Chris Lattnereeefa9a2009-01-05 08:24:46 +00006477 if (!Valid)
6478 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006479
Chris Lattnerac161bf2009-01-02 07:01:27 +00006480 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6481 return false;
6482}
6483
6484/// ParseLogical
6485/// ::= ArithmeticOps TypeAndValue ',' Value {
6486bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6487 unsigned Opc) {
6488 LocTy Loc; Value *LHS, *RHS;
6489 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6490 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6491 ParseValue(LHS->getType(), RHS, PFS))
6492 return true;
6493
Duncan Sands9dff9be2010-02-15 16:12:20 +00006494 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006495 return Error(Loc,"instruction requires integer or integer vector operands");
6496
6497 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6498 return false;
6499}
6500
Chris Lattnerac161bf2009-01-02 07:01:27 +00006501/// ParseCompare
6502/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6503/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006504bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6505 unsigned Opc) {
6506 // Parse the integer/fp comparison predicate.
6507 LocTy Loc;
6508 unsigned Pred;
6509 Value *LHS, *RHS;
6510 if (ParseCmpPredicate(Pred, Opc) ||
6511 ParseTypeAndValue(LHS, Loc, PFS) ||
6512 ParseToken(lltok::comma, "expected ',' after compare value") ||
6513 ParseValue(LHS->getType(), RHS, PFS))
6514 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006515
Chris Lattnerac161bf2009-01-02 07:01:27 +00006516 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006517 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006518 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006519 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006520 } else {
6521 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006522 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006523 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006524 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006525 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006526 }
6527 return false;
6528}
6529
6530//===----------------------------------------------------------------------===//
6531// Other Instructions.
6532//===----------------------------------------------------------------------===//
6533
6534
6535/// ParseCast
6536/// ::= CastOpc TypeAndValue 'to' Type
6537bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6538 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006539 LocTy Loc;
6540 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006541 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006542 if (ParseTypeAndValue(Op, Loc, PFS) ||
6543 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6544 ParseType(DestTy))
6545 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006546
Chris Lattner89d856e2009-03-01 00:53:13 +00006547 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6548 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006549 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006550 getTypeString(Op->getType()) + "' to '" +
6551 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006552 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006553 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6554 return false;
6555}
6556
6557/// ParseSelect
6558/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6559bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6560 LocTy Loc;
6561 Value *Op0, *Op1, *Op2;
6562 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6563 ParseToken(lltok::comma, "expected ',' after select condition") ||
6564 ParseTypeAndValue(Op1, PFS) ||
6565 ParseToken(lltok::comma, "expected ',' after select value") ||
6566 ParseTypeAndValue(Op2, PFS))
6567 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006568
Chris Lattnerac161bf2009-01-02 07:01:27 +00006569 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6570 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006571
Chris Lattnerac161bf2009-01-02 07:01:27 +00006572 Inst = SelectInst::Create(Op0, Op1, Op2);
6573 return false;
6574}
6575
Chris Lattnerb55ab542009-01-05 08:18:44 +00006576/// ParseVA_Arg
6577/// ::= 'va_arg' TypeAndValue ',' Type
6578bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006579 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006580 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006581 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006582 if (ParseTypeAndValue(Op, PFS) ||
6583 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006584 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006585 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006586
Chris Lattnerb55ab542009-01-05 08:18:44 +00006587 if (!EltTy->isFirstClassType())
6588 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006589
6590 Inst = new VAArgInst(Op, EltTy);
6591 return false;
6592}
6593
6594/// ParseExtractElement
6595/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6596bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6597 LocTy Loc;
6598 Value *Op0, *Op1;
6599 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6600 ParseToken(lltok::comma, "expected ',' after extract value") ||
6601 ParseTypeAndValue(Op1, PFS))
6602 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006603
Chris Lattnerac161bf2009-01-02 07:01:27 +00006604 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6605 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006606
Eric Christopherc9742252009-07-25 02:28:41 +00006607 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006608 return false;
6609}
6610
6611/// ParseInsertElement
6612/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6613bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6614 LocTy Loc;
6615 Value *Op0, *Op1, *Op2;
6616 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6617 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6618 ParseTypeAndValue(Op1, PFS) ||
6619 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6620 ParseTypeAndValue(Op2, PFS))
6621 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006622
Chris Lattnerac161bf2009-01-02 07:01:27 +00006623 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006624 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006625
Chris Lattnerac161bf2009-01-02 07:01:27 +00006626 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6627 return false;
6628}
6629
6630/// ParseShuffleVector
6631/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6632bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6633 LocTy Loc;
6634 Value *Op0, *Op1, *Op2;
6635 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6636 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6637 ParseTypeAndValue(Op1, PFS) ||
6638 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6639 ParseTypeAndValue(Op2, PFS))
6640 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006641
Chris Lattnerac161bf2009-01-02 07:01:27 +00006642 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006643 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006644
Chris Lattnerac161bf2009-01-02 07:01:27 +00006645 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6646 return false;
6647}
6648
6649/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006650/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006651int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006652 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006653 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006654
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006655 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006656 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6657 ParseValue(Ty, Op0, PFS) ||
6658 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006659 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006660 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6661 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006662
Chris Lattnerf4f03422009-12-30 05:27:33 +00006663 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006664 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006665
6666 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006667 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006668
Chris Lattner3822f632009-01-02 08:05:26 +00006669 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006670 break;
6671
Chris Lattnerf4f03422009-12-30 05:27:33 +00006672 if (Lex.getKind() == lltok::MetadataVar) {
6673 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006674 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006675 }
Devang Patel8f842d32009-10-16 18:45:49 +00006676
Chris Lattner3822f632009-01-02 08:05:26 +00006677 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006678 ParseValue(Ty, Op0, PFS) ||
6679 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006680 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006681 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6682 return true;
6683 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006684
Chris Lattnerac161bf2009-01-02 07:01:27 +00006685 if (!Ty->isFirstClassType())
6686 return Error(TypeLoc, "phi node must have first class type");
6687
Jay Foad52131342011-03-30 11:28:46 +00006688 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006689 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6690 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6691 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006692 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006693}
6694
Bill Wendlingfae14752011-08-12 20:24:12 +00006695/// ParseLandingPad
6696/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6697/// Clause
6698/// ::= 'catch' TypeAndValue
6699/// ::= 'filter'
6700/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6701bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006702 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006703
David Majnemer7fddecc2015-06-17 20:52:32 +00006704 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006705 return true;
6706
David Majnemer7fddecc2015-06-17 20:52:32 +00006707 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006708 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6709
6710 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6711 LandingPadInst::ClauseType CT;
6712 if (EatIfPresent(lltok::kw_catch))
6713 CT = LandingPadInst::Catch;
6714 else if (EatIfPresent(lltok::kw_filter))
6715 CT = LandingPadInst::Filter;
6716 else
6717 return TokError("expected 'catch' or 'filter' clause type");
6718
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006719 Value *V;
6720 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006721 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006722 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006723
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006724 // A 'catch' type expects a non-array constant. A filter clause expects an
6725 // array constant.
6726 if (CT == LandingPadInst::Catch) {
6727 if (isa<ArrayType>(V->getType()))
6728 Error(VLoc, "'catch' clause has an invalid type");
6729 } else {
6730 if (!isa<ArrayType>(V->getType()))
6731 Error(VLoc, "'filter' clause has an invalid type");
6732 }
6733
Owen Andersonf8f259d2015-03-09 07:13:42 +00006734 Constant *CV = dyn_cast<Constant>(V);
6735 if (!CV)
6736 return Error(VLoc, "clause argument must be a constant");
6737 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006738 }
6739
Owen Andersonf8f259d2015-03-09 07:13:42 +00006740 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006741 return false;
6742}
6743
Chris Lattnerac161bf2009-01-02 07:01:27 +00006744/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006745/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6746/// OptionalAttrs Type Value ParameterList OptionalAttrs
6747/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6748/// OptionalAttrs Type Value ParameterList OptionalAttrs
6749/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6750/// OptionalAttrs Type Value ParameterList OptionalAttrs
6751/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6752/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006753bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006754 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006755 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006756 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006757 LocTy BuiltinLoc;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006758 unsigned CallAddrSpace;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006759 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006760 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006761 LocTy RetTypeLoc;
6762 ValID CalleeID;
6763 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006764 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006765 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006766
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006767 if (TCK != CallInst::TCK_None &&
6768 ParseToken(lltok::kw_call,
6769 "expected 'tail call', 'musttail call', or 'notail call'"))
6770 return true;
6771
6772 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6773
6774 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006775 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006776 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006777 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006778 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6779 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006780 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6781 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006782 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006783
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006784 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6785 return Error(CallLoc, "fast-math-flags specified for call without "
6786 "floating-point scalar or vector return type");
6787
Chris Lattnerac161bf2009-01-02 07:01:27 +00006788 // If RetType is a non-function pointer type, then this is the short syntax
6789 // for the call, which means that RetType is just the return type. Infer the
6790 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006791 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6792 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006793 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006794 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006795 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6796 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006797
Chris Lattnerac161bf2009-01-02 07:01:27 +00006798 if (!FunctionType::isValidReturnType(RetType))
6799 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006800
Owen Anderson4056ca92009-07-29 22:17:13 +00006801 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006802 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006803
David Blaikie41ba2b42015-07-27 23:32:19 +00006804 CalleeID.FTy = Ty;
6805
Chris Lattnerac161bf2009-01-02 07:01:27 +00006806 // Look up the callee.
6807 Value *Callee;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00006808 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6809 &PFS, /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006810 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006811
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006812 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006813 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006814
Chris Lattnerac161bf2009-01-02 07:01:27 +00006815 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006816
Chris Lattnerac161bf2009-01-02 07:01:27 +00006817 // Loop through FunctionType's arguments and ensure they are specified
6818 // correctly. Also, gather any parameter attributes.
6819 FunctionType::param_iterator I = Ty->param_begin();
6820 FunctionType::param_iterator E = Ty->param_end();
6821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006822 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006823 if (I != E) {
6824 ExpectedTy = *I++;
6825 } else if (!Ty->isVarArg()) {
6826 return Error(ArgList[i].Loc, "too many arguments specified");
6827 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006828
Chris Lattnerac161bf2009-01-02 07:01:27 +00006829 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6830 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006831 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006832 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006833 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006834 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006835
Chris Lattnerac161bf2009-01-02 07:01:27 +00006836 if (I != E)
6837 return Error(CallLoc, "not enough parameters specified for call");
6838
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006839 if (FnAttrs.hasAlignmentAttr())
6840 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006841
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006842 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006843 AttributeList PAL =
6844 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6845 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006846
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006847 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006848 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006849 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006850 if (FMF.any())
6851 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006852 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006853 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006854 Inst = CI;
6855 return false;
6856}
6857
6858//===----------------------------------------------------------------------===//
6859// Memory Instructions.
6860//===----------------------------------------------------------------------===//
6861
6862/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006863/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006864/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006865int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006866 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006867 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006868 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006869 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006870 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006871
6872 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006873 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006874
David Majnemera3b0eb22015-02-16 08:38:03 +00006875 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006876
David Majnemera3b0eb22015-02-16 08:38:03 +00006877 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6878 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006879
Chris Lattnerb2f39502009-12-30 05:44:30 +00006880 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006881 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006882 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006883 if (ParseOptionalAlignment(Alignment))
6884 return true;
6885 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6886 return true;
6887 } else if (Lex.getKind() == lltok::kw_addrspace) {
6888 ASLoc = Lex.getLoc();
6889 if (ParseOptionalAddrSpace(AddrSpace))
6890 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006891 } else if (Lex.getKind() == lltok::MetadataVar) {
6892 AteExtraComma = true;
6893 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006894 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006895 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006896 if (EatIfPresent(lltok::comma)) {
6897 if (Lex.getKind() == lltok::kw_align) {
6898 if (ParseOptionalAlignment(Alignment))
6899 return true;
6900 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6901 return true;
6902 } else if (Lex.getKind() == lltok::kw_addrspace) {
6903 ASLoc = Lex.getLoc();
6904 if (ParseOptionalAddrSpace(AddrSpace))
6905 return true;
6906 } else if (Lex.getKind() == lltok::MetadataVar) {
6907 AteExtraComma = true;
6908 }
6909 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006910 }
6911 }
6912
Dan Gohman2140a742010-05-28 01:14:11 +00006913 if (Size && !Size->getType()->isIntegerTy())
6914 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006915
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006916 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006917 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006918 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006919 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006920 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006921}
6922
6923/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006924/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006925/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006926/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006927int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006928 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006929 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006930 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006931 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006932 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006933 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006934
6935 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006936 isAtomic = true;
6937 Lex.Lex();
6938 }
6939
Chris Lattnerbc639292011-11-27 06:56:53 +00006940 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006941 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006942 isVolatile = true;
6943 Lex.Lex();
6944 }
6945
David Blaikie15d9a4c2015-04-06 20:59:48 +00006946 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006947 LocTy ExplicitTypeLoc = Lex.getLoc();
6948 if (ParseType(Ty) ||
6949 ParseToken(lltok::comma, "expected comma after load's type") ||
6950 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006951 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006952 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6953 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006954
David Blaikie15d9a4c2015-04-06 20:59:48 +00006955 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006956 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006957 if (isAtomic && !Alignment)
6958 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006959 if (Ordering == AtomicOrdering::Release ||
6960 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006961 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006962
David Blaikiea79ac142015-02-27 21:17:42 +00006963 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6964 return Error(ExplicitTypeLoc,
6965 "explicit pointee type doesn't match operand's pointee type");
6966
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006967 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006968 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006969}
6970
6971/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006972
6973/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6974/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006975/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006976int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006977 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006978 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006979 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006980 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006981 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006982 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006983
6984 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006985 isAtomic = true;
6986 Lex.Lex();
6987 }
6988
Chris Lattnerbc639292011-11-27 06:56:53 +00006989 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006990 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006991 isVolatile = true;
6992 Lex.Lex();
6993 }
6994
Chris Lattnerac161bf2009-01-02 07:01:27 +00006995 if (ParseTypeAndValue(Val, Loc, PFS) ||
6996 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006997 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006998 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006999 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00007000 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00007001
Duncan Sands19d0b472010-02-16 11:11:14 +00007002 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00007003 return Error(PtrLoc, "store operand must be a pointer");
7004 if (!Val->getType()->isFirstClassType())
7005 return Error(Loc, "store operand must be a first class value");
7006 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7007 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00007008 if (isAtomic && !Alignment)
7009 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00007010 if (Ordering == AtomicOrdering::Acquire ||
7011 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00007012 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00007013
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007014 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00007015 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007016}
7017
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007018/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00007019/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7020/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00007021int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007022 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7023 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00007024 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7025 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007026 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00007027 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00007028 bool isWeak = false;
7029
7030 if (EatIfPresent(lltok::kw_weak))
7031 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00007032
7033 if (EatIfPresent(lltok::kw_volatile))
7034 isVolatile = true;
7035
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007036 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7037 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7038 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
7039 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7040 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007041 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00007042 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007043 return true;
7044
JF Bastien800f87a2016-04-06 21:19:33 +00007045 if (SuccessOrdering == AtomicOrdering::Unordered ||
7046 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007047 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00007048 if (isStrongerThan(FailureOrdering, SuccessOrdering))
7049 return TokError("cmpxchg failure argument shall be no stronger than the "
7050 "success argument");
7051 if (FailureOrdering == AtomicOrdering::Release ||
7052 FailureOrdering == AtomicOrdering::AcquireRelease)
7053 return TokError(
7054 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007055 if (!Ptr->getType()->isPointerTy())
7056 return Error(PtrLoc, "cmpxchg operand must be a pointer");
7057 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7058 return Error(CmpLoc, "compare value and pointer type do not match");
7059 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7060 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00007061 if (!New->getType()->isFirstClassType())
7062 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00007063 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007064 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007065 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00007066 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007067 Inst = CXI;
7068 return AteExtraComma ? InstExtraComma : InstNormal;
7069}
7070
7071/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00007072/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7073/// 'singlethread'? AtomicOrdering
7074int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007075 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7076 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00007077 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007078 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00007079 bool isVolatile = false;
Matt Arsenault39508332019-01-22 18:18:02 +00007080 bool IsFP = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007081 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00007082
7083 if (EatIfPresent(lltok::kw_volatile))
7084 isVolatile = true;
7085
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007086 switch (Lex.getKind()) {
7087 default: return TokError("expected binary operation in atomicrmw");
7088 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7089 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7090 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7091 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7092 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7093 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7094 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7095 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7096 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7097 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7098 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
Matt Arsenault39508332019-01-22 18:18:02 +00007099 case lltok::kw_fadd:
7100 Operation = AtomicRMWInst::FAdd;
7101 IsFP = true;
7102 break;
7103 case lltok::kw_fsub:
7104 Operation = AtomicRMWInst::FSub;
7105 IsFP = true;
7106 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007107 }
7108 Lex.Lex(); // Eat the operation.
7109
7110 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7111 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7112 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007113 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007114 return true;
7115
JF Bastien800f87a2016-04-06 21:19:33 +00007116 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007117 return TokError("atomicrmw cannot be unordered");
7118 if (!Ptr->getType()->isPointerTy())
7119 return Error(PtrLoc, "atomicrmw operand must be a pointer");
7120 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7121 return Error(ValLoc, "atomicrmw value and pointer type do not match");
Matt Arsenault0f83d662018-10-03 02:37:15 +00007122
Matt Arsenault39508332019-01-22 18:18:02 +00007123 if (Operation == AtomicRMWInst::Xchg) {
7124 if (!Val->getType()->isIntegerTy() &&
7125 !Val->getType()->isFloatingPointTy()) {
7126 return Error(ValLoc, "atomicrmw " +
7127 AtomicRMWInst::getOperationName(Operation) +
7128 " operand must be an integer or floating point type");
7129 }
7130 } else if (IsFP) {
7131 if (!Val->getType()->isFloatingPointTy()) {
7132 return Error(ValLoc, "atomicrmw " +
7133 AtomicRMWInst::getOperationName(Operation) +
7134 " operand must be a floating point type");
7135 }
7136 } else {
7137 if (!Val->getType()->isIntegerTy()) {
7138 return Error(ValLoc, "atomicrmw " +
7139 AtomicRMWInst::getOperationName(Operation) +
7140 " operand must be an integer");
7141 }
Matt Arsenault0cb08e42019-01-17 10:49:01 +00007142 }
7143
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007144 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7145 if (Size < 8 || (Size & (Size - 1)))
7146 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7147 " integer");
7148
7149 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007150 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00007151 RMWI->setVolatile(isVolatile);
7152 Inst = RMWI;
7153 return AteExtraComma ? InstExtraComma : InstNormal;
7154}
7155
Eli Friedmanfee02c62011-07-25 23:16:38 +00007156/// ParseFence
7157/// ::= 'fence' 'singlethread'? AtomicOrdering
7158int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00007159 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007160 SyncScope::ID SSID = SyncScope::System;
7161 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00007162 return true;
7163
JF Bastien800f87a2016-04-06 21:19:33 +00007164 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00007165 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00007166 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00007167 return TokError("fence cannot be monotonic");
7168
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00007169 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00007170 return InstNormal;
7171}
7172
Chris Lattnerac161bf2009-01-02 07:01:27 +00007173/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00007174/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00007175int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00007176 Value *Ptr = nullptr;
7177 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00007178 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00007179
Dan Gohman16cbbe42009-07-29 15:58:36 +00007180 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00007181
David Blaikie79e6c742015-02-27 19:29:02 +00007182 Type *Ty = nullptr;
7183 LocTy ExplicitTypeLoc = Lex.getLoc();
7184 if (ParseType(Ty) ||
7185 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
7186 ParseTypeAndValue(Ptr, Loc, PFS))
7187 return true;
7188
Eli Benderskyd9806682013-04-22 17:03:42 +00007189 Type *BaseType = Ptr->getType();
7190 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7191 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00007192 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00007193
David Blaikie8d757942015-03-09 23:08:44 +00007194 if (Ty != BasePointerType->getElementType())
7195 return Error(ExplicitTypeLoc,
7196 "explicit pointee type doesn't match operand's pointee type");
7197
Chris Lattnerac161bf2009-01-02 07:01:27 +00007198 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00007199 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00007200 // GEP returns a vector of pointers if at least one of parameters is a vector.
7201 // All vector parameters should have the same vector width.
7202 unsigned GEPWidth = BaseType->isVectorTy() ?
7203 BaseType->getVectorNumElements() : 0;
7204
Chris Lattner3822f632009-01-02 08:05:26 +00007205 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00007206 if (Lex.getKind() == lltok::MetadataVar) {
7207 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00007208 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00007209 }
Chris Lattner3822f632009-01-02 08:05:26 +00007210 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00007211 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00007212 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00007213
Nadav Rotem3924cb02011-12-05 06:29:09 +00007214 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00007215 unsigned ValNumEl = Val->getType()->getVectorNumElements();
7216 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00007217 return Error(EltLoc,
7218 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00007219 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00007220 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00007221 Indices.push_back(Val);
7222 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00007223
Craig Toppere3dcce92015-08-01 22:20:21 +00007224 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00007225 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00007226 return Error(Loc, "base element of getelementptr must be sized");
7227
David Blaikied33bad32015-04-17 22:32:13 +00007228 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00007229 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00007230 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00007231 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00007232 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00007233 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007234}
7235
7236/// ParseExtractValue
7237/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00007238int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00007239 Value *Val; LocTy Loc;
7240 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00007241 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007242 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00007243 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00007244 return true;
7245
Chris Lattner392be582010-02-12 20:49:41 +00007246 if (!Val->getType()->isAggregateType())
7247 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00007248
Jay Foad57aa6362011-07-13 10:26:04 +00007249 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00007250 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00007251 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00007252 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007253}
7254
7255/// ParseInsertValue
7256/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00007257int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00007258 Value *Val0, *Val1; LocTy Loc0, Loc1;
7259 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00007260 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007261 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
7262 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
7263 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00007264 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00007265 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00007266
Chris Lattner392be582010-02-12 20:49:41 +00007267 if (!Val0->getType()->isAggregateType())
7268 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00007269
David Majnemer30074532015-02-11 07:43:58 +00007270 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7271 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00007272 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00007273 if (IndexedType != Val1->getType())
7274 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7275 getTypeString(Val1->getType()) + "' instead of '" +
7276 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00007277 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00007278 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00007279}
Nick Lewycky49f89192009-04-04 07:22:01 +00007280
7281//===----------------------------------------------------------------------===//
7282// Embedded metadata.
7283//===----------------------------------------------------------------------===//
7284
7285/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007286/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007287/// Element
7288/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007289bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00007290 if (ParseToken(lltok::lbrace, "expected '{' here"))
7291 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007292
Dan Gohman1e0213a2010-07-13 19:33:27 +00007293 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007294 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00007295 return false;
7296
Nick Lewycky49f89192009-04-04 07:22:01 +00007297 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007298 // Null is a special case since it is typeless.
7299 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00007300 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00007301 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00007302 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00007303
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007304 Metadata *MD;
7305 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007306 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00007307 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00007308 } while (EatIfPresent(lltok::comma));
7309
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00007310 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00007311}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007312
7313//===----------------------------------------------------------------------===//
7314// Use-list order directives.
7315//===----------------------------------------------------------------------===//
7316bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7317 SMLoc Loc) {
7318 if (V->use_empty())
7319 return Error(Loc, "value has no uses");
7320
7321 unsigned NumUses = 0;
7322 SmallDenseMap<const Use *, unsigned, 16> Order;
7323 for (const Use &U : V->uses()) {
7324 if (++NumUses > Indexes.size())
7325 break;
7326 Order[&U] = Indexes[NumUses - 1];
7327 }
7328 if (NumUses < 2)
7329 return Error(Loc, "value only has one use");
7330 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00007331 return Error(Loc,
7332 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007333
7334 V->sortUseList([&](const Use &L, const Use &R) {
7335 return Order.lookup(&L) < Order.lookup(&R);
7336 });
7337 return false;
7338}
7339
7340/// ParseUseListOrderIndexes
7341/// ::= '{' uint32 (',' uint32)+ '}'
7342bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7343 SMLoc Loc = Lex.getLoc();
7344 if (ParseToken(lltok::lbrace, "expected '{' here"))
7345 return true;
7346 if (Lex.getKind() == lltok::rbrace)
7347 return Lex.Error("expected non-empty list of uselistorder indexes");
7348
7349 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7350 // indexes should be distinct numbers in the range [0, size-1], and should
7351 // not be in order.
7352 unsigned Offset = 0;
7353 unsigned Max = 0;
7354 bool IsOrdered = true;
7355 assert(Indexes.empty() && "Expected empty order vector");
7356 do {
7357 unsigned Index;
7358 if (ParseUInt32(Index))
7359 return true;
7360
7361 // Update consistency checks.
7362 Offset += Index - Indexes.size();
7363 Max = std::max(Max, Index);
7364 IsOrdered &= Index == Indexes.size();
7365
7366 Indexes.push_back(Index);
7367 } while (EatIfPresent(lltok::comma));
7368
7369 if (ParseToken(lltok::rbrace, "expected '}' here"))
7370 return true;
7371
7372 if (Indexes.size() < 2)
7373 return Error(Loc, "expected >= 2 uselistorder indexes");
7374 if (Offset != 0 || Max >= Indexes.size())
7375 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7376 if (IsOrdered)
7377 return Error(Loc, "expected uselistorder indexes to change the order");
7378
7379 return false;
7380}
7381
7382/// ParseUseListOrder
7383/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7384bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7385 SMLoc Loc = Lex.getLoc();
7386 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7387 return true;
7388
7389 Value *V;
7390 SmallVector<unsigned, 16> Indexes;
7391 if (ParseTypeAndValue(V, PFS) ||
7392 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7393 ParseUseListOrderIndexes(Indexes))
7394 return true;
7395
7396 return sortUseListOrder(V, Indexes, Loc);
7397}
7398
7399/// ParseUseListOrderBB
7400/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7401bool LLParser::ParseUseListOrderBB() {
7402 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7403 SMLoc Loc = Lex.getLoc();
7404 Lex.Lex();
7405
7406 ValID Fn, Label;
7407 SmallVector<unsigned, 16> Indexes;
7408 if (ParseValID(Fn) ||
7409 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7410 ParseValID(Label) ||
7411 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7412 ParseUseListOrderIndexes(Indexes))
7413 return true;
7414
7415 // Check the function.
7416 GlobalValue *GV;
7417 if (Fn.Kind == ValID::t_GlobalName)
7418 GV = M->getNamedValue(Fn.StrVal);
7419 else if (Fn.Kind == ValID::t_GlobalID)
7420 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7421 else
7422 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7423 if (!GV)
7424 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7425 auto *F = dyn_cast<Function>(GV);
7426 if (!F)
7427 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7428 if (F->isDeclaration())
7429 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7430
7431 // Check the basic block.
7432 if (Label.Kind == ValID::t_LocalID)
7433 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7434 if (Label.Kind != ValID::t_LocalName)
7435 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00007436 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00007437 if (!V)
7438 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7439 if (!isa<BasicBlock>(V))
7440 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7441
7442 return sortUseListOrder(V, Indexes, Loc);
7443}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007444
7445/// ModuleEntry
7446/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7447/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7448bool LLParser::ParseModuleEntry(unsigned ID) {
7449 assert(Lex.getKind() == lltok::kw_module);
7450 Lex.Lex();
7451
7452 std::string Path;
7453 if (ParseToken(lltok::colon, "expected ':' here") ||
7454 ParseToken(lltok::lparen, "expected '(' here") ||
7455 ParseToken(lltok::kw_path, "expected 'path' here") ||
7456 ParseToken(lltok::colon, "expected ':' here") ||
7457 ParseStringConstant(Path) ||
7458 ParseToken(lltok::comma, "expected ',' here") ||
7459 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7460 ParseToken(lltok::colon, "expected ':' here") ||
7461 ParseToken(lltok::lparen, "expected '(' here"))
7462 return true;
7463
7464 ModuleHash Hash;
7465 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7466 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7467 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7468 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7469 ParseUInt32(Hash[4]))
7470 return true;
7471
7472 if (ParseToken(lltok::rparen, "expected ')' here") ||
7473 ParseToken(lltok::rparen, "expected ')' here"))
7474 return true;
7475
7476 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7477 ModuleIdMap[ID] = ModuleEntry->first();
7478
7479 return false;
7480}
7481
7482/// TypeIdEntry
7483/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7484bool LLParser::ParseTypeIdEntry(unsigned ID) {
7485 assert(Lex.getKind() == lltok::kw_typeid);
7486 Lex.Lex();
7487
7488 std::string Name;
7489 if (ParseToken(lltok::colon, "expected ':' here") ||
7490 ParseToken(lltok::lparen, "expected '(' here") ||
7491 ParseToken(lltok::kw_name, "expected 'name' here") ||
7492 ParseToken(lltok::colon, "expected ':' here") ||
7493 ParseStringConstant(Name))
7494 return true;
7495
7496 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7497 if (ParseToken(lltok::comma, "expected ',' here") ||
7498 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7499 return true;
7500
7501 // Check if this ID was forward referenced, and if so, update the
7502 // corresponding GUIDs.
7503 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7504 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7505 for (auto TIDRef : FwdRefTIDs->second) {
7506 assert(!*TIDRef.first &&
7507 "Forward referenced type id GUID expected to be 0");
7508 *TIDRef.first = GlobalValue::getGUID(Name);
7509 }
7510 ForwardRefTypeIds.erase(FwdRefTIDs);
7511 }
7512
7513 return false;
7514}
7515
7516/// TypeIdSummary
7517/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7518bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7519 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7520 ParseToken(lltok::colon, "expected ':' here") ||
7521 ParseToken(lltok::lparen, "expected '(' here") ||
7522 ParseTypeTestResolution(TIS.TTRes))
7523 return true;
7524
7525 if (EatIfPresent(lltok::comma)) {
7526 // Expect optional wpdResolutions field
7527 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7528 return true;
7529 }
7530
7531 if (ParseToken(lltok::rparen, "expected ')' here"))
7532 return true;
7533
7534 return false;
7535}
7536
Teresa Johnsona7004362019-07-02 19:38:02 +00007537static ValueInfo EmptyVI =
7538 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7539
7540/// TypeIdCompatibleVtableEntry
7541/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7542/// TypeIdCompatibleVtableInfo
7543/// ')'
7544bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) {
7545 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7546 Lex.Lex();
7547
7548 std::string Name;
7549 if (ParseToken(lltok::colon, "expected ':' here") ||
7550 ParseToken(lltok::lparen, "expected '(' here") ||
7551 ParseToken(lltok::kw_name, "expected 'name' here") ||
7552 ParseToken(lltok::colon, "expected ':' here") ||
7553 ParseStringConstant(Name))
7554 return true;
7555
7556 TypeIdCompatibleVtableInfo &TI =
7557 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7558 if (ParseToken(lltok::comma, "expected ',' here") ||
7559 ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7560 ParseToken(lltok::colon, "expected ':' here") ||
7561 ParseToken(lltok::lparen, "expected '(' here"))
7562 return true;
7563
7564 IdToIndexMapType IdToIndexMap;
7565 // Parse each call edge
7566 do {
7567 uint64_t Offset;
7568 if (ParseToken(lltok::lparen, "expected '(' here") ||
7569 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7570 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7571 ParseToken(lltok::comma, "expected ',' here"))
7572 return true;
7573
7574 LocTy Loc = Lex.getLoc();
7575 unsigned GVId;
7576 ValueInfo VI;
7577 if (ParseGVReference(VI, GVId))
7578 return true;
7579
7580 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7581 // forward reference. We will save the location of the ValueInfo needing an
7582 // update, but can only do so once the std::vector is finalized.
7583 if (VI == EmptyVI)
7584 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7585 TI.push_back({Offset, VI});
7586
7587 if (ParseToken(lltok::rparen, "expected ')' in call"))
7588 return true;
7589 } while (EatIfPresent(lltok::comma));
7590
7591 // Now that the TI vector is finalized, it is safe to save the locations
7592 // of any forward GV references that need updating later.
7593 for (auto I : IdToIndexMap) {
7594 for (auto P : I.second) {
7595 assert(TI[P.first].VTableVI == EmptyVI &&
7596 "Forward referenced ValueInfo expected to be empty");
7597 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7598 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7599 FwdRef.first->second.push_back(
7600 std::make_pair(&TI[P.first].VTableVI, P.second));
7601 }
7602 }
7603
7604 if (ParseToken(lltok::rparen, "expected ')' here") ||
7605 ParseToken(lltok::rparen, "expected ')' here"))
7606 return true;
7607
7608 // Check if this ID was forward referenced, and if so, update the
7609 // corresponding GUIDs.
7610 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7611 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7612 for (auto TIDRef : FwdRefTIDs->second) {
7613 assert(!*TIDRef.first &&
7614 "Forward referenced type id GUID expected to be 0");
7615 *TIDRef.first = GlobalValue::getGUID(Name);
7616 }
7617 ForwardRefTypeIds.erase(FwdRefTIDs);
7618 }
7619
7620 return false;
7621}
7622
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007623/// TypeTestResolution
7624/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7625/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7626/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7627/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7628/// [',' 'inlinesBits' ':' UInt64]? ')'
7629bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7630 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7631 ParseToken(lltok::colon, "expected ':' here") ||
7632 ParseToken(lltok::lparen, "expected '(' here") ||
7633 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7634 ParseToken(lltok::colon, "expected ':' here"))
7635 return true;
7636
7637 switch (Lex.getKind()) {
7638 case lltok::kw_unsat:
7639 TTRes.TheKind = TypeTestResolution::Unsat;
7640 break;
7641 case lltok::kw_byteArray:
7642 TTRes.TheKind = TypeTestResolution::ByteArray;
7643 break;
7644 case lltok::kw_inline:
7645 TTRes.TheKind = TypeTestResolution::Inline;
7646 break;
7647 case lltok::kw_single:
7648 TTRes.TheKind = TypeTestResolution::Single;
7649 break;
7650 case lltok::kw_allOnes:
7651 TTRes.TheKind = TypeTestResolution::AllOnes;
7652 break;
7653 default:
7654 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7655 }
7656 Lex.Lex();
7657
7658 if (ParseToken(lltok::comma, "expected ',' here") ||
7659 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7660 ParseToken(lltok::colon, "expected ':' here") ||
7661 ParseUInt32(TTRes.SizeM1BitWidth))
7662 return true;
7663
7664 // Parse optional fields
7665 while (EatIfPresent(lltok::comma)) {
7666 switch (Lex.getKind()) {
7667 case lltok::kw_alignLog2:
7668 Lex.Lex();
7669 if (ParseToken(lltok::colon, "expected ':'") ||
7670 ParseUInt64(TTRes.AlignLog2))
7671 return true;
7672 break;
7673 case lltok::kw_sizeM1:
7674 Lex.Lex();
7675 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7676 return true;
7677 break;
7678 case lltok::kw_bitMask: {
7679 unsigned Val;
7680 Lex.Lex();
7681 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7682 return true;
7683 assert(Val <= 0xff);
7684 TTRes.BitMask = (uint8_t)Val;
7685 break;
7686 }
7687 case lltok::kw_inlineBits:
7688 Lex.Lex();
7689 if (ParseToken(lltok::colon, "expected ':'") ||
7690 ParseUInt64(TTRes.InlineBits))
7691 return true;
7692 break;
7693 default:
7694 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7695 }
7696 }
7697
7698 if (ParseToken(lltok::rparen, "expected ')' here"))
7699 return true;
7700
7701 return false;
7702}
7703
7704/// OptionalWpdResolutions
7705/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7706/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7707bool LLParser::ParseOptionalWpdResolutions(
7708 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7709 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7710 ParseToken(lltok::colon, "expected ':' here") ||
7711 ParseToken(lltok::lparen, "expected '(' here"))
7712 return true;
7713
7714 do {
7715 uint64_t Offset;
7716 WholeProgramDevirtResolution WPDRes;
7717 if (ParseToken(lltok::lparen, "expected '(' here") ||
7718 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7719 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7720 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7721 ParseToken(lltok::rparen, "expected ')' here"))
7722 return true;
7723 WPDResMap[Offset] = WPDRes;
7724 } while (EatIfPresent(lltok::comma));
7725
7726 if (ParseToken(lltok::rparen, "expected ')' here"))
7727 return true;
7728
7729 return false;
7730}
7731
7732/// WpdRes
7733/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7734/// [',' OptionalResByArg]? ')'
7735/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7736/// ',' 'singleImplName' ':' STRINGCONSTANT ','
7737/// [',' OptionalResByArg]? ')'
7738/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7739/// [',' OptionalResByArg]? ')'
7740bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7741 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7742 ParseToken(lltok::colon, "expected ':' here") ||
7743 ParseToken(lltok::lparen, "expected '(' here") ||
7744 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7745 ParseToken(lltok::colon, "expected ':' here"))
7746 return true;
7747
7748 switch (Lex.getKind()) {
7749 case lltok::kw_indir:
7750 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7751 break;
7752 case lltok::kw_singleImpl:
7753 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7754 break;
7755 case lltok::kw_branchFunnel:
7756 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7757 break;
7758 default:
7759 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7760 }
7761 Lex.Lex();
7762
7763 // Parse optional fields
7764 while (EatIfPresent(lltok::comma)) {
7765 switch (Lex.getKind()) {
7766 case lltok::kw_singleImplName:
7767 Lex.Lex();
7768 if (ParseToken(lltok::colon, "expected ':' here") ||
7769 ParseStringConstant(WPDRes.SingleImplName))
7770 return true;
7771 break;
7772 case lltok::kw_resByArg:
7773 if (ParseOptionalResByArg(WPDRes.ResByArg))
7774 return true;
7775 break;
7776 default:
7777 return Error(Lex.getLoc(),
7778 "expected optional WholeProgramDevirtResolution field");
7779 }
7780 }
7781
7782 if (ParseToken(lltok::rparen, "expected ')' here"))
7783 return true;
7784
7785 return false;
7786}
7787
7788/// OptionalResByArg
7789/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7790/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7791/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7792/// 'virtualConstProp' )
7793/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7794/// [',' 'bit' ':' UInt32]? ')'
7795bool LLParser::ParseOptionalResByArg(
7796 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7797 &ResByArg) {
7798 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7799 ParseToken(lltok::colon, "expected ':' here") ||
7800 ParseToken(lltok::lparen, "expected '(' here"))
7801 return true;
7802
7803 do {
7804 std::vector<uint64_t> Args;
7805 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7806 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7807 ParseToken(lltok::colon, "expected ':' here") ||
7808 ParseToken(lltok::lparen, "expected '(' here") ||
7809 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7810 ParseToken(lltok::colon, "expected ':' here"))
7811 return true;
7812
7813 WholeProgramDevirtResolution::ByArg ByArg;
7814 switch (Lex.getKind()) {
7815 case lltok::kw_indir:
7816 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7817 break;
7818 case lltok::kw_uniformRetVal:
7819 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7820 break;
7821 case lltok::kw_uniqueRetVal:
7822 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7823 break;
7824 case lltok::kw_virtualConstProp:
7825 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7826 break;
7827 default:
7828 return Error(Lex.getLoc(),
7829 "unexpected WholeProgramDevirtResolution::ByArg kind");
7830 }
7831 Lex.Lex();
7832
7833 // Parse optional fields
7834 while (EatIfPresent(lltok::comma)) {
7835 switch (Lex.getKind()) {
7836 case lltok::kw_info:
7837 Lex.Lex();
7838 if (ParseToken(lltok::colon, "expected ':' here") ||
7839 ParseUInt64(ByArg.Info))
7840 return true;
7841 break;
7842 case lltok::kw_byte:
7843 Lex.Lex();
7844 if (ParseToken(lltok::colon, "expected ':' here") ||
7845 ParseUInt32(ByArg.Byte))
7846 return true;
7847 break;
7848 case lltok::kw_bit:
7849 Lex.Lex();
7850 if (ParseToken(lltok::colon, "expected ':' here") ||
7851 ParseUInt32(ByArg.Bit))
7852 return true;
7853 break;
7854 default:
7855 return Error(Lex.getLoc(),
7856 "expected optional whole program devirt field");
7857 }
7858 }
7859
7860 if (ParseToken(lltok::rparen, "expected ')' here"))
7861 return true;
7862
7863 ResByArg[Args] = ByArg;
7864 } while (EatIfPresent(lltok::comma));
7865
7866 if (ParseToken(lltok::rparen, "expected ')' here"))
7867 return true;
7868
7869 return false;
7870}
7871
7872/// OptionalResByArg
7873/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7874bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7875 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7876 ParseToken(lltok::colon, "expected ':' here") ||
7877 ParseToken(lltok::lparen, "expected '(' here"))
7878 return true;
7879
7880 do {
7881 uint64_t Val;
7882 if (ParseUInt64(Val))
7883 return true;
7884 Args.push_back(Val);
7885 } while (EatIfPresent(lltok::comma));
7886
7887 if (ParseToken(lltok::rparen, "expected ')' here"))
7888 return true;
7889
7890 return false;
7891}
7892
Benjamin Kramerb17d2132019-01-12 18:36:22 +00007893static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
Eugene Leviant009d8332018-11-23 10:54:51 +00007894
7895static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7896 bool ReadOnly = Fwd->isReadOnly();
Eugene Leviant3aef3522019-07-05 15:25:05 +00007897 bool WriteOnly = Fwd->isWriteOnly();
7898 assert(!(ReadOnly && WriteOnly));
Eugene Leviant009d8332018-11-23 10:54:51 +00007899 *Fwd = Resolved;
7900 if (ReadOnly)
7901 Fwd->setReadOnly();
Eugene Leviant3aef3522019-07-05 15:25:05 +00007902 if (WriteOnly)
7903 Fwd->setWriteOnly();
Eugene Leviant009d8332018-11-23 10:54:51 +00007904}
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007905
7906/// Stores the given Name/GUID and associated summary into the Index.
7907/// Also updates any forward references to the associated entry ID.
7908void LLParser::AddGlobalValueToIndex(
7909 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7910 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7911 // First create the ValueInfo utilizing the Name or GUID.
7912 ValueInfo VI;
7913 if (GUID != 0) {
7914 assert(Name.empty());
7915 VI = Index->getOrInsertValueInfo(GUID);
7916 } else {
7917 assert(!Name.empty());
7918 if (M) {
7919 auto *GV = M->getNamedValue(Name);
7920 assert(GV);
7921 VI = Index->getOrInsertValueInfo(GV);
7922 } else {
7923 assert(
7924 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7925 "Need a source_filename to compute GUID for local");
7926 GUID = GlobalValue::getGUID(
7927 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7928 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7929 }
7930 }
7931
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007932 // Resolve forward references from calls/refs
7933 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7934 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7935 for (auto VIRef : FwdRefVIs->second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00007936 assert(VIRef.first->getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007937 "Forward referenced ValueInfo expected to be empty");
Eugene Leviant009d8332018-11-23 10:54:51 +00007938 resolveFwdRef(VIRef.first, VI);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007939 }
7940 ForwardRefValueInfos.erase(FwdRefVIs);
7941 }
7942
7943 // Resolve forward references from aliases
7944 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7945 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7946 for (auto AliaseeRef : FwdRefAliasees->second) {
7947 assert(!AliaseeRef.first->hasAliasee() &&
7948 "Forward referencing alias already has aliasee");
Teresa Johnson70ec64c2019-03-15 15:11:38 +00007949 assert(Summary && "Aliasee must be a definition");
7950 AliaseeRef.first->setAliasee(VI, Summary.get());
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007951 }
7952 ForwardRefAliasees.erase(FwdRefAliasees);
7953 }
7954
Teresa Johnson70ec64c2019-03-15 15:11:38 +00007955 // Add the summary if one was provided.
7956 if (Summary)
7957 Index->addGlobalValueSummary(VI, std::move(Summary));
7958
Teresa Johnson63ee0e72018-06-26 13:56:49 +00007959 // Save the associated ValueInfo for use in later references by ID.
7960 if (ID == NumberedValueInfos.size())
7961 NumberedValueInfos.push_back(VI);
7962 else {
7963 // Handle non-continuous numbers (to make test simplification easier).
7964 if (ID > NumberedValueInfos.size())
7965 NumberedValueInfos.resize(ID + 1);
7966 NumberedValueInfos[ID] = VI;
7967 }
7968}
7969
7970/// ParseGVEntry
7971/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7972/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7973/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7974bool LLParser::ParseGVEntry(unsigned ID) {
7975 assert(Lex.getKind() == lltok::kw_gv);
7976 Lex.Lex();
7977
7978 if (ParseToken(lltok::colon, "expected ':' here") ||
7979 ParseToken(lltok::lparen, "expected '(' here"))
7980 return true;
7981
7982 std::string Name;
7983 GlobalValue::GUID GUID = 0;
7984 switch (Lex.getKind()) {
7985 case lltok::kw_name:
7986 Lex.Lex();
7987 if (ParseToken(lltok::colon, "expected ':' here") ||
7988 ParseStringConstant(Name))
7989 return true;
7990 // Can't create GUID/ValueInfo until we have the linkage.
7991 break;
7992 case lltok::kw_guid:
7993 Lex.Lex();
7994 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7995 return true;
7996 break;
7997 default:
7998 return Error(Lex.getLoc(), "expected name or guid tag");
7999 }
8000
8001 if (!EatIfPresent(lltok::comma)) {
8002 // No summaries. Wrap up.
8003 if (ParseToken(lltok::rparen, "expected ')' here"))
8004 return true;
8005 // This was created for a call to an external or indirect target.
8006 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8007 // created for indirect calls with VP. A Name with no GUID came from
8008 // an external definition. We pass ExternalLinkage since that is only
8009 // used when the GUID must be computed from Name, and in that case
8010 // the symbol must have external linkage.
8011 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8012 nullptr);
8013 return false;
8014 }
8015
8016 // Have a list of summaries
8017 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8018 ParseToken(lltok::colon, "expected ':' here"))
8019 return true;
8020
8021 do {
8022 if (ParseToken(lltok::lparen, "expected '(' here"))
8023 return true;
8024 switch (Lex.getKind()) {
8025 case lltok::kw_function:
8026 if (ParseFunctionSummary(Name, GUID, ID))
8027 return true;
8028 break;
8029 case lltok::kw_variable:
8030 if (ParseVariableSummary(Name, GUID, ID))
8031 return true;
8032 break;
8033 case lltok::kw_alias:
8034 if (ParseAliasSummary(Name, GUID, ID))
8035 return true;
8036 break;
8037 default:
8038 return Error(Lex.getLoc(), "expected summary type");
8039 }
8040 if (ParseToken(lltok::rparen, "expected ')' here"))
8041 return true;
8042 } while (EatIfPresent(lltok::comma));
8043
8044 if (ParseToken(lltok::rparen, "expected ')' here"))
8045 return true;
8046
8047 return false;
8048}
8049
8050/// FunctionSummary
8051/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8052/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8053/// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
8054bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8055 unsigned ID) {
8056 assert(Lex.getKind() == lltok::kw_function);
8057 Lex.Lex();
8058
8059 StringRef ModulePath;
8060 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8061 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
Teresa Johnson37b80122019-05-10 20:08:24 +00008062 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008063 unsigned InstCount;
8064 std::vector<FunctionSummary::EdgeTy> Calls;
8065 FunctionSummary::TypeIdInfo TypeIdInfo;
8066 std::vector<ValueInfo> Refs;
8067 // Default is all-zeros (conservative values).
8068 FunctionSummary::FFlags FFlags = {};
8069 if (ParseToken(lltok::colon, "expected ':' here") ||
8070 ParseToken(lltok::lparen, "expected '(' here") ||
8071 ParseModuleReference(ModulePath) ||
8072 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8073 ParseToken(lltok::comma, "expected ',' here") ||
8074 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
8075 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
8076 return true;
8077
8078 // Parse optional fields
8079 while (EatIfPresent(lltok::comma)) {
8080 switch (Lex.getKind()) {
8081 case lltok::kw_funcFlags:
8082 if (ParseOptionalFFlags(FFlags))
8083 return true;
8084 break;
8085 case lltok::kw_calls:
8086 if (ParseOptionalCalls(Calls))
8087 return true;
8088 break;
8089 case lltok::kw_typeIdInfo:
8090 if (ParseOptionalTypeIdInfo(TypeIdInfo))
8091 return true;
8092 break;
8093 case lltok::kw_refs:
8094 if (ParseOptionalRefs(Refs))
8095 return true;
8096 break;
8097 default:
8098 return Error(Lex.getLoc(), "expected optional function summary field");
8099 }
8100 }
8101
8102 if (ParseToken(lltok::rparen, "expected ')' here"))
8103 return true;
8104
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00008105 auto FS = std::make_unique<FunctionSummary>(
Easwaran Raman5a7056f2018-12-13 19:54:27 +00008106 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8107 std::move(Calls), std::move(TypeIdInfo.TypeTests),
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008108 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8109 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8110 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8111 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
8112
8113 FS->setModulePath(ModulePath);
8114
8115 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8116 ID, std::move(FS));
8117
8118 return false;
8119}
8120
8121/// VariableSummary
8122/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8123/// [',' OptionalRefs]? ')'
8124bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8125 unsigned ID) {
8126 assert(Lex.getKind() == lltok::kw_variable);
8127 Lex.Lex();
8128
8129 StringRef ModulePath;
8130 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8131 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
Teresa Johnson37b80122019-05-10 20:08:24 +00008132 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
Eugene Leviant3aef3522019-07-05 15:25:05 +00008133 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8134 /* WriteOnly */ false);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008135 std::vector<ValueInfo> Refs;
Teresa Johnsona7004362019-07-02 19:38:02 +00008136 VTableFuncList VTableFuncs;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008137 if (ParseToken(lltok::colon, "expected ':' here") ||
8138 ParseToken(lltok::lparen, "expected '(' here") ||
8139 ParseModuleReference(ModulePath) ||
Eugene Leviant009d8332018-11-23 10:54:51 +00008140 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8141 ParseToken(lltok::comma, "expected ',' here") ||
8142 ParseGVarFlags(GVarFlags))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008143 return true;
8144
Teresa Johnsona7004362019-07-02 19:38:02 +00008145 // Parse optional fields
8146 while (EatIfPresent(lltok::comma)) {
8147 switch (Lex.getKind()) {
8148 case lltok::kw_vTableFuncs:
8149 if (ParseOptionalVTableFuncs(VTableFuncs))
8150 return true;
8151 break;
8152 case lltok::kw_refs:
8153 if (ParseOptionalRefs(Refs))
8154 return true;
8155 break;
8156 default:
8157 return Error(Lex.getLoc(), "expected optional variable summary field");
8158 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008159 }
8160
8161 if (ParseToken(lltok::rparen, "expected ')' here"))
8162 return true;
8163
Eugene Leviant009d8332018-11-23 10:54:51 +00008164 auto GS =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00008165 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008166
8167 GS->setModulePath(ModulePath);
Teresa Johnsona7004362019-07-02 19:38:02 +00008168 GS->setVTableFuncs(std::move(VTableFuncs));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008169
8170 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8171 ID, std::move(GS));
8172
8173 return false;
8174}
8175
8176/// AliasSummary
8177/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8178/// 'aliasee' ':' GVReference ')'
8179bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8180 unsigned ID) {
8181 assert(Lex.getKind() == lltok::kw_alias);
8182 LocTy Loc = Lex.getLoc();
8183 Lex.Lex();
8184
8185 StringRef ModulePath;
8186 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8187 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
Teresa Johnson37b80122019-05-10 20:08:24 +00008188 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008189 if (ParseToken(lltok::colon, "expected ':' here") ||
8190 ParseToken(lltok::lparen, "expected '(' here") ||
8191 ParseModuleReference(ModulePath) ||
8192 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8193 ParseToken(lltok::comma, "expected ',' here") ||
8194 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8195 ParseToken(lltok::colon, "expected ':' here"))
8196 return true;
8197
8198 ValueInfo AliaseeVI;
8199 unsigned GVId;
8200 if (ParseGVReference(AliaseeVI, GVId))
8201 return true;
8202
8203 if (ParseToken(lltok::rparen, "expected ')' here"))
8204 return true;
8205
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00008206 auto AS = std::make_unique<AliasSummary>(GVFlags);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008207
8208 AS->setModulePath(ModulePath);
8209
8210 // Record forward reference if the aliasee is not parsed yet.
Eugene Leviant009d8332018-11-23 10:54:51 +00008211 if (AliaseeVI.getRef() == FwdVIRef) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008212 auto FwdRef = ForwardRefAliasees.insert(
8213 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
8214 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
Teresa Johnson70ec64c2019-03-15 15:11:38 +00008215 } else {
8216 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8217 assert(Summary && "Aliasee must be a definition");
8218 AS->setAliasee(AliaseeVI, Summary);
8219 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008220
8221 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8222 ID, std::move(AS));
8223
8224 return false;
8225}
8226
8227/// Flag
8228/// ::= [0|1]
8229bool LLParser::ParseFlag(unsigned &Val) {
8230 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8231 return TokError("expected integer");
8232 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8233 Lex.Lex();
8234 return false;
8235}
8236
8237/// OptionalFFlags
8238/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8239/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8240/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
Teresa Johnsoncb397462018-11-06 19:41:35 +00008241/// [',' 'noInline' ':' Flag]? ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008242bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8243 assert(Lex.getKind() == lltok::kw_funcFlags);
8244 Lex.Lex();
8245
8246 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
8247 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
8248 return true;
8249
8250 do {
Simon Pilgrim46d96c02019-05-11 11:08:24 +00008251 unsigned Val = 0;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008252 switch (Lex.getKind()) {
8253 case lltok::kw_readNone:
8254 Lex.Lex();
8255 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8256 return true;
8257 FFlags.ReadNone = Val;
8258 break;
8259 case lltok::kw_readOnly:
8260 Lex.Lex();
8261 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8262 return true;
8263 FFlags.ReadOnly = Val;
8264 break;
8265 case lltok::kw_noRecurse:
8266 Lex.Lex();
8267 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8268 return true;
8269 FFlags.NoRecurse = Val;
8270 break;
8271 case lltok::kw_returnDoesNotAlias:
8272 Lex.Lex();
8273 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8274 return true;
8275 FFlags.ReturnDoesNotAlias = Val;
8276 break;
Teresa Johnsoncb397462018-11-06 19:41:35 +00008277 case lltok::kw_noInline:
8278 Lex.Lex();
8279 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8280 return true;
8281 FFlags.NoInline = Val;
8282 break;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008283 default:
8284 return Error(Lex.getLoc(), "expected function flag type");
8285 }
8286 } while (EatIfPresent(lltok::comma));
8287
8288 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8289 return true;
8290
8291 return false;
8292}
8293
8294/// OptionalCalls
8295/// := 'calls' ':' '(' Call [',' Call]* ')'
8296/// Call ::= '(' 'callee' ':' GVReference
8297/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8298bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8299 assert(Lex.getKind() == lltok::kw_calls);
8300 Lex.Lex();
8301
8302 if (ParseToken(lltok::colon, "expected ':' in calls") |
8303 ParseToken(lltok::lparen, "expected '(' in calls"))
8304 return true;
8305
8306 IdToIndexMapType IdToIndexMap;
8307 // Parse each call edge
8308 do {
8309 ValueInfo VI;
8310 if (ParseToken(lltok::lparen, "expected '(' in call") ||
8311 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8312 ParseToken(lltok::colon, "expected ':'"))
8313 return true;
8314
8315 LocTy Loc = Lex.getLoc();
8316 unsigned GVId;
8317 if (ParseGVReference(VI, GVId))
8318 return true;
8319
8320 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8321 unsigned RelBF = 0;
8322 if (EatIfPresent(lltok::comma)) {
8323 // Expect either hotness or relbf
8324 if (EatIfPresent(lltok::kw_hotness)) {
8325 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8326 return true;
8327 } else {
8328 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8329 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8330 return true;
8331 }
8332 }
8333 // Keep track of the Call array index needing a forward reference.
8334 // We will save the location of the ValueInfo needing an update, but
8335 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00008336 if (VI.getRef() == FwdVIRef)
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008337 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8338 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8339
8340 if (ParseToken(lltok::rparen, "expected ')' in call"))
8341 return true;
8342 } while (EatIfPresent(lltok::comma));
8343
8344 // Now that the Calls vector is finalized, it is safe to save the locations
8345 // of any forward GV references that need updating later.
8346 for (auto I : IdToIndexMap) {
8347 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008348 assert(Calls[P.first].first.getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008349 "Forward referenced ValueInfo expected to be empty");
8350 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8351 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8352 FwdRef.first->second.push_back(
8353 std::make_pair(&Calls[P.first].first, P.second));
8354 }
8355 }
8356
8357 if (ParseToken(lltok::rparen, "expected ')' in calls"))
8358 return true;
8359
8360 return false;
8361}
8362
8363/// Hotness
8364/// := ('unknown'|'cold'|'none'|'hot'|'critical')
8365bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8366 switch (Lex.getKind()) {
8367 case lltok::kw_unknown:
8368 Hotness = CalleeInfo::HotnessType::Unknown;
8369 break;
8370 case lltok::kw_cold:
8371 Hotness = CalleeInfo::HotnessType::Cold;
8372 break;
8373 case lltok::kw_none:
8374 Hotness = CalleeInfo::HotnessType::None;
8375 break;
8376 case lltok::kw_hot:
8377 Hotness = CalleeInfo::HotnessType::Hot;
8378 break;
8379 case lltok::kw_critical:
8380 Hotness = CalleeInfo::HotnessType::Critical;
8381 break;
8382 default:
8383 return Error(Lex.getLoc(), "invalid call edge hotness");
8384 }
8385 Lex.Lex();
8386 return false;
8387}
8388
Teresa Johnsona7004362019-07-02 19:38:02 +00008389/// OptionalVTableFuncs
8390/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8391/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8392bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8393 assert(Lex.getKind() == lltok::kw_vTableFuncs);
8394 Lex.Lex();
8395
8396 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") |
8397 ParseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8398 return true;
8399
8400 IdToIndexMapType IdToIndexMap;
8401 // Parse each virtual function pair
8402 do {
8403 ValueInfo VI;
8404 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8405 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8406 ParseToken(lltok::colon, "expected ':'"))
8407 return true;
8408
8409 LocTy Loc = Lex.getLoc();
8410 unsigned GVId;
8411 if (ParseGVReference(VI, GVId))
8412 return true;
8413
8414 uint64_t Offset;
8415 if (ParseToken(lltok::comma, "expected comma") ||
8416 ParseToken(lltok::kw_offset, "expected offset") ||
8417 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset))
8418 return true;
8419
8420 // Keep track of the VTableFuncs array index needing a forward reference.
8421 // We will save the location of the ValueInfo needing an update, but
8422 // can only do so once the std::vector is finalized.
8423 if (VI == EmptyVI)
8424 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8425 VTableFuncs.push_back({VI, Offset});
8426
8427 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc"))
8428 return true;
8429 } while (EatIfPresent(lltok::comma));
8430
8431 // Now that the VTableFuncs vector is finalized, it is safe to save the
8432 // locations of any forward GV references that need updating later.
8433 for (auto I : IdToIndexMap) {
8434 for (auto P : I.second) {
8435 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8436 "Forward referenced ValueInfo expected to be empty");
8437 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8438 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8439 FwdRef.first->second.push_back(
8440 std::make_pair(&VTableFuncs[P.first].FuncVI, P.second));
8441 }
8442 }
8443
8444 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8445 return true;
8446
8447 return false;
8448}
8449
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008450/// OptionalRefs
8451/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8452bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8453 assert(Lex.getKind() == lltok::kw_refs);
8454 Lex.Lex();
8455
8456 if (ParseToken(lltok::colon, "expected ':' in refs") |
8457 ParseToken(lltok::lparen, "expected '(' in refs"))
8458 return true;
8459
Eugene Leviant009d8332018-11-23 10:54:51 +00008460 struct ValueContext {
8461 ValueInfo VI;
8462 unsigned GVId;
8463 LocTy Loc;
8464 };
8465 std::vector<ValueContext> VContexts;
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008466 // Parse each ref edge
8467 do {
Eugene Leviant009d8332018-11-23 10:54:51 +00008468 ValueContext VC;
8469 VC.Loc = Lex.getLoc();
8470 if (ParseGVReference(VC.VI, VC.GVId))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008471 return true;
Eugene Leviant009d8332018-11-23 10:54:51 +00008472 VContexts.push_back(VC);
8473 } while (EatIfPresent(lltok::comma));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008474
Eugene Leviant3aef3522019-07-05 15:25:05 +00008475 // Sort value contexts so that ones with writeonly
8476 // and readonly ValueInfo are at the end of VContexts vector.
8477 // See FunctionSummary::specialRefCounts()
Eugene Leviant972e3482018-11-23 11:28:58 +00008478 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
Eugene Leviant3aef3522019-07-05 15:25:05 +00008479 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
Eugene Leviant009d8332018-11-23 10:54:51 +00008480 });
8481
8482 IdToIndexMapType IdToIndexMap;
8483 for (auto &VC : VContexts) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008484 // Keep track of the Refs array index needing a forward reference.
8485 // We will save the location of the ValueInfo needing an update, but
8486 // can only do so once the std::vector is finalized.
Eugene Leviant009d8332018-11-23 10:54:51 +00008487 if (VC.VI.getRef() == FwdVIRef)
8488 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8489 Refs.push_back(VC.VI);
8490 }
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008491
8492 // Now that the Refs vector is finalized, it is safe to save the locations
8493 // of any forward GV references that need updating later.
8494 for (auto I : IdToIndexMap) {
8495 for (auto P : I.second) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008496 assert(Refs[P.first].getRef() == FwdVIRef &&
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008497 "Forward referenced ValueInfo expected to be empty");
8498 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8499 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8500 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8501 }
8502 }
8503
8504 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8505 return true;
8506
8507 return false;
8508}
8509
8510/// OptionalTypeIdInfo
8511/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8512/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8513/// [',' TypeCheckedLoadConstVCalls]? ')'
8514bool LLParser::ParseOptionalTypeIdInfo(
8515 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8516 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8517 Lex.Lex();
8518
8519 if (ParseToken(lltok::colon, "expected ':' here") ||
8520 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8521 return true;
8522
8523 do {
8524 switch (Lex.getKind()) {
8525 case lltok::kw_typeTests:
8526 if (ParseTypeTests(TypeIdInfo.TypeTests))
8527 return true;
8528 break;
8529 case lltok::kw_typeTestAssumeVCalls:
8530 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8531 TypeIdInfo.TypeTestAssumeVCalls))
8532 return true;
8533 break;
8534 case lltok::kw_typeCheckedLoadVCalls:
8535 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8536 TypeIdInfo.TypeCheckedLoadVCalls))
8537 return true;
8538 break;
8539 case lltok::kw_typeTestAssumeConstVCalls:
8540 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8541 TypeIdInfo.TypeTestAssumeConstVCalls))
8542 return true;
8543 break;
8544 case lltok::kw_typeCheckedLoadConstVCalls:
8545 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8546 TypeIdInfo.TypeCheckedLoadConstVCalls))
8547 return true;
8548 break;
8549 default:
8550 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8551 }
8552 } while (EatIfPresent(lltok::comma));
8553
8554 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8555 return true;
8556
8557 return false;
8558}
8559
8560/// TypeTests
8561/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8562/// [',' (SummaryID | UInt64)]* ')'
8563bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8564 assert(Lex.getKind() == lltok::kw_typeTests);
8565 Lex.Lex();
8566
8567 if (ParseToken(lltok::colon, "expected ':' here") ||
8568 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8569 return true;
8570
8571 IdToIndexMapType IdToIndexMap;
8572 do {
8573 GlobalValue::GUID GUID = 0;
8574 if (Lex.getKind() == lltok::SummaryID) {
8575 unsigned ID = Lex.getUIntVal();
8576 LocTy Loc = Lex.getLoc();
8577 // Keep track of the TypeTests array index needing a forward reference.
8578 // We will save the location of the GUID needing an update, but
8579 // can only do so once the std::vector is finalized.
8580 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8581 Lex.Lex();
8582 } else if (ParseUInt64(GUID))
8583 return true;
8584 TypeTests.push_back(GUID);
8585 } while (EatIfPresent(lltok::comma));
8586
8587 // Now that the TypeTests vector is finalized, it is safe to save the
8588 // locations of any forward GV references that need updating later.
8589 for (auto I : IdToIndexMap) {
8590 for (auto P : I.second) {
8591 assert(TypeTests[P.first] == 0 &&
8592 "Forward referenced type id GUID expected to be 0");
8593 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8594 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8595 FwdRef.first->second.push_back(
8596 std::make_pair(&TypeTests[P.first], P.second));
8597 }
8598 }
8599
8600 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8601 return true;
8602
8603 return false;
8604}
8605
8606/// VFuncIdList
8607/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8608bool LLParser::ParseVFuncIdList(
8609 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8610 assert(Lex.getKind() == Kind);
8611 Lex.Lex();
8612
8613 if (ParseToken(lltok::colon, "expected ':' here") ||
8614 ParseToken(lltok::lparen, "expected '(' here"))
8615 return true;
8616
8617 IdToIndexMapType IdToIndexMap;
8618 do {
8619 FunctionSummary::VFuncId VFuncId;
8620 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8621 return true;
8622 VFuncIdList.push_back(VFuncId);
8623 } while (EatIfPresent(lltok::comma));
8624
8625 if (ParseToken(lltok::rparen, "expected ')' here"))
8626 return true;
8627
8628 // Now that the VFuncIdList vector is finalized, it is safe to save the
8629 // locations of any forward GV references that need updating later.
8630 for (auto I : IdToIndexMap) {
8631 for (auto P : I.second) {
8632 assert(VFuncIdList[P.first].GUID == 0 &&
8633 "Forward referenced type id GUID expected to be 0");
8634 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8635 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8636 FwdRef.first->second.push_back(
8637 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8638 }
8639 }
8640
8641 return false;
8642}
8643
8644/// ConstVCallList
8645/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8646bool LLParser::ParseConstVCallList(
8647 lltok::Kind Kind,
8648 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8649 assert(Lex.getKind() == Kind);
8650 Lex.Lex();
8651
8652 if (ParseToken(lltok::colon, "expected ':' here") ||
8653 ParseToken(lltok::lparen, "expected '(' here"))
8654 return true;
8655
8656 IdToIndexMapType IdToIndexMap;
8657 do {
8658 FunctionSummary::ConstVCall ConstVCall;
8659 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8660 return true;
8661 ConstVCallList.push_back(ConstVCall);
8662 } while (EatIfPresent(lltok::comma));
8663
8664 if (ParseToken(lltok::rparen, "expected ')' here"))
8665 return true;
8666
8667 // Now that the ConstVCallList vector is finalized, it is safe to save the
8668 // locations of any forward GV references that need updating later.
8669 for (auto I : IdToIndexMap) {
8670 for (auto P : I.second) {
8671 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8672 "Forward referenced type id GUID expected to be 0");
8673 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8674 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8675 FwdRef.first->second.push_back(
8676 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8677 }
8678 }
8679
8680 return false;
8681}
8682
8683/// ConstVCall
Teresa Johnsonc7816802018-08-14 01:49:33 +00008684/// ::= '(' VFuncId ',' Args ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008685bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8686 IdToIndexMapType &IdToIndexMap, unsigned Index) {
Teresa Johnsonc7816802018-08-14 01:49:33 +00008687 if (ParseToken(lltok::lparen, "expected '(' here") ||
8688 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8689 return true;
8690
8691 if (EatIfPresent(lltok::comma))
8692 if (ParseArgs(ConstVCall.Args))
8693 return true;
8694
8695 if (ParseToken(lltok::rparen, "expected ')' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008696 return true;
8697
8698 return false;
8699}
8700
8701/// VFuncId
8702/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8703/// 'offset' ':' UInt64 ')'
8704bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8705 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8706 assert(Lex.getKind() == lltok::kw_vFuncId);
8707 Lex.Lex();
8708
8709 if (ParseToken(lltok::colon, "expected ':' here") ||
8710 ParseToken(lltok::lparen, "expected '(' here"))
8711 return true;
8712
8713 if (Lex.getKind() == lltok::SummaryID) {
8714 VFuncId.GUID = 0;
8715 unsigned ID = Lex.getUIntVal();
8716 LocTy Loc = Lex.getLoc();
8717 // Keep track of the array index needing a forward reference.
8718 // We will save the location of the GUID needing an update, but
8719 // can only do so once the caller's std::vector is finalized.
8720 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8721 Lex.Lex();
8722 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8723 ParseToken(lltok::colon, "expected ':' here") ||
8724 ParseUInt64(VFuncId.GUID))
8725 return true;
8726
8727 if (ParseToken(lltok::comma, "expected ',' here") ||
8728 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8729 ParseToken(lltok::colon, "expected ':' here") ||
8730 ParseUInt64(VFuncId.Offset) ||
8731 ParseToken(lltok::rparen, "expected ')' here"))
8732 return true;
8733
8734 return false;
8735}
8736
8737/// GVFlags
8738/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8739/// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
Teresa Johnson37b80122019-05-10 20:08:24 +00008740/// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008741bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8742 assert(Lex.getKind() == lltok::kw_flags);
8743 Lex.Lex();
8744
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008745 if (ParseToken(lltok::colon, "expected ':' here") ||
Teresa Johnson37b80122019-05-10 20:08:24 +00008746 ParseToken(lltok::lparen, "expected '(' here"))
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008747 return true;
8748
Teresa Johnson37b80122019-05-10 20:08:24 +00008749 do {
Simon Pilgrimd99f9372019-05-27 16:33:15 +00008750 unsigned Flag = 0;
Teresa Johnson37b80122019-05-10 20:08:24 +00008751 switch (Lex.getKind()) {
8752 case lltok::kw_linkage:
8753 Lex.Lex();
8754 if (ParseToken(lltok::colon, "expected ':'"))
8755 return true;
Simon Pilgrime4343682019-05-26 15:08:45 +00008756 bool HasLinkage;
Teresa Johnson37b80122019-05-10 20:08:24 +00008757 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8758 assert(HasLinkage && "Linkage not optional in summary entry");
8759 Lex.Lex();
8760 break;
8761 case lltok::kw_notEligibleToImport:
8762 Lex.Lex();
8763 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8764 return true;
8765 GVFlags.NotEligibleToImport = Flag;
8766 break;
8767 case lltok::kw_live:
8768 Lex.Lex();
8769 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8770 return true;
8771 GVFlags.Live = Flag;
8772 break;
8773 case lltok::kw_dsoLocal:
8774 Lex.Lex();
8775 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8776 return true;
8777 GVFlags.DSOLocal = Flag;
8778 break;
8779 case lltok::kw_canAutoHide:
8780 Lex.Lex();
8781 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8782 return true;
8783 GVFlags.CanAutoHide = Flag;
8784 break;
8785 default:
8786 return Error(Lex.getLoc(), "expected gv flag type");
8787 }
8788 } while (EatIfPresent(lltok::comma));
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008789
8790 if (ParseToken(lltok::rparen, "expected ')' here"))
8791 return true;
8792
8793 return false;
8794}
8795
Eugene Leviant009d8332018-11-23 10:54:51 +00008796/// GVarFlags
Eugene Leviant3aef3522019-07-05 15:25:05 +00008797/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
8798/// ',' 'writeonly' ':' Flag ')'
Eugene Leviant009d8332018-11-23 10:54:51 +00008799bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8800 assert(Lex.getKind() == lltok::kw_varFlags);
8801 Lex.Lex();
8802
Eugene Leviant009d8332018-11-23 10:54:51 +00008803 if (ParseToken(lltok::colon, "expected ':' here") ||
Eugene Leviant3aef3522019-07-05 15:25:05 +00008804 ParseToken(lltok::lparen, "expected '(' here"))
Eugene Leviant009d8332018-11-23 10:54:51 +00008805 return true;
8806
Eugene Leviant3aef3522019-07-05 15:25:05 +00008807 auto ParseRest = [this](unsigned int &Val) {
8808 Lex.Lex();
8809 if (ParseToken(lltok::colon, "expected ':'"))
8810 return true;
8811 return ParseFlag(Val);
8812 };
Eugene Leviant009d8332018-11-23 10:54:51 +00008813
Eugene Leviant3aef3522019-07-05 15:25:05 +00008814 do {
8815 unsigned Flag = 0;
8816 switch (Lex.getKind()) {
8817 case lltok::kw_readonly:
8818 if (ParseRest(Flag))
8819 return true;
8820 GVarFlags.MaybeReadOnly = Flag;
8821 break;
8822 case lltok::kw_writeonly:
8823 if (ParseRest(Flag))
8824 return true;
8825 GVarFlags.MaybeWriteOnly = Flag;
8826 break;
8827 default:
8828 return Error(Lex.getLoc(), "expected gvar flag type");
8829 }
8830 } while (EatIfPresent(lltok::comma));
8831 return ParseToken(lltok::rparen, "expected ')' here");
Eugene Leviant009d8332018-11-23 10:54:51 +00008832}
8833
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008834/// ModuleReference
8835/// ::= 'module' ':' UInt
8836bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8837 // Parse module id.
8838 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8839 ParseToken(lltok::colon, "expected ':' here") ||
8840 ParseToken(lltok::SummaryID, "expected module ID"))
8841 return true;
8842
8843 unsigned ModuleID = Lex.getUIntVal();
8844 auto I = ModuleIdMap.find(ModuleID);
8845 // We should have already parsed all module IDs
8846 assert(I != ModuleIdMap.end());
8847 ModulePath = I->second;
8848 return false;
8849}
8850
8851/// GVReference
8852/// ::= SummaryID
8853bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
Eugene Leviant3aef3522019-07-05 15:25:05 +00008854 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
8855 if (!ReadOnly)
8856 WriteOnly = EatIfPresent(lltok::kw_writeonly);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008857 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8858 return true;
8859
8860 GVId = Lex.getUIntVal();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008861 // Check if we already have a VI for this GV
8862 if (GVId < NumberedValueInfos.size()) {
Eugene Leviant009d8332018-11-23 10:54:51 +00008863 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008864 VI = NumberedValueInfos[GVId];
8865 } else
8866 // We will create a forward reference to the stored location.
Eugene Leviant009d8332018-11-23 10:54:51 +00008867 VI = ValueInfo(false, FwdVIRef);
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008868
Eugene Leviant009d8332018-11-23 10:54:51 +00008869 if (ReadOnly)
8870 VI.setReadOnly();
Eugene Leviant3aef3522019-07-05 15:25:05 +00008871 if (WriteOnly)
8872 VI.setWriteOnly();
Teresa Johnson63ee0e72018-06-26 13:56:49 +00008873 return false;
8874}