blob: 0d478d4090b69294713043ab633e35feb932b584 [file] [log] [blame]
Chris Lattnerac161bf2009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallPtrSet.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000023#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalIFunc.h"
32#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000036#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000037#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000133 AttributeList AS = Fn->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
Javed Absarf3d79042017-05-11 12:28:08 +0000165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
167 Attrs.merge(B);
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 } else {
170 llvm_unreachable("invalid object with forward attribute group reference");
171 }
172 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000173
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000179
David Majnemer19b51052015-02-11 07:43:56 +0000180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000184
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000190
David Majnemerdad0a642014-06-27 18:19:56 +0000191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
195
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
199 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000204 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Devang Pateld2541152009-07-08 19:23:54 +0000206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
215 }
Devang Pateld2541152009-07-08 19:23:54 +0000216
Mehdi Aminie4709272016-09-14 22:29:59 +0000217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
223 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000224
Chris Lattnerac161bf2009-01-02 07:01:27 +0000225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000228
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
237 }
238 }
239
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000240 if (UpgradeDebugInfo)
241 llvm::UpgradeDebugInfo(*M);
Manman Ren8b4306c2013-12-02 21:29:56 +0000242
Manman Renb5d7ff42016-05-25 23:14:48 +0000243 UpgradeModuleFlags(*M);
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000244 UpgradeSectionAttributes(*M);
Manman Renb5d7ff42016-05-25 23:14:48 +0000245
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000246 if (!Slots)
247 return false;
248 // Initialize the slot mapping.
249 // Because by this point we've parsed and validated everything, we can "steal"
250 // the mapping from LLParser as it doesn't need it anymore.
251 Slots->GlobalValues = std::move(NumberedVals);
252 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000253 for (const auto &I : NamedTypes)
254 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
255 for (const auto &I : NumberedTypes)
256 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000257
Chris Lattnerac161bf2009-01-02 07:01:27 +0000258 return false;
259}
260
261//===----------------------------------------------------------------------===//
262// Top-Level Entities
263//===----------------------------------------------------------------------===//
264
265bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000266 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000267 switch (Lex.getKind()) {
268 default: return TokError("expected top-level entity");
269 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 case lltok::kw_declare: if (ParseDeclare()) return true; break;
271 case lltok::kw_define: if (ParseDefine()) return true; break;
272 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
273 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000274 case lltok::kw_source_filename:
275 if (ParseSourceFileName())
276 return true;
277 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000278 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000279 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000280 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000281 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000282 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000283 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000284 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000285 case lltok::SummaryID:
286 if (ParseSummaryEntry())
287 return true;
288 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000289 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000290 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000291 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
292 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000293 if (ParseUseListOrderBB())
294 return true;
295 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296 }
297 }
298}
299
Chris Lattnerac161bf2009-01-02 07:01:27 +0000300/// toplevelentity
301/// ::= 'module' 'asm' STRINGCONSTANT
302bool LLParser::ParseModuleAsm() {
303 assert(Lex.getKind() == lltok::kw_module);
304 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000305
306 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000307 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
308 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000309
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000310 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000311 return false;
312}
313
314/// toplevelentity
315/// ::= 'target' 'triple' '=' STRINGCONSTANT
316/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
317bool LLParser::ParseTargetDefinition() {
318 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000319 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 switch (Lex.Lex()) {
321 default: return TokError("unknown target property");
322 case lltok::kw_triple:
323 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000324 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
325 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000326 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000327 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328 return false;
329 case lltok::kw_datalayout:
330 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000331 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
332 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000333 return true;
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000334 if (DataLayoutStr.empty())
335 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000336 return false;
337 }
338}
339
Bill Wendling706d3d62012-11-28 08:41:48 +0000340/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000341/// ::= 'source_filename' '=' STRINGCONSTANT
342bool LLParser::ParseSourceFileName() {
343 assert(Lex.getKind() == lltok::kw_source_filename);
344 std::string Str;
345 Lex.Lex();
346 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
347 ParseStringConstant(Str))
348 return true;
349 M->setSourceFileName(Str);
350 return false;
351}
352
353/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000354/// ::= 'deplibs' '=' '[' ']'
355/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
356/// FIXME: Remove in 4.0. Currently parse, but ignore.
357bool LLParser::ParseDepLibs() {
358 assert(Lex.getKind() == lltok::kw_deplibs);
359 Lex.Lex();
360 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
361 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
362 return true;
363
364 if (EatIfPresent(lltok::rsquare))
365 return false;
366
367 do {
368 std::string Str;
369 if (ParseStringConstant(Str)) return true;
370 } while (EatIfPresent(lltok::comma));
371
372 return ParseToken(lltok::rsquare, "expected ']' at end of list");
373}
374
Dan Gohman466876b2009-08-12 23:32:33 +0000375/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000376/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000378 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000380 Lex.Lex(); // eat LocalVarID;
381
382 if (ParseToken(lltok::equal, "expected '=' after name") ||
383 ParseToken(lltok::kw_type, "expected 'type' after '='"))
384 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385
Craig Topper2617dcc2014-04-15 06:32:26 +0000386 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000387 if (ParseStructDefinition(TypeLoc, "",
388 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000389
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000390 if (!isa<StructType>(Result)) {
391 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
392 if (Entry.first)
393 return Error(TypeLoc, "non-struct types may not be recursive");
394 Entry.first = Result;
395 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000396 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000397
Chris Lattnerac161bf2009-01-02 07:01:27 +0000398 return false;
399}
400
401/// toplevelentity
402/// ::= LocalVar '=' 'type' type
403bool LLParser::ParseNamedType() {
404 std::string Name = Lex.getStrVal();
405 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000406 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000407
Chris Lattner3822f632009-01-02 08:05:26 +0000408 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000410 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000411
Craig Topper2617dcc2014-04-15 06:32:26 +0000412 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000413 if (ParseStructDefinition(NameLoc, Name,
414 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000415
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416 if (!isa<StructType>(Result)) {
417 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
418 if (Entry.first)
419 return Error(NameLoc, "non-struct types may not be recursive");
420 Entry.first = Result;
421 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000424 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425}
426
Chris Lattnerac161bf2009-01-02 07:01:27 +0000427/// toplevelentity
428/// ::= 'declare' FunctionHeader
429bool LLParser::ParseDeclare() {
430 assert(Lex.getKind() == lltok::kw_declare);
431 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000432
Peter Collingbourne21521892016-06-21 23:42:48 +0000433 std::vector<std::pair<unsigned, MDNode *>> MDs;
434 while (Lex.getKind() == lltok::MetadataVar) {
435 unsigned MDK;
436 MDNode *N;
437 if (ParseMetadataAttachment(MDK, N))
438 return true;
439 MDs.push_back({MDK, N});
440 }
441
Chris Lattnerac161bf2009-01-02 07:01:27 +0000442 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000443 if (ParseFunctionHeader(F, false))
444 return true;
445 for (auto &MD : MDs)
446 F->addMetadata(MD.first, *MD.second);
447 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448}
449
450/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000451/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452bool LLParser::ParseDefine() {
453 assert(Lex.getKind() == lltok::kw_define);
454 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000455
Chris Lattnerac161bf2009-01-02 07:01:27 +0000456 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000457 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000458 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000459 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000460}
461
Chris Lattner3822f632009-01-02 08:05:26 +0000462/// ParseGlobalType
463/// ::= 'constant'
464/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465bool LLParser::ParseGlobalType(bool &IsConstant) {
466 if (Lex.getKind() == lltok::kw_constant)
467 IsConstant = true;
468 else if (Lex.getKind() == lltok::kw_global)
469 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000470 else {
471 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000473 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000474 Lex.Lex();
475 return false;
476}
477
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000478bool LLParser::ParseOptionalUnnamedAddr(
479 GlobalVariable::UnnamedAddr &UnnamedAddr) {
480 if (EatIfPresent(lltok::kw_unnamed_addr))
481 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
482 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
483 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
484 else
485 UnnamedAddr = GlobalValue::UnnamedAddr::None;
486 return false;
487}
488
Dan Gohman466876b2009-08-12 23:32:33 +0000489/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000490/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000491/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
492/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000493/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000494/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000495/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
496/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000497/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000498bool LLParser::ParseUnnamedGlobal() {
499 unsigned VarID = NumberedVals.size();
500 std::string Name;
501 LocTy NameLoc = Lex.getLoc();
502
503 // Handle the GlobalID form.
504 if (Lex.getKind() == lltok::GlobalID) {
505 if (Lex.getUIntVal() != VarID)
506 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000507 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000508 Lex.Lex(); // eat GlobalID;
509
510 if (ParseToken(lltok::equal, "expected '=' after name"))
511 return true;
512 }
513
514 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000515 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000516 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000517 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000518 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000519 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
520 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000521 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000522 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000523
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000524 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000525 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000526 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000527
528 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000529 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000530}
531
Chris Lattnerac161bf2009-01-02 07:01:27 +0000532/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000533/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000534/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
535/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000536/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000537bool LLParser::ParseNamedGlobal() {
538 assert(Lex.getKind() == lltok::GlobalVar);
539 LocTy NameLoc = Lex.getLoc();
540 std::string Name = Lex.getStrVal();
541 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542
Chris Lattnerac161bf2009-01-02 07:01:27 +0000543 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000544 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000545 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000546 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000547 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000548 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000549 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
550 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000551 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000552 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000553
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000554 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000555 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000556 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000557
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000558 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000559 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000560}
561
David Majnemerdad0a642014-06-27 18:19:56 +0000562bool LLParser::parseComdat() {
563 assert(Lex.getKind() == lltok::ComdatVar);
564 std::string Name = Lex.getStrVal();
565 LocTy NameLoc = Lex.getLoc();
566 Lex.Lex();
567
568 if (ParseToken(lltok::equal, "expected '=' here"))
569 return true;
570
571 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
572 return TokError("expected comdat type");
573
574 Comdat::SelectionKind SK;
575 switch (Lex.getKind()) {
576 default:
577 return TokError("unknown selection kind");
578 case lltok::kw_any:
579 SK = Comdat::Any;
580 break;
581 case lltok::kw_exactmatch:
582 SK = Comdat::ExactMatch;
583 break;
584 case lltok::kw_largest:
585 SK = Comdat::Largest;
586 break;
587 case lltok::kw_noduplicates:
588 SK = Comdat::NoDuplicates;
589 break;
590 case lltok::kw_samesize:
591 SK = Comdat::SameSize;
592 break;
593 }
594 Lex.Lex();
595
596 // See if the comdat was forward referenced, if so, use the comdat.
597 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
598 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
599 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
600 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
601
602 Comdat *C;
603 if (I != ComdatSymTab.end())
604 C = &I->second;
605 else
606 C = M->getOrInsertComdat(Name);
607 C->setSelectionKind(SK);
608
609 return false;
610}
611
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612// MDString:
613// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000614bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 std::string Str;
616 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000617 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000618 return false;
619}
620
621// MDNode:
622// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000623bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000624 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000625 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000626 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000627 if (ParseUInt32(MID))
628 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000629
Chris Lattner8eff0152010-04-01 05:14:45 +0000630 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000631 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000632 Result = NumberedMetadata[MID];
633 return false;
634 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000635
Chris Lattner8eff0152010-04-01 05:14:45 +0000636 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000637 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000638 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000639
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000640 Result = FwdRef.first.get();
641 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000642 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000643}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000644
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000645/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000646/// !foo = !{ !1, !2 }
647bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000648 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000649 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000650 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000651
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000652 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000653 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000654 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000655 return true;
656
Dan Gohman2637cc12010-07-21 23:38:33 +0000657 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000658 if (Lex.getKind() != lltok::rbrace)
659 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000660 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000661 // Parse DIExpressions inline as a special case. They are still MDNodes,
662 // so they can still appear in named metadata. Remove this logic if they
663 // become plain Metadata.
664 if (Lex.getKind() == lltok::MetadataVar &&
665 Lex.getStrVal() == "DIExpression") {
666 if (ParseDIExpression(N, /*IsDistinct=*/false))
667 return true;
668 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
669 ParseMDNodeID(N)) {
670 return true;
671 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000672 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000673 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000674
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000675 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000676}
677
Devang Patel39e64d42009-07-01 19:21:12 +0000678/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000679/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000680bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000681 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000682 Lex.Lex();
683 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000684
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000685 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000686 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000687 ParseToken(lltok::equal, "expected '=' here"))
688 return true;
689
690 // Detect common error, from old metadata syntax.
691 if (Lex.getKind() == lltok::Type)
692 return TokError("unexpected type in metadata definition");
693
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000694 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000695 if (Lex.getKind() == lltok::MetadataVar) {
696 if (ParseSpecializedMDNode(Init, IsDistinct))
697 return true;
698 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
699 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000700 return true;
701
Chris Lattnerfc58af22009-12-30 04:51:58 +0000702 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000703 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000704 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000705 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000706 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000707
Chris Lattnerfc58af22009-12-30 04:51:58 +0000708 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
709 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000710 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000711 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000712 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000713 }
714
Devang Patel39e64d42009-07-01 19:21:12 +0000715 return false;
716}
717
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000718// Skips a single module summary entry.
719bool LLParser::SkipModuleSummaryEntry() {
720 // Each module summary entry consists of a tag for the entry
721 // type, followed by a colon, then the fields surrounded by nested sets of
722 // parentheses. The "tag:" looks like a Label. Once parsing support is
723 // in place we will look for the tokens corresponding to the expected tags.
724 if (ParseToken(lltok::LabelStr,
725 "expected 'label' at start of summary entry") ||
726 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
727 return true;
728 // Now walk through the parenthesized entry, until the number of open
729 // parentheses goes back down to 0 (the first '(' was parsed above).
730 unsigned NumOpenParen = 1;
731 do {
732 switch (Lex.getKind()) {
733 case lltok::lparen:
734 NumOpenParen++;
735 break;
736 case lltok::rparen:
737 NumOpenParen--;
738 break;
739 case lltok::Eof:
740 return TokError("found end of file while parsing summary entry");
741 default:
742 // Skip everything in between parentheses.
743 break;
744 }
745 Lex.Lex();
746 } while (NumOpenParen > 0);
747 return false;
748}
749
750/// ParseSummaryEntry:
751/// ::= SummaryID '=' ...
752bool LLParser::ParseSummaryEntry() {
753 assert(Lex.getKind() == lltok::SummaryID);
754 // unsigned SummaryID = Lex.getUIntVal();
755
756 Lex.Lex();
757 if (ParseToken(lltok::equal, "expected '=' here"))
758 return true;
759
760 // TODO: Support parsing into a ModuleSummaryIndex object saved in
761 // the LLParser. For now, skip the summary entry.
762 if (SkipModuleSummaryEntry())
763 return true;
764 return false;
765}
766
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000767static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
768 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
769 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
770}
771
Rafael Espindolae4b02312018-01-11 22:15:05 +0000772// If there was an explicit dso_local, update GV. In the absence of an explicit
773// dso_local we keep the default value.
774static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
775 if (DSOLocal)
776 GV.setDSOLocal(true);
777}
778
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000779/// parseIndirectSymbol:
Sean Fertilec70d28b2017-10-26 15:00:26 +0000780/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
781/// OptionalVisibility OptionalDLLStorageClass
782/// OptionalThreadLocal OptionalUnnamedAddr
783// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000784///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000785/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000786/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000787///
Eric Christopher536f0a92015-05-28 23:07:39 +0000788/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000790bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
791 unsigned L, unsigned Visibility,
792 unsigned DLLStorageClass, bool DSOLocal,
793 GlobalVariable::ThreadLocalMode TLM,
794 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000795 bool IsAlias;
796 if (Lex.getKind() == lltok::kw_alias)
797 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000798 else if (Lex.getKind() == lltok::kw_ifunc)
799 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000800 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000801 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000802 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000803
Rafael Espindola78527052013-10-06 15:10:43 +0000804 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
805
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000806 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000807 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000809 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000810 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000811 "symbol with local linkage must have default visibility");
812
David Blaikie2f408302015-09-11 03:22:04 +0000813 Type *Ty;
814 LocTy ExplicitTypeLoc = Lex.getLoc();
815 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000816 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000817 return true;
818
Rafael Espindola64c1e182014-06-03 02:41:57 +0000819 Constant *Aliasee;
820 LocTy AliaseeLoc = Lex.getLoc();
821 if (Lex.getKind() != lltok::kw_bitcast &&
822 Lex.getKind() != lltok::kw_getelementptr &&
823 Lex.getKind() != lltok::kw_addrspacecast &&
824 Lex.getKind() != lltok::kw_inttoptr) {
825 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000826 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000828 // The bitcast dest type is not present, it is implied by the dest type.
829 ValID ID;
830 if (ParseValID(ID))
831 return true;
832 if (ID.Kind != ValID::t_Constant)
833 return Error(AliaseeLoc, "invalid aliasee");
834 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000836
Rafael Espindola64c1e182014-06-03 02:41:57 +0000837 Type *AliaseeType = Aliasee->getType();
838 auto *PTy = dyn_cast<PointerType>(AliaseeType);
839 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000840 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000841 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000843 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000844 return Error(
845 ExplicitTypeLoc,
846 "explicit pointee type doesn't match operand's pointee type");
847
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000848 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
849 return Error(
850 ExplicitTypeLoc,
851 "explicit pointee type should be a function type");
852
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000853 GlobalValue *GVal = nullptr;
854
855 // See if the alias was forward referenced, if so, prepare to replace the
856 // forward reference.
857 if (!Name.empty()) {
858 GVal = M->getNamedValue(Name);
859 if (GVal) {
860 if (!ForwardRefVals.erase(Name))
861 return Error(NameLoc, "redefinition of global '@" + Name + "'");
862 }
863 } else {
864 auto I = ForwardRefValIDs.find(NumberedVals.size());
865 if (I != ForwardRefValIDs.end()) {
866 GVal = I->second.first;
867 ForwardRefValIDs.erase(I);
868 }
869 }
870
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000872 std::unique_ptr<GlobalIndirectSymbol> GA;
873 if (IsAlias)
874 GA.reset(GlobalAlias::create(Ty, AddrSpace,
875 (GlobalValue::LinkageTypes)Linkage, Name,
876 Aliasee, /*Parent*/ nullptr));
877 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000878 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
879 (GlobalValue::LinkageTypes)Linkage, Name,
880 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000881 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000882 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000883 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000884 GA->setUnnamedAddr(UnnamedAddr);
Rafael Espindolae4b02312018-01-11 22:15:05 +0000885 maybeSetDSOLocal(DSOLocal, *GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000886
Rafael Espindola54fc2982015-06-17 17:53:31 +0000887 if (Name.empty())
888 NumberedVals.push_back(GA.get());
889
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000890 if (GVal) {
891 // Verify that types agree.
892 if (GVal->getType() != GA->getType())
893 return Error(
894 ExplicitTypeLoc,
895 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000896
Chris Lattnerac161bf2009-01-02 07:01:27 +0000897 // If they agree, just RAUW the old value with the alias and remove the
898 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000899 GVal->replaceAllUsesWith(GA.get());
900 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000902
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000904 if (IsAlias)
905 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
906 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000907 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000908 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000909
Rafael Espindolaaa273822014-05-09 21:49:17 +0000910 // The module owns this now
911 GA.release();
912
Chris Lattnerac161bf2009-01-02 07:01:27 +0000913 return false;
914}
915
916/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000917/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
918/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000919/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000920/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000921/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
922/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
923/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
924/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000925///
Eric Christopher536f0a92015-05-28 23:07:39 +0000926/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000927/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000928///
929bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
930 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000931 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000932 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000933 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000934 if (!isValidVisibilityForLinkage(Visibility, Linkage))
935 return Error(NameLoc,
936 "symbol with local linkage must have default visibility");
937
Chris Lattnerac161bf2009-01-02 07:01:27 +0000938 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000939 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000940 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000941 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000942
Craig Topper2617dcc2014-04-15 06:32:26 +0000943 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000944 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000945 ParseOptionalToken(lltok::kw_externally_initialized,
946 IsExternallyInitialized,
947 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000948 ParseGlobalType(IsConstant) ||
949 ParseType(Ty, TyLoc))
950 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Chris Lattnerac161bf2009-01-02 07:01:27 +0000952 // If the linkage is specified and is external, then no initializer is
953 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000954 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000955 if (!HasLinkage ||
956 !GlobalValue::isValidDeclarationLinkage(
957 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000958 if (ParseGlobalValue(Ty, Init))
959 return true;
960 }
961
David Majnemer49b3d9b2015-02-16 08:41:08 +0000962 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000963 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000964
David Majnemer598bd052014-12-09 05:56:09 +0000965 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000966
967 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000968 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000969 GVal = M->getNamedValue(Name);
970 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000971 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000972 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000973 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000974 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000975 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000976 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000977 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000978 ForwardRefValIDs.erase(I);
979 }
980 }
981
David Majnemer598bd052014-12-09 05:56:09 +0000982 GlobalVariable *GV;
983 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000984 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
985 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000986 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000987 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000988 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000989 return Error(TyLoc,
990 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000991
David Majnemer598bd052014-12-09 05:56:09 +0000992 GV = cast<GlobalVariable>(GVal);
993
Chris Lattnerac161bf2009-01-02 07:01:27 +0000994 // Move the forward-reference to the correct spot in the module.
995 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
996 }
997
998 if (Name.empty())
999 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001000
Chris Lattnerac161bf2009-01-02 07:01:27 +00001001 // Set the parsed properties on the global.
1002 if (Init)
1003 GV->setInitializer(Init);
1004 GV->setConstant(IsConstant);
1005 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00001006 maybeSetDSOLocal(DSOLocal, *GV);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001007 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00001008 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001009 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001010 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001011 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001012
Chris Lattnerac161bf2009-01-02 07:01:27 +00001013 // Parse attributes on the global.
1014 while (Lex.getKind() == lltok::comma) {
1015 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001016
Chris Lattnerac161bf2009-01-02 07:01:27 +00001017 if (Lex.getKind() == lltok::kw_section) {
1018 Lex.Lex();
1019 GV->setSection(Lex.getStrVal());
1020 if (ParseToken(lltok::StringConstant, "expected global section string"))
1021 return true;
1022 } else if (Lex.getKind() == lltok::kw_align) {
1023 unsigned Alignment;
1024 if (ParseOptionalAlignment(Alignment)) return true;
1025 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001026 } else if (Lex.getKind() == lltok::MetadataVar) {
1027 if (ParseGlobalObjectMetadataAttachment(*GV))
1028 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 } else {
David Majnemerdad0a642014-06-27 18:19:56 +00001030 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +00001031 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +00001032 return true;
1033 if (C)
1034 GV->setComdat(C);
1035 else
1036 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001037 }
1038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001039
Javed Absarf3d79042017-05-11 12:28:08 +00001040 AttrBuilder Attrs;
1041 LocTy BuiltinLoc;
1042 std::vector<unsigned> FwdRefAttrGrps;
1043 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1044 return true;
1045 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1046 GV->setAttributes(AttributeSet::get(Context, Attrs));
1047 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1048 }
1049
Chris Lattnerac161bf2009-01-02 07:01:27 +00001050 return false;
1051}
1052
Bill Wendling63b88192013-02-06 06:52:58 +00001053/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +00001054/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +00001055bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001056 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001057 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001058 Lex.Lex();
1059
David Majnemerb39e22b2014-12-09 18:33:57 +00001060 if (Lex.getKind() != lltok::AttrGrpID)
1061 return TokError("expected attribute group id");
1062
Bill Wendling63b88192013-02-06 06:52:58 +00001063 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001064 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001065 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001066 Lex.Lex();
1067
1068 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001069 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001070 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001071 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001072 ParseToken(lltok::rbrace, "expected end of attribute group"))
1073 return true;
1074
Bill Wendlingb32b0412013-02-08 06:32:06 +00001075 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001076 return Error(AttrGrpLoc, "attribute group has no attributes");
1077
1078 return false;
1079}
1080
Bill Wendling8b0321d2013-02-08 00:52:31 +00001081/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001082/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001083bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1084 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001085 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001086 bool HaveError = false;
1087
1088 B.clear();
1089
Bill Wendling63b88192013-02-06 06:52:58 +00001090 while (true) {
1091 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001092 if (Token == lltok::kw_builtin)
1093 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001094 switch (Token) {
1095 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001096 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001097 return Error(Lex.getLoc(), "unterminated attribute group");
1098 case lltok::rbrace:
1099 // Finished.
1100 return false;
1101
Bill Wendlingb32b0412013-02-08 06:32:06 +00001102 case lltok::AttrGrpID: {
1103 // Allow a function to reference an attribute group:
1104 //
1105 // define void @foo() #1 { ... }
1106 if (inAttrGrp)
1107 HaveError |=
1108 Error(Lex.getLoc(),
1109 "cannot have an attribute group reference in an attribute group");
1110
1111 unsigned AttrGrpNum = Lex.getUIntVal();
1112 if (inAttrGrp) break;
1113
1114 // Save the reference to the attribute group. We'll fill it in later.
1115 FwdRefAttrGrps.push_back(AttrGrpNum);
1116 break;
1117 }
Bill Wendling63b88192013-02-06 06:52:58 +00001118 // Target-dependent attributes:
1119 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001120 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001121 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001122 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001123 }
1124
1125 // Target-independent attributes:
1126 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001127 // As a hack, we allow function alignment to be initially parsed as an
1128 // attribute on a function declaration/definition or added to an attribute
1129 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001130 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001131 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001132 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001133 if (ParseToken(lltok::equal, "expected '=' here") ||
1134 ParseUInt32(Alignment))
1135 return true;
1136 } else {
1137 if (ParseOptionalAlignment(Alignment))
1138 return true;
1139 }
Bill Wendling63b88192013-02-06 06:52:58 +00001140 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001141 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001142 }
1143 case lltok::kw_alignstack: {
1144 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001145 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001146 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001147 if (ParseToken(lltok::equal, "expected '=' here") ||
1148 ParseUInt32(Alignment))
1149 return true;
1150 } else {
1151 if (ParseOptionalStackAlignment(Alignment))
1152 return true;
1153 }
Bill Wendling63b88192013-02-06 06:52:58 +00001154 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001155 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001156 }
George Burgess IV278199f2016-04-12 01:05:35 +00001157 case lltok::kw_allocsize: {
1158 unsigned ElemSizeArg;
1159 Optional<unsigned> NumElemsArg;
1160 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1161 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1162 return true;
1163 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1164 continue;
1165 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001166 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1167 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1168 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1169 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1170 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001171 case lltok::kw_inaccessiblememonly:
1172 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1173 case lltok::kw_inaccessiblemem_or_argmemonly:
1174 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001175 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1176 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1177 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1178 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1179 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1180 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1181 case lltok::kw_noimplicitfloat:
1182 B.addAttribute(Attribute::NoImplicitFloat); break;
1183 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1184 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1185 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1186 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001187 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001188 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001189 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001190 case lltok::kw_optforfuzzing:
1191 B.addAttribute(Attribute::OptForFuzzing); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001192 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1193 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1194 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1195 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1196 case lltok::kw_returns_twice:
1197 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001198 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001199 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1200 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1201 case lltok::kw_sspstrong:
1202 B.addAttribute(Attribute::StackProtectStrong); break;
1203 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001204 case lltok::kw_shadowcallstack:
1205 B.addAttribute(Attribute::ShadowCallStack); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001206 case lltok::kw_sanitize_address:
1207 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001208 case lltok::kw_sanitize_hwaddress:
1209 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001210 case lltok::kw_sanitize_thread:
1211 B.addAttribute(Attribute::SanitizeThread); break;
1212 case lltok::kw_sanitize_memory:
1213 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001214 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001215 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001216 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001217
1218 // Error handling.
1219 case lltok::kw_inreg:
1220 case lltok::kw_signext:
1221 case lltok::kw_zeroext:
1222 HaveError |=
1223 Error(Lex.getLoc(),
1224 "invalid use of attribute on a function");
1225 break;
1226 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001227 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001228 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001229 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001230 case lltok::kw_nest:
1231 case lltok::kw_noalias:
1232 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001233 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001234 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001235 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001236 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001237 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001238 HaveError |=
1239 Error(Lex.getLoc(),
1240 "invalid use of parameter-only attribute on a function");
1241 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001242 }
1243
1244 Lex.Lex();
1245 }
1246}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001247
1248//===----------------------------------------------------------------------===//
1249// GlobalValue Reference/Resolution Routines.
1250//===----------------------------------------------------------------------===//
1251
Karl Schimpf77729782015-09-03 18:06:44 +00001252static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1253 const std::string &Name) {
1254 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1255 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1256 else
1257 return new GlobalVariable(*M, PTy->getElementType(), false,
1258 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1259 nullptr, GlobalVariable::NotThreadLocal,
1260 PTy->getAddressSpace());
1261}
1262
Chris Lattnerac161bf2009-01-02 07:01:27 +00001263/// GetGlobalVal - Get a value with the specified name or ID, creating a
1264/// forward reference record if needed. This can return null if the value
1265/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001266GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001267 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001268 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001269 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001270 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001271 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001272 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001273
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 // Look this name up in the normal function symbol table.
1275 GlobalValue *Val =
1276 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001277
Chris Lattnerac161bf2009-01-02 07:01:27 +00001278 // If this is a forward reference for the value, see if we already created a
1279 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001280 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001281 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001282 if (I != ForwardRefVals.end())
1283 Val = I->second.first;
1284 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001285
Chris Lattnerac161bf2009-01-02 07:01:27 +00001286 // If we have the value in the symbol table or fwd-ref table, return it.
1287 if (Val) {
1288 if (Val->getType() == Ty) return Val;
1289 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001290 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001291 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001293
Chris Lattnerac161bf2009-01-02 07:01:27 +00001294 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001295 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001296 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1297 return FwdVal;
1298}
1299
Chris Lattner229907c2011-07-18 04:54:35 +00001300GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1301 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001302 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001303 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001304 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001306
Craig Topper2617dcc2014-04-15 06:32:26 +00001307 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001308
Chris Lattnerac161bf2009-01-02 07:01:27 +00001309 // If this is a forward reference for the value, see if we already created a
1310 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001311 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001312 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001313 if (I != ForwardRefValIDs.end())
1314 Val = I->second.first;
1315 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001316
Chris Lattnerac161bf2009-01-02 07:01:27 +00001317 // If we have the value in the symbol table or fwd-ref table, return it.
1318 if (Val) {
1319 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001320 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001321 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001322 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001323 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001324
Chris Lattnerac161bf2009-01-02 07:01:27 +00001325 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001326 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001327 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1328 return FwdVal;
1329}
1330
Chris Lattnerac161bf2009-01-02 07:01:27 +00001331//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001332// Comdat Reference/Resolution Routines.
1333//===----------------------------------------------------------------------===//
1334
1335Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1336 // Look this name up in the comdat symbol table.
1337 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1338 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1339 if (I != ComdatSymTab.end())
1340 return &I->second;
1341
1342 // Otherwise, create a new forward reference for this value and remember it.
1343 Comdat *C = M->getOrInsertComdat(Name);
1344 ForwardRefComdats[Name] = Loc;
1345 return C;
1346}
1347
David Majnemerdad0a642014-06-27 18:19:56 +00001348//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001349// Helper Routines.
1350//===----------------------------------------------------------------------===//
1351
1352/// ParseToken - If the current token has the specified kind, eat it and return
1353/// success. Otherwise, emit the specified error and return failure.
1354bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1355 if (Lex.getKind() != T)
1356 return TokError(ErrMsg);
1357 Lex.Lex();
1358 return false;
1359}
1360
Chris Lattner3822f632009-01-02 08:05:26 +00001361/// ParseStringConstant
1362/// ::= StringConstant
1363bool LLParser::ParseStringConstant(std::string &Result) {
1364 if (Lex.getKind() != lltok::StringConstant)
1365 return TokError("expected string constant");
1366 Result = Lex.getStrVal();
1367 Lex.Lex();
1368 return false;
1369}
1370
1371/// ParseUInt32
1372/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001373bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001374 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1375 return TokError("expected integer");
1376 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1377 if (Val64 != unsigned(Val64))
1378 return TokError("expected 32-bit integer (too large)");
1379 Val = Val64;
1380 Lex.Lex();
1381 return false;
1382}
1383
Hal Finkelb0407ba2014-07-18 15:51:28 +00001384/// ParseUInt64
1385/// ::= uint64
1386bool LLParser::ParseUInt64(uint64_t &Val) {
1387 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1388 return TokError("expected integer");
1389 Val = Lex.getAPSIntVal().getLimitedValue();
1390 Lex.Lex();
1391 return false;
1392}
1393
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001394/// ParseTLSModel
1395/// := 'localdynamic'
1396/// := 'initialexec'
1397/// := 'localexec'
1398bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1399 switch (Lex.getKind()) {
1400 default:
1401 return TokError("expected localdynamic, initialexec or localexec");
1402 case lltok::kw_localdynamic:
1403 TLM = GlobalVariable::LocalDynamicTLSModel;
1404 break;
1405 case lltok::kw_initialexec:
1406 TLM = GlobalVariable::InitialExecTLSModel;
1407 break;
1408 case lltok::kw_localexec:
1409 TLM = GlobalVariable::LocalExecTLSModel;
1410 break;
1411 }
1412
1413 Lex.Lex();
1414 return false;
1415}
1416
1417/// ParseOptionalThreadLocal
1418/// := /*empty*/
1419/// := 'thread_local'
1420/// := 'thread_local' '(' tlsmodel ')'
1421bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1422 TLM = GlobalVariable::NotThreadLocal;
1423 if (!EatIfPresent(lltok::kw_thread_local))
1424 return false;
1425
1426 TLM = GlobalVariable::GeneralDynamicTLSModel;
1427 if (Lex.getKind() == lltok::lparen) {
1428 Lex.Lex();
1429 return ParseTLSModel(TLM) ||
1430 ParseToken(lltok::rparen, "expected ')' after thread local model");
1431 }
1432 return false;
1433}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001434
1435/// ParseOptionalAddrSpace
1436/// := /*empty*/
1437/// := 'addrspace' '(' uint32 ')'
1438bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1439 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001440 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001441 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001442 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001443 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001444 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001445}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001446
Artur Pilipenko17376c42015-08-03 14:31:49 +00001447/// ParseStringAttribute
1448/// := StringConstant
1449/// := StringConstant '=' StringConstant
1450bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1451 std::string Attr = Lex.getStrVal();
1452 Lex.Lex();
1453 std::string Val;
1454 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1455 return true;
1456 B.addAttribute(Attr, Val);
1457 return false;
1458}
1459
Bill Wendling34c2eb22012-12-04 23:40:58 +00001460/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1461bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1462 bool HaveError = false;
1463
1464 B.clear();
1465
Eugene Zelenko1804a772016-08-25 00:45:04 +00001466 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001467 lltok::Kind Token = Lex.getKind();
1468 switch (Token) {
1469 default: // End of attributes.
1470 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001471 case lltok::StringConstant: {
1472 if (ParseStringAttribute(B))
1473 return true;
1474 continue;
1475 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001476 case lltok::kw_align: {
1477 unsigned Alignment;
1478 if (ParseOptionalAlignment(Alignment))
1479 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001480 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001481 continue;
1482 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001483 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001484 case lltok::kw_dereferenceable: {
1485 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001486 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001487 return true;
1488 B.addDereferenceableAttr(Bytes);
1489 continue;
1490 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001491 case lltok::kw_dereferenceable_or_null: {
1492 uint64_t Bytes;
1493 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1494 return true;
1495 B.addDereferenceableOrNullAttr(Bytes);
1496 continue;
1497 }
Reid Klecknera534a382013-12-19 02:14:12 +00001498 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001499 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1500 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1501 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1502 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001503 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001504 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1505 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001506 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001507 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1508 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001509 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001510 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001511 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001512 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001513
Stephen Lin7577ed52013-04-20 13:16:13 +00001514 case lltok::kw_alignstack:
1515 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001516 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001517 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001518 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001519 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001520 case lltok::kw_minsize:
1521 case lltok::kw_naked:
1522 case lltok::kw_nobuiltin:
1523 case lltok::kw_noduplicate:
1524 case lltok::kw_noimplicitfloat:
1525 case lltok::kw_noinline:
1526 case lltok::kw_nonlazybind:
1527 case lltok::kw_noredzone:
1528 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001529 case lltok::kw_nocf_check:
Stephen Lin7577ed52013-04-20 13:16:13 +00001530 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001531 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001532 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001533 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001534 case lltok::kw_returns_twice:
1535 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001536 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001537 case lltok::kw_sanitize_memory:
1538 case lltok::kw_sanitize_thread:
1539 case lltok::kw_ssp:
1540 case lltok::kw_sspreq:
1541 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001542 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001543 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001544 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001545 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001546 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1547 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001548 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001549
Bill Wendling34c2eb22012-12-04 23:40:58 +00001550 Lex.Lex();
1551 }
1552}
1553
1554/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1555bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1556 bool HaveError = false;
1557
1558 B.clear();
1559
Eugene Zelenko1804a772016-08-25 00:45:04 +00001560 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001561 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001562 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001563 default: // End of attributes.
1564 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001565 case lltok::StringConstant: {
1566 if (ParseStringAttribute(B))
1567 return true;
1568 continue;
1569 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001570 case lltok::kw_dereferenceable: {
1571 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001572 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001573 return true;
1574 B.addDereferenceableAttr(Bytes);
1575 continue;
1576 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001577 case lltok::kw_dereferenceable_or_null: {
1578 uint64_t Bytes;
1579 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1580 return true;
1581 B.addDereferenceableOrNullAttr(Bytes);
1582 continue;
1583 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001584 case lltok::kw_align: {
1585 unsigned Alignment;
1586 if (ParseOptionalAlignment(Alignment))
1587 return true;
1588 B.addAlignmentAttr(Alignment);
1589 continue;
1590 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001591 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1592 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001593 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001594 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1595 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001596
Bill Wendling34c2eb22012-12-04 23:40:58 +00001597 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001598 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001599 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001600 case lltok::kw_nest:
1601 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001602 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001603 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001604 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001605 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001606 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001607 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001608
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001609 case lltok::kw_alignstack:
1610 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001611 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001612 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001613 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001614 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001615 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001616 case lltok::kw_minsize:
1617 case lltok::kw_naked:
1618 case lltok::kw_nobuiltin:
1619 case lltok::kw_noduplicate:
1620 case lltok::kw_noimplicitfloat:
1621 case lltok::kw_noinline:
1622 case lltok::kw_nonlazybind:
1623 case lltok::kw_noredzone:
1624 case lltok::kw_noreturn:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001625 case lltok::kw_nocf_check:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001626 case lltok::kw_nounwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001627 case lltok::kw_optforfuzzing:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001628 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001629 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001630 case lltok::kw_returns_twice:
1631 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001632 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001633 case lltok::kw_sanitize_memory:
1634 case lltok::kw_sanitize_thread:
1635 case lltok::kw_ssp:
1636 case lltok::kw_sspreq:
1637 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001638 case lltok::kw_safestack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001639 case lltok::kw_shadowcallstack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001640 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001641 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001642 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001643 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001644
1645 case lltok::kw_readnone:
1646 case lltok::kw_readonly:
1647 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001648 }
1649
Chris Lattnerac161bf2009-01-02 07:01:27 +00001650 Lex.Lex();
1651 }
1652}
1653
Rafael Espindolac6269912016-05-10 17:16:45 +00001654static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1655 HasLinkage = true;
1656 switch (Kind) {
1657 default:
1658 HasLinkage = false;
1659 return GlobalValue::ExternalLinkage;
1660 case lltok::kw_private:
1661 return GlobalValue::PrivateLinkage;
1662 case lltok::kw_internal:
1663 return GlobalValue::InternalLinkage;
1664 case lltok::kw_weak:
1665 return GlobalValue::WeakAnyLinkage;
1666 case lltok::kw_weak_odr:
1667 return GlobalValue::WeakODRLinkage;
1668 case lltok::kw_linkonce:
1669 return GlobalValue::LinkOnceAnyLinkage;
1670 case lltok::kw_linkonce_odr:
1671 return GlobalValue::LinkOnceODRLinkage;
1672 case lltok::kw_available_externally:
1673 return GlobalValue::AvailableExternallyLinkage;
1674 case lltok::kw_appending:
1675 return GlobalValue::AppendingLinkage;
1676 case lltok::kw_common:
1677 return GlobalValue::CommonLinkage;
1678 case lltok::kw_extern_weak:
1679 return GlobalValue::ExternalWeakLinkage;
1680 case lltok::kw_external:
1681 return GlobalValue::ExternalLinkage;
1682 }
1683}
1684
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685/// ParseOptionalLinkage
1686/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001687/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001688/// ::= 'internal'
1689/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001690/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001691/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001692/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001693/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001694/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001695/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001696/// ::= 'extern_weak'
1697/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001698bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1699 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001700 unsigned &DLLStorageClass,
1701 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001702 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1703 if (HasLinkage)
1704 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001705 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001706 ParseOptionalVisibility(Visibility);
1707 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001708
1709 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1710 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1711 }
1712
Chris Lattnerac161bf2009-01-02 07:01:27 +00001713 return false;
1714}
1715
Sean Fertilec70d28b2017-10-26 15:00:26 +00001716void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1717 switch (Lex.getKind()) {
1718 default:
1719 DSOLocal = false;
1720 break;
1721 case lltok::kw_dso_local:
1722 DSOLocal = true;
1723 Lex.Lex();
1724 break;
1725 case lltok::kw_dso_preemptable:
1726 DSOLocal = false;
1727 Lex.Lex();
1728 break;
1729 }
1730}
1731
Chris Lattnerac161bf2009-01-02 07:01:27 +00001732/// ParseOptionalVisibility
1733/// ::= /*empty*/
1734/// ::= 'default'
1735/// ::= 'hidden'
1736/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001738void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001740 default:
1741 Res = GlobalValue::DefaultVisibility;
1742 return;
1743 case lltok::kw_default:
1744 Res = GlobalValue::DefaultVisibility;
1745 break;
1746 case lltok::kw_hidden:
1747 Res = GlobalValue::HiddenVisibility;
1748 break;
1749 case lltok::kw_protected:
1750 Res = GlobalValue::ProtectedVisibility;
1751 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 }
1753 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001754}
1755
Nico Rieck7157bb72014-01-14 15:22:47 +00001756/// ParseOptionalDLLStorageClass
1757/// ::= /*empty*/
1758/// ::= 'dllimport'
1759/// ::= 'dllexport'
1760///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001761void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001762 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001763 default:
1764 Res = GlobalValue::DefaultStorageClass;
1765 return;
1766 case lltok::kw_dllimport:
1767 Res = GlobalValue::DLLImportStorageClass;
1768 break;
1769 case lltok::kw_dllexport:
1770 Res = GlobalValue::DLLExportStorageClass;
1771 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001772 }
1773 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001774}
1775
Chris Lattnerac161bf2009-01-02 07:01:27 +00001776/// ParseOptionalCallingConv
1777/// ::= /*empty*/
1778/// ::= 'ccc'
1779/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001780/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001781/// ::= 'coldcc'
1782/// ::= 'x86_stdcallcc'
1783/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001784/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001785/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001786/// ::= 'arm_apcscc'
1787/// ::= 'arm_aapcscc'
1788/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001789/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001790/// ::= 'avr_intrcc'
1791/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001792/// ::= 'ptx_kernel'
1793/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001794/// ::= 'spir_func'
1795/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001796/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001797/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001798/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001799/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001800/// ::= 'preserve_mostcc'
1801/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001802/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001803/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001804/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001805/// ::= 'hhvmcc'
1806/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001807/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001808/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001809/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001810/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001811/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001812/// ::= 'amdgpu_gs'
1813/// ::= 'amdgpu_ps'
1814/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001815/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001816/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001817///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001818bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001819 switch (Lex.getKind()) {
1820 default: CC = CallingConv::C; return false;
1821 case lltok::kw_ccc: CC = CallingConv::C; break;
1822 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1823 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1824 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1825 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001826 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001827 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001828 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001829 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1830 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1831 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001832 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001833 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1834 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001835 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1836 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001837 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1838 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001839 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001840 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001841 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001842 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001843 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001844 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1845 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001846 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001847 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001848 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001849 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1850 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001851 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001852 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001853 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001854 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001855 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001856 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1857 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1858 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001859 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001860 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001861 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001862 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001863 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001865
Chris Lattnerac161bf2009-01-02 07:01:27 +00001866 Lex.Lex();
1867 return false;
1868}
1869
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001870/// ParseMetadataAttachment
1871/// ::= !dbg !42
1872bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1873 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1874
1875 std::string Name = Lex.getStrVal();
1876 Kind = M->getMDKindID(Name);
1877 Lex.Lex();
1878
1879 return ParseMDNode(MD);
1880}
1881
Chris Lattner5c427632009-12-30 05:31:19 +00001882/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001883/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001884bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001885 do {
1886 if (Lex.getKind() != lltok::MetadataVar)
1887 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001888
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001889 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001890 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001891 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001892 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001893
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001894 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001895 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001896 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001897
Chris Lattner596760d2009-12-29 21:25:40 +00001898 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001899 } while (EatIfPresent(lltok::comma));
1900 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001901}
1902
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001903/// ParseGlobalObjectMetadataAttachment
1904/// ::= !dbg !57
1905bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1906 unsigned MDK;
1907 MDNode *N;
1908 if (ParseMetadataAttachment(MDK, N))
1909 return true;
1910
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001911 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001912 return false;
1913}
1914
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001915/// ParseOptionalFunctionMetadata
1916/// ::= (!dbg !57)*
1917bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001918 while (Lex.getKind() == lltok::MetadataVar)
1919 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001920 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001921 return false;
1922}
1923
Chris Lattnerac161bf2009-01-02 07:01:27 +00001924/// ParseOptionalAlignment
1925/// ::= /* empty */
1926/// ::= 'align' 4
1927bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1928 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001929 if (!EatIfPresent(lltok::kw_align))
1930 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001931 LocTy AlignLoc = Lex.getLoc();
1932 if (ParseUInt32(Alignment)) return true;
1933 if (!isPowerOf2_32(Alignment))
1934 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001935 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001936 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001937 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938}
1939
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001940/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001941/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001942/// ::= AttrKind '(' 4 ')'
1943///
1944/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1945bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1946 uint64_t &Bytes) {
1947 assert((AttrKind == lltok::kw_dereferenceable ||
1948 AttrKind == lltok::kw_dereferenceable_or_null) &&
1949 "contract!");
1950
Hal Finkelb0407ba2014-07-18 15:51:28 +00001951 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001952 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001953 return false;
1954 LocTy ParenLoc = Lex.getLoc();
1955 if (!EatIfPresent(lltok::lparen))
1956 return Error(ParenLoc, "expected '('");
1957 LocTy DerefLoc = Lex.getLoc();
1958 if (ParseUInt64(Bytes)) return true;
1959 ParenLoc = Lex.getLoc();
1960 if (!EatIfPresent(lltok::rparen))
1961 return Error(ParenLoc, "expected ')'");
1962 if (!Bytes)
1963 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1964 return false;
1965}
1966
Chris Lattnerb2f39502009-12-30 05:44:30 +00001967/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001968/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001969/// ::= ',' align 4
1970///
1971/// This returns with AteExtraComma set to true if it ate an excess comma at the
1972/// end.
1973bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1974 bool &AteExtraComma) {
1975 AteExtraComma = false;
1976 while (EatIfPresent(lltok::comma)) {
1977 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001978 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001979 AteExtraComma = true;
1980 return false;
1981 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001982
Chris Lattner95b0ff42010-04-23 00:50:50 +00001983 if (Lex.getKind() != lltok::kw_align)
1984 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001985
Chris Lattner95b0ff42010-04-23 00:50:50 +00001986 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001988
Devang Patelea8a4b92009-09-17 23:04:48 +00001989 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990}
1991
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001992/// ParseOptionalCommaAddrSpace
1993/// ::=
1994/// ::= ',' addrspace(1)
1995///
1996/// This returns with AteExtraComma set to true if it ate an excess comma at the
1997/// end.
1998bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1999 LocTy &Loc,
2000 bool &AteExtraComma) {
2001 AteExtraComma = false;
2002 while (EatIfPresent(lltok::comma)) {
2003 // Metadata at the end is an early exit.
2004 if (Lex.getKind() == lltok::MetadataVar) {
2005 AteExtraComma = true;
2006 return false;
2007 }
2008
2009 Loc = Lex.getLoc();
2010 if (Lex.getKind() != lltok::kw_addrspace)
2011 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2012
2013 if (ParseOptionalAddrSpace(AddrSpace))
2014 return true;
2015 }
2016
2017 return false;
2018}
2019
George Burgess IV278199f2016-04-12 01:05:35 +00002020bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2021 Optional<unsigned> &HowManyArg) {
2022 Lex.Lex();
2023
2024 auto StartParen = Lex.getLoc();
2025 if (!EatIfPresent(lltok::lparen))
2026 return Error(StartParen, "expected '('");
2027
2028 if (ParseUInt32(BaseSizeArg))
2029 return true;
2030
2031 if (EatIfPresent(lltok::comma)) {
2032 auto HowManyAt = Lex.getLoc();
2033 unsigned HowMany;
2034 if (ParseUInt32(HowMany))
2035 return true;
2036 if (HowMany == BaseSizeArg)
2037 return Error(HowManyAt,
2038 "'allocsize' indices can't refer to the same parameter");
2039 HowManyArg = HowMany;
2040 } else
2041 HowManyArg = None;
2042
2043 auto EndParen = Lex.getLoc();
2044 if (!EatIfPresent(lltok::rparen))
2045 return Error(EndParen, "expected ')'");
2046 return false;
2047}
2048
Eli Friedmanfee02c62011-07-25 23:16:38 +00002049/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002050/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00002051/// else: ::=
2052///
2053/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002054bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00002055 AtomicOrdering &Ordering) {
2056 if (!isAtomic)
2057 return false;
2058
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002059 return ParseScope(SSID) || ParseOrdering(Ordering);
2060}
Tim Northovere94a5182014-03-11 10:48:52 +00002061
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002062/// ParseScope
2063/// ::= syncscope("singlethread" | "<target scope>")?
2064///
2065/// This sets synchronization scope ID to the ID of the parsed value.
2066bool LLParser::ParseScope(SyncScope::ID &SSID) {
2067 SSID = SyncScope::System;
2068 if (EatIfPresent(lltok::kw_syncscope)) {
2069 auto StartParenAt = Lex.getLoc();
2070 if (!EatIfPresent(lltok::lparen))
2071 return Error(StartParenAt, "Expected '(' in syncscope");
2072
2073 std::string SSN;
2074 auto SSNAt = Lex.getLoc();
2075 if (ParseStringConstant(SSN))
2076 return Error(SSNAt, "Expected synchronization scope name");
2077
2078 auto EndParenAt = Lex.getLoc();
2079 if (!EatIfPresent(lltok::rparen))
2080 return Error(EndParenAt, "Expected ')' in syncscope");
2081
2082 SSID = Context.getOrInsertSyncScopeID(SSN);
2083 }
2084
2085 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002086}
2087
2088/// ParseOrdering
2089/// ::= AtomicOrdering
2090///
2091/// This sets Ordering to the parsed value.
2092bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002093 switch (Lex.getKind()) {
2094 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002095 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2096 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2097 // Not specified yet:
2098 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2099 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2100 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2101 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2102 case lltok::kw_seq_cst:
2103 Ordering = AtomicOrdering::SequentiallyConsistent;
2104 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002105 }
2106 Lex.Lex();
2107 return false;
2108}
2109
Charles Davisbe5557e2010-02-12 00:31:15 +00002110/// ParseOptionalStackAlignment
2111/// ::= /* empty */
2112/// ::= 'alignstack' '(' 4 ')'
2113bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2114 Alignment = 0;
2115 if (!EatIfPresent(lltok::kw_alignstack))
2116 return false;
2117 LocTy ParenLoc = Lex.getLoc();
2118 if (!EatIfPresent(lltok::lparen))
2119 return Error(ParenLoc, "expected '('");
2120 LocTy AlignLoc = Lex.getLoc();
2121 if (ParseUInt32(Alignment)) return true;
2122 ParenLoc = Lex.getLoc();
2123 if (!EatIfPresent(lltok::rparen))
2124 return Error(ParenLoc, "expected ')'");
2125 if (!isPowerOf2_32(Alignment))
2126 return Error(AlignLoc, "stack alignment is not a power of two");
2127 return false;
2128}
Devang Patelea8a4b92009-09-17 23:04:48 +00002129
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002130/// ParseIndexList - This parses the index list for an insert/extractvalue
2131/// instruction. This sets AteExtraComma in the case where we eat an extra
2132/// comma at the end of the line and find that it is followed by metadata.
2133/// Clients that don't allow metadata can call the version of this function that
2134/// only takes one argument.
2135///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002136/// ParseIndexList
2137/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002138///
2139bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2140 bool &AteExtraComma) {
2141 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002142
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143 if (Lex.getKind() != lltok::comma)
2144 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002145
Chris Lattner3822f632009-01-02 08:05:26 +00002146 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002147 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002148 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002149 AteExtraComma = true;
2150 return false;
2151 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002152 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002153 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002154 Indices.push_back(Idx);
2155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 return false;
2158}
2159
2160//===----------------------------------------------------------------------===//
2161// Type Parsing.
2162//===----------------------------------------------------------------------===//
2163
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002164/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002165bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002166 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 switch (Lex.getKind()) {
2168 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002169 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002171 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002174 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002176 // Type ::= StructType
2177 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 return true;
2179 break;
2180 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002181 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 Lex.Lex(); // eat the lsquare.
2183 if (ParseArrayVectorType(Result, false))
2184 return true;
2185 break;
2186 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002188 Lex.Lex();
2189 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002190 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002191 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002192 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002193 } else if (ParseArrayVectorType(Result, true))
2194 return true;
2195 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002196 case lltok::LocalVar: {
2197 // Type ::= %foo
2198 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002199
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002200 // If the type hasn't been defined yet, create a forward definition and
2201 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002202 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002203 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002204 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002206 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002207 Lex.Lex();
2208 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002211 case lltok::LocalVarID: {
2212 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002213 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002214
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002215 // If the type hasn't been defined yet, create a forward definition and
2216 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002217 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002218 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002219 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002221 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 Lex.Lex();
2223 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224 }
2225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
2227 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002228 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002229 switch (Lex.getKind()) {
2230 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002231 default:
2232 if (!AllowVoid && Result->isVoidTy())
2233 return Error(TypeLoc, "void type only allowed for function results");
2234 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002236 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002238 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002240 if (Result->isVoidTy())
2241 return TokError("pointers to void are invalid - use i8* instead");
2242 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002243 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002244 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002245 Lex.Lex();
2246 break;
2247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002248 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002249 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002250 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002252 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002253 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002254 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002255 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 unsigned AddrSpace;
2257 if (ParseOptionalAddrSpace(AddrSpace) ||
2258 ParseToken(lltok::star, "expected '*' in address space"))
2259 return true;
2260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002261 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 break;
2263 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002264
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2266 case lltok::lparen:
2267 if (ParseFunctionType(Result))
2268 return true;
2269 break;
2270 }
2271 }
2272}
2273
2274/// ParseParameterList
2275/// ::= '(' ')'
2276/// ::= '(' Arg (',' Arg)* ')'
2277/// Arg
2278/// ::= Type OptionalAttributes Value OptionalAttributes
2279bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002280 PerFunctionState &PFS, bool IsMustTailCall,
2281 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 if (ParseToken(lltok::lparen, "expected '(' in call"))
2283 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 while (Lex.getKind() != lltok::rparen) {
2286 // If this isn't the first argument, we need a comma.
2287 if (!ArgList.empty() &&
2288 ParseToken(lltok::comma, "expected ',' in argument list"))
2289 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Reid Kleckner83498642014-08-26 00:33:28 +00002291 // Parse an ellipsis if this is a musttail call in a variadic function.
2292 if (Lex.getKind() == lltok::dotdotdot) {
2293 const char *Msg = "unexpected ellipsis in argument list for ";
2294 if (!IsMustTailCall)
2295 return TokError(Twine(Msg) + "non-musttail call");
2296 if (!InVarArgsFunc)
2297 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2298 Lex.Lex(); // Lex the '...', it is purely for readability.
2299 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2300 }
2301
Chris Lattnerac161bf2009-01-02 07:01:27 +00002302 // Parse the argument.
2303 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002304 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002305 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002307 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002309
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002310 if (ArgTy->isMetadataTy()) {
2311 if (ParseMetadataAsValue(V, PFS))
2312 return true;
2313 } else {
2314 // Otherwise, handle normal operands.
2315 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2316 return true;
2317 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002318 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002319 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 }
2321
Reid Kleckner83498642014-08-26 00:33:28 +00002322 if (IsMustTailCall && InVarArgsFunc)
2323 return TokError("expected '...' at end of argument list for musttail call "
2324 "in varargs function");
2325
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 Lex.Lex(); // Lex the ')'.
2327 return false;
2328}
2329
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002330/// ParseOptionalOperandBundles
2331/// ::= /*empty*/
2332/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2333///
2334/// OperandBundle
2335/// ::= bundle-tag '(' ')'
2336/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2337///
2338/// bundle-tag ::= String Constant
2339bool LLParser::ParseOptionalOperandBundles(
2340 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2341 LocTy BeginLoc = Lex.getLoc();
2342 if (!EatIfPresent(lltok::lsquare))
2343 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002344
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002345 while (Lex.getKind() != lltok::rsquare) {
2346 // If this isn't the first operand bundle, we need a comma.
2347 if (!BundleList.empty() &&
2348 ParseToken(lltok::comma, "expected ',' in input list"))
2349 return true;
2350
2351 std::string Tag;
2352 if (ParseStringConstant(Tag))
2353 return true;
2354
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002355 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2356 return true;
2357
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002358 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002359 while (Lex.getKind() != lltok::rparen) {
2360 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002361 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002362 ParseToken(lltok::comma, "expected ',' in input list"))
2363 return true;
2364
2365 Type *Ty = nullptr;
2366 Value *Input = nullptr;
2367 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2368 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002369 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002370 }
2371
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002372 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2373
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002374 Lex.Lex(); // Lex the ')'.
2375 }
2376
2377 if (BundleList.empty())
2378 return Error(BeginLoc, "operand bundle set must not be empty");
2379
2380 Lex.Lex(); // Lex the ']'.
2381 return false;
2382}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002383
Chris Lattner2ed06b42009-01-05 18:34:07 +00002384/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386/// ::= '(' ArgTypeListI ')'
2387/// ArgTypeListI
2388/// ::= /*empty*/
2389/// ::= '...'
2390/// ::= ArgTypeList ',' '...'
2391/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002392///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2394 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395 isVarArg = false;
2396 assert(Lex.getKind() == lltok::lparen);
2397 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399 if (Lex.getKind() == lltok::rparen) {
2400 // empty
2401 } else if (Lex.getKind() == lltok::dotdotdot) {
2402 isVarArg = true;
2403 Lex.Lex();
2404 } else {
2405 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002406 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002407 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002411 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Chris Lattnerfdd87902009-10-05 05:54:46 +00002413 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002414 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002415
Chris Lattnerdef19492011-06-17 06:36:20 +00002416 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 Name = Lex.getStrVal();
2418 Lex.Lex();
2419 }
Chris Lattner3822f632009-01-02 08:05:26 +00002420
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002421 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002422 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002423
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002424 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002425 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002426 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002427
Chris Lattner3822f632009-01-02 08:05:26 +00002428 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002429 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002430 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002432 break;
2433 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002434
Chris Lattnerac161bf2009-01-02 07:01:27 +00002435 // Otherwise must be an argument type.
2436 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002437 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002438
Chris Lattnerfdd87902009-10-05 05:54:46 +00002439 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002440 return Error(TypeLoc, "argument can not have void type");
2441
Chris Lattnerdef19492011-06-17 06:36:20 +00002442 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 Name = Lex.getStrVal();
2444 Lex.Lex();
2445 } else {
2446 Name = "";
2447 }
Chris Lattner3822f632009-01-02 08:05:26 +00002448
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002449 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002450 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002451
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002452 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002453 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002454 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 }
2456 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457
Chris Lattner3822f632009-01-02 08:05:26 +00002458 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002459}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461/// ParseFunctionType
2462/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002463bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 assert(Lex.getKind() == lltok::lparen);
2465
Chris Lattnerce473c72009-01-05 08:04:33 +00002466 if (!FunctionType::isValidReturnType(Result))
2467 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002468
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002469 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002470 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002471 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002473
Chris Lattnerac161bf2009-01-02 07:01:27 +00002474 // Reject names on the arguments lists.
2475 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2476 if (!ArgList[i].Name.empty())
2477 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002478 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002479 return Error(ArgList[i].Loc,
2480 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Jay Foadb804a2b2011-07-12 14:06:48 +00002483 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002485 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002487 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 return false;
2489}
2490
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002491/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2492/// other structs.
2493bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2494 SmallVector<Type*, 8> Elts;
2495 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002496
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002497 Result = StructType::get(Context, Elts, Packed);
2498 return false;
2499}
2500
2501/// ParseStructDefinition - Parse a struct in a 'type' definition.
2502bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2503 std::pair<Type*, LocTy> &Entry,
2504 Type *&ResultTy) {
2505 // If the type was already defined, diagnose the redefinition.
2506 if (Entry.first && !Entry.second.isValid())
2507 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002508
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002509 // If we have opaque, just return without filling in the definition for the
2510 // struct. This counts as a definition as far as the .ll file goes.
2511 if (EatIfPresent(lltok::kw_opaque)) {
2512 // This type is being defined, so clear the location to indicate this.
2513 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002514
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002515 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002516 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002517 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002518 ResultTy = Entry.first;
2519 return false;
2520 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002521
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002522 // If the type starts with '<', then it is either a packed struct or a vector.
2523 bool isPacked = EatIfPresent(lltok::less);
2524
2525 // If we don't have a struct, then we have a random type alias, which we
2526 // accept for compatibility with old files. These types are not allowed to be
2527 // forward referenced and not allowed to be recursive.
2528 if (Lex.getKind() != lltok::lbrace) {
2529 if (Entry.first)
2530 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002531
Craig Topper2617dcc2014-04-15 06:32:26 +00002532 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002533 if (isPacked)
2534 return ParseArrayVectorType(ResultTy, true);
2535 return ParseType(ResultTy);
2536 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002537
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002538 // This type is being defined, so clear the location to indicate this.
2539 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002540
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002541 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002542 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002543 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002544
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002545 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002546
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002547 SmallVector<Type*, 8> Body;
2548 if (ParseStructBody(Body) ||
2549 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2550 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002551
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002552 STy->setBody(Body, isPacked);
2553 ResultTy = STy;
2554 return false;
2555}
2556
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002558/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002559/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002560/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002562/// ::= '<' '{' Type (',' Type)* '}' '>'
2563bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 assert(Lex.getKind() == lltok::lbrace);
2565 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002567 // Handle the empty struct.
2568 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002569 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570
Chris Lattnerf880ca22009-03-09 04:49:14 +00002571 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002572 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002573 if (ParseType(Ty)) return true;
2574 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002576 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002577 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002578
Chris Lattner3822f632009-01-02 08:05:26 +00002579 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002580 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002581 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002582
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002583 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002584 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002585
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002586 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002588
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002589 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002590}
2591
2592/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2593/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002594/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595/// ::= '[' APSINTVAL 'x' Types ']'
2596/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002597bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2599 Lex.getAPSIntVal().getBitWidth() > 64)
2600 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002601
Chris Lattnerac161bf2009-01-02 07:01:27 +00002602 LocTy SizeLoc = Lex.getLoc();
2603 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002604 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002605
Chris Lattner3822f632009-01-02 08:05:26 +00002606 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2607 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608
2609 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002610 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002611 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002612
Chris Lattner3822f632009-01-02 08:05:26 +00002613 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2614 "expected end of sequential type"))
2615 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002616
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002618 if (Size == 0)
2619 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 if ((unsigned)Size != Size)
2621 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002622 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002623 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002624 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002625 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002626 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002627 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002628 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002629 }
2630 return false;
2631}
2632
2633//===----------------------------------------------------------------------===//
2634// Function Semantic Analysis.
2635//===----------------------------------------------------------------------===//
2636
Chris Lattner3432c622009-10-28 03:39:23 +00002637LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2638 int functionNumber)
2639 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002640
2641 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002642 for (Argument &A : F.args())
2643 if (!A.hasName())
2644 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645}
2646
2647LLParser::PerFunctionState::~PerFunctionState() {
2648 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002649
David Blaikie9ebdc692015-09-21 21:07:50 +00002650 for (const auto &P : ForwardRefVals) {
2651 if (isa<BasicBlock>(P.second.first))
2652 continue;
2653 P.second.first->replaceAllUsesWith(
2654 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002655 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002656 }
2657
2658 for (const auto &P : ForwardRefValIDs) {
2659 if (isa<BasicBlock>(P.second.first))
2660 continue;
2661 P.second.first->replaceAllUsesWith(
2662 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002663 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002664 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665}
2666
Chris Lattner3432c622009-10-28 03:39:23 +00002667bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 if (!ForwardRefVals.empty())
2669 return P.Error(ForwardRefVals.begin()->second.second,
2670 "use of undefined value '%" + ForwardRefVals.begin()->first +
2671 "'");
2672 if (!ForwardRefValIDs.empty())
2673 return P.Error(ForwardRefValIDs.begin()->second.second,
2674 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002675 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 return false;
2677}
2678
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002679static bool isValidVariableType(Module *M, Type *Ty, Value *Val, bool IsCall) {
2680 if (Val->getType() == Ty)
2681 return true;
2682 // For calls we also accept variables in the program address space
2683 if (IsCall && isa<PointerType>(Ty)) {
2684 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
2685 M->getDataLayout().getProgramAddressSpace());
2686 if (Val->getType() == TyInProgAS)
2687 return true;
2688 }
2689 return false;
2690}
2691
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692/// GetVal - Get a value with the specified name or ID, creating a
2693/// forward reference record if needed. This can return null if the value
2694/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002695Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002696 LocTy Loc, bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002698 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002699
Chris Lattnerac161bf2009-01-02 07:01:27 +00002700 // If this is a forward reference for the value, see if we already created a
2701 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002702 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002703 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 if (I != ForwardRefVals.end())
2705 Val = I->second.first;
2706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002707
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 // If we have the value in the symbol table or fwd-ref table, return it.
2709 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002710 if (isValidVariableType(P.M, Ty, Val, IsCall))
2711 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002712 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 P.Error(Loc, "'%" + Name + "' is not a basic block");
2714 else
2715 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002716 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002717 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002719
Chris Lattnerac161bf2009-01-02 07:01:27 +00002720 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002721 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002723 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002725
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 // Otherwise, create a new forward reference for this value and remember it.
2727 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002728 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002729 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002730 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002731 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002732 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002733
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2735 return FwdVal;
2736}
2737
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002738Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2739 bool IsCall) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002740 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002741 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Chris Lattnerac161bf2009-01-02 07:01:27 +00002743 // If this is a forward reference for the value, see if we already created a
2744 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002745 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002746 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002747 if (I != ForwardRefValIDs.end())
2748 Val = I->second.first;
2749 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Chris Lattnerac161bf2009-01-02 07:01:27 +00002751 // If we have the value in the symbol table or fwd-ref table, return it.
2752 if (Val) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002753 if (isValidVariableType(P.M, Ty, Val, IsCall))
2754 return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002755 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002756 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002757 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002758 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002759 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002760 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002761 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002762
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002763 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002765 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 // Otherwise, create a new forward reference for this value and remember it.
2769 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002770 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002771 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002772 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002773 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2777 return FwdVal;
2778}
2779
2780/// SetInstName - After an instruction is parsed and inserted into its
2781/// basic block, this installs its name.
2782bool LLParser::PerFunctionState::SetInstName(int NameID,
2783 const std::string &NameStr,
2784 LocTy NameLoc, Instruction *Inst) {
2785 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002786 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 if (NameID != -1 || !NameStr.empty())
2788 return P.Error(NameLoc, "instructions returning void cannot have a name");
2789 return false;
2790 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002791
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 // If this was a numbered instruction, verify that the instruction is the
2793 // expected value and resolve any forward references.
2794 if (NameStr.empty()) {
2795 // If neither a name nor an ID was specified, just use the next ID.
2796 if (NameID == -1)
2797 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002798
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 if (unsigned(NameID) != NumberedVals.size())
2800 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002801 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002802
David Blaikie9ebdc692015-09-21 21:07:50 +00002803 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002805 Value *Sentinel = FI->second.first;
2806 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002807 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002808 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002809
2810 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002811 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002812 ForwardRefValIDs.erase(FI);
2813 }
2814
2815 NumberedVals.push_back(Inst);
2816 return false;
2817 }
2818
2819 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002820 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002822 Value *Sentinel = FI->second.first;
2823 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002824 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002825 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002826
2827 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002828 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 ForwardRefVals.erase(FI);
2830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002831
Chris Lattnerac161bf2009-01-02 07:01:27 +00002832 // Set the name on the instruction.
2833 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002835 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002836 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 NameStr + "'");
2838 return false;
2839}
2840
2841/// GetBB - Get a basic block with the specified name or ID, creating a
2842/// forward reference record if needed.
2843BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2844 LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002845 return dyn_cast_or_null<BasicBlock>(
2846 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847}
2848
2849BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Alexander Richardsonc11ae182018-02-27 11:15:11 +00002850 return dyn_cast_or_null<BasicBlock>(
2851 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852}
2853
2854/// DefineBB - Define the specified basic block, which is either named or
2855/// unnamed. If there is an error, this returns null otherwise it returns
2856/// the block being defined.
2857BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2858 LocTy Loc) {
2859 BasicBlock *BB;
2860 if (Name.empty())
2861 BB = GetBB(NumberedVals.size(), Loc);
2862 else
2863 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002864 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002865
Chris Lattnerac161bf2009-01-02 07:01:27 +00002866 // Move the block to the end of the function. Forward ref'd blocks are
2867 // inserted wherever they happen to be referenced.
2868 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002869
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 // Remove the block from forward ref sets.
2871 if (Name.empty()) {
2872 ForwardRefValIDs.erase(NumberedVals.size());
2873 NumberedVals.push_back(BB);
2874 } else {
2875 // BB forward references are already in the function symbol table.
2876 ForwardRefVals.erase(Name);
2877 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 return BB;
2880}
2881
2882//===----------------------------------------------------------------------===//
2883// Constants.
2884//===----------------------------------------------------------------------===//
2885
2886/// ParseValID - Parse an abstract value that doesn't necessarily have a
2887/// type implied. For example, if we parse "4" we don't know what integer type
2888/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002889/// sanity. PFS is used to convert function-local operands of metadata (since
2890/// metadata operands are not just parsed here but also converted to values).
2891/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002892bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 ID.Loc = Lex.getLoc();
2894 switch (Lex.getKind()) {
2895 default: return TokError("expected value token");
2896 case lltok::GlobalID: // @42
2897 ID.UIntVal = Lex.getUIntVal();
2898 ID.Kind = ValID::t_GlobalID;
2899 break;
2900 case lltok::GlobalVar: // @foo
2901 ID.StrVal = Lex.getStrVal();
2902 ID.Kind = ValID::t_GlobalName;
2903 break;
2904 case lltok::LocalVarID: // %42
2905 ID.UIntVal = Lex.getUIntVal();
2906 ID.Kind = ValID::t_LocalID;
2907 break;
2908 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002909 ID.StrVal = Lex.getStrVal();
2910 ID.Kind = ValID::t_LocalName;
2911 break;
2912 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002913 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002914 ID.Kind = ValID::t_APSInt;
2915 break;
2916 case lltok::APFloat:
2917 ID.APFloatVal = Lex.getAPFloatVal();
2918 ID.Kind = ValID::t_APFloat;
2919 break;
2920 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002921 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002922 ID.Kind = ValID::t_Constant;
2923 break;
2924 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002925 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002926 ID.Kind = ValID::t_Constant;
2927 break;
2928 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2929 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2930 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002931 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002932
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 case lltok::lbrace: {
2934 // ValID ::= '{' ConstVector '}'
2935 Lex.Lex();
2936 SmallVector<Constant*, 16> Elts;
2937 if (ParseGlobalValueVector(Elts) ||
2938 ParseToken(lltok::rbrace, "expected end of struct constant"))
2939 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002940
David Blaikieadbda4b2015-08-03 20:08:41 +00002941 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002942 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002943 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2944 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002945 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 return false;
2947 }
2948 case lltok::less: {
2949 // ValID ::= '<' ConstVector '>' --> Vector.
2950 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2951 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002952 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002953
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 SmallVector<Constant*, 16> Elts;
2955 LocTy FirstEltLoc = Lex.getLoc();
2956 if (ParseGlobalValueVector(Elts) ||
2957 (isPackedStruct &&
2958 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2959 ParseToken(lltok::greater, "expected end of constant"))
2960 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002963 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2964 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2965 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002966 ID.UIntVal = Elts.size();
2967 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002968 return false;
2969 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002970
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 if (Elts.empty())
2972 return Error(ID.Loc, "constant vector must not be empty");
2973
Duncan Sands9dff9be2010-02-15 16:12:20 +00002974 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002975 !Elts[0]->getType()->isFloatingPointTy() &&
2976 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002977 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002978 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002979
Chris Lattnerac161bf2009-01-02 07:01:27 +00002980 // Verify that all the vector elements have the same type.
2981 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2982 if (Elts[i]->getType() != Elts[0]->getType())
2983 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002984 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002985 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002986
Chris Lattner69229312011-02-15 00:14:00 +00002987 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002988 ID.Kind = ValID::t_Constant;
2989 return false;
2990 }
2991 case lltok::lsquare: { // Array Constant
2992 Lex.Lex();
2993 SmallVector<Constant*, 16> Elts;
2994 LocTy FirstEltLoc = Lex.getLoc();
2995 if (ParseGlobalValueVector(Elts) ||
2996 ParseToken(lltok::rsquare, "expected end of array constant"))
2997 return true;
2998
2999 // Handle empty element.
3000 if (Elts.empty()) {
3001 // Use undef instead of an array because it's inconvenient to determine
3002 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00003003 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003004 return false;
3005 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003006
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003008 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003009 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003010
Owen Anderson4056ca92009-07-29 22:17:13 +00003011 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003012
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00003014 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 if (Elts[i]->getType() != Elts[0]->getType())
3016 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00003017 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003018 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003019 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003020
Jay Foad83be3612011-06-22 09:24:39 +00003021 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 ID.Kind = ValID::t_Constant;
3023 return false;
3024 }
3025 case lltok::kw_c: // c "foo"
3026 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003027 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3028 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3030 ID.Kind = ValID::t_Constant;
3031 return false;
3032
3033 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00003034 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3035 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00003036 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 Lex.Lex();
3038 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003039 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00003040 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003041 ParseStringConstant(ID.StrVal) ||
3042 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 ParseToken(lltok::StringConstant, "expected constraint string"))
3044 return true;
3045 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00003046 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00003047 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003048 ID.Kind = ValID::t_InlineAsm;
3049 return false;
3050 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Chris Lattner3432c622009-10-28 03:39:23 +00003052 case lltok::kw_blockaddress: {
3053 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3054 Lex.Lex();
3055
3056 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003057
Chris Lattner3432c622009-10-28 03:39:23 +00003058 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3059 ParseValID(Fn) ||
3060 ParseToken(lltok::comma, "expected comma in block address expression")||
3061 ParseValID(Label) ||
3062 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3063 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003064
Chris Lattner3432c622009-10-28 03:39:23 +00003065 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3066 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00003067 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00003068 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003069
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003070 // Try to find the function (but skip it if it's forward-referenced).
3071 GlobalValue *GV = nullptr;
3072 if (Fn.Kind == ValID::t_GlobalID) {
3073 if (Fn.UIntVal < NumberedVals.size())
3074 GV = NumberedVals[Fn.UIntVal];
3075 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3076 GV = M->getNamedValue(Fn.StrVal);
3077 }
3078 Function *F = nullptr;
3079 if (GV) {
3080 // Confirm that it's actually a function with a definition.
3081 if (!isa<Function>(GV))
3082 return Error(Fn.Loc, "expected function name in blockaddress");
3083 F = cast<Function>(GV);
3084 if (F->isDeclaration())
3085 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3086 }
3087
3088 if (!F) {
3089 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003090 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003091 ForwardRefBlockAddresses.insert(std::make_pair(
3092 std::move(Fn),
3093 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003094 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3095 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003096 if (!FwdRef)
3097 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3098 GlobalValue::InternalLinkage, nullptr, "");
3099 ID.ConstantVal = FwdRef;
3100 ID.Kind = ValID::t_Constant;
3101 return false;
3102 }
3103
3104 // We found the function; now find the basic block. Don't use PFS, since we
3105 // might be inside a constant expression.
3106 BasicBlock *BB;
3107 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3108 if (Label.Kind == ValID::t_LocalID)
3109 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3110 else
3111 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3112 if (!BB)
3113 return Error(Label.Loc, "referenced value is not a basic block");
3114 } else {
3115 if (Label.Kind == ValID::t_LocalID)
3116 return Error(Label.Loc, "cannot take address of numeric label after "
3117 "the function is defined");
3118 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003119 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003120 if (!BB)
3121 return Error(Label.Loc, "referenced value is not a basic block");
3122 }
3123
3124 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003125 ID.Kind = ValID::t_Constant;
3126 return false;
3127 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003128
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 case lltok::kw_trunc:
3130 case lltok::kw_zext:
3131 case lltok::kw_sext:
3132 case lltok::kw_fptrunc:
3133 case lltok::kw_fpext:
3134 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003135 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003136 case lltok::kw_uitofp:
3137 case lltok::kw_sitofp:
3138 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003139 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003141 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003143 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 Constant *SrcVal;
3145 Lex.Lex();
3146 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3147 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003148 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003149 ParseType(DestTy) ||
3150 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3151 return true;
3152 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3153 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003154 getTypeString(SrcVal->getType()) + "' to '" +
3155 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003156 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003157 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 ID.Kind = ValID::t_Constant;
3159 return false;
3160 }
3161 case lltok::kw_extractvalue: {
3162 Lex.Lex();
3163 Constant *Val;
3164 SmallVector<unsigned, 4> Indices;
3165 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3166 ParseGlobalTypeAndValue(Val) ||
3167 ParseIndexList(Indices) ||
3168 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3169 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003170
Chris Lattner392be582010-02-12 20:49:41 +00003171 if (!Val->getType()->isAggregateType())
3172 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003173 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003175 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 ID.Kind = ValID::t_Constant;
3177 return false;
3178 }
3179 case lltok::kw_insertvalue: {
3180 Lex.Lex();
3181 Constant *Val0, *Val1;
3182 SmallVector<unsigned, 4> Indices;
3183 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3184 ParseGlobalTypeAndValue(Val0) ||
3185 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3186 ParseGlobalTypeAndValue(Val1) ||
3187 ParseIndexList(Indices) ||
3188 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3189 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003190 if (!Val0->getType()->isAggregateType())
3191 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003192 Type *IndexedType =
3193 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3194 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003195 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003196 if (IndexedType != Val1->getType())
3197 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3198 getTypeString(Val1->getType()) +
3199 "' instead of '" + getTypeString(IndexedType) +
3200 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003201 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003202 ID.Kind = ValID::t_Constant;
3203 return false;
3204 }
3205 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003206 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003207 unsigned PredVal, Opc = Lex.getUIntVal();
3208 Constant *Val0, *Val1;
3209 Lex.Lex();
3210 if (ParseCmpPredicate(PredVal, Opc) ||
3211 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3212 ParseGlobalTypeAndValue(Val0) ||
3213 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3214 ParseGlobalTypeAndValue(Val1) ||
3215 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3216 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003217
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 if (Val0->getType() != Val1->getType())
3219 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003220
Chris Lattnerac161bf2009-01-02 07:01:27 +00003221 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003222
Chris Lattnerac161bf2009-01-02 07:01:27 +00003223 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003224 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003225 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003226 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003227 } else {
3228 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003229 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003230 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003231 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003232 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003233 }
3234 ID.Kind = ValID::t_Constant;
3235 return false;
3236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003237
Chris Lattnerac161bf2009-01-02 07:01:27 +00003238 // Binary Operators.
3239 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003240 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003242 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003243 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003244 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003245 case lltok::kw_udiv:
3246 case lltok::kw_sdiv:
3247 case lltok::kw_fdiv:
3248 case lltok::kw_urem:
3249 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003250 case lltok::kw_frem:
3251 case lltok::kw_shl:
3252 case lltok::kw_lshr:
3253 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003254 bool NUW = false;
3255 bool NSW = false;
3256 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003257 unsigned Opc = Lex.getUIntVal();
3258 Constant *Val0, *Val1;
3259 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003260 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003261 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3262 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003263 if (EatIfPresent(lltok::kw_nuw))
3264 NUW = true;
3265 if (EatIfPresent(lltok::kw_nsw)) {
3266 NSW = true;
3267 if (EatIfPresent(lltok::kw_nuw))
3268 NUW = true;
3269 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003270 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3271 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003272 if (EatIfPresent(lltok::kw_exact))
3273 Exact = true;
3274 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3276 ParseGlobalTypeAndValue(Val0) ||
3277 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3278 ParseGlobalTypeAndValue(Val1) ||
3279 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3280 return true;
3281 if (Val0->getType() != Val1->getType())
3282 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003283 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003284 if (NUW)
3285 return Error(ModifierLoc, "nuw only applies to integer operations");
3286 if (NSW)
3287 return Error(ModifierLoc, "nsw only applies to integer operations");
3288 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003289 // Check that the type is valid for the operator.
3290 switch (Opc) {
3291 case Instruction::Add:
3292 case Instruction::Sub:
3293 case Instruction::Mul:
3294 case Instruction::UDiv:
3295 case Instruction::SDiv:
3296 case Instruction::URem:
3297 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003298 case Instruction::Shl:
3299 case Instruction::AShr:
3300 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003301 if (!Val0->getType()->isIntOrIntVectorTy())
3302 return Error(ID.Loc, "constexpr requires integer operands");
3303 break;
3304 case Instruction::FAdd:
3305 case Instruction::FSub:
3306 case Instruction::FMul:
3307 case Instruction::FDiv:
3308 case Instruction::FRem:
3309 if (!Val0->getType()->isFPOrFPVectorTy())
3310 return Error(ID.Loc, "constexpr requires fp operands");
3311 break;
3312 default: llvm_unreachable("Unknown binary operator!");
3313 }
Dan Gohman1b849082009-09-07 23:54:19 +00003314 unsigned Flags = 0;
3315 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3316 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003317 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003318 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003319 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003320 ID.Kind = ValID::t_Constant;
3321 return false;
3322 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003323
Chris Lattnerac161bf2009-01-02 07:01:27 +00003324 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003325 case lltok::kw_and:
3326 case lltok::kw_or:
3327 case lltok::kw_xor: {
3328 unsigned Opc = Lex.getUIntVal();
3329 Constant *Val0, *Val1;
3330 Lex.Lex();
3331 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3332 ParseGlobalTypeAndValue(Val0) ||
3333 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3334 ParseGlobalTypeAndValue(Val1) ||
3335 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3336 return true;
3337 if (Val0->getType() != Val1->getType())
3338 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003339 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003340 return Error(ID.Loc,
3341 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003342 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003343 ID.Kind = ValID::t_Constant;
3344 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003345 }
3346
Chris Lattnerac161bf2009-01-02 07:01:27 +00003347 case lltok::kw_getelementptr:
3348 case lltok::kw_shufflevector:
3349 case lltok::kw_insertelement:
3350 case lltok::kw_extractelement:
3351 case lltok::kw_select: {
3352 unsigned Opc = Lex.getUIntVal();
3353 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003354 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003355 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003356 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003357
Dan Gohman1639c392009-07-27 21:53:46 +00003358 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003359 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003360
3361 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3362 return true;
3363
3364 LocTy ExplicitTypeLoc = Lex.getLoc();
3365 if (Opc == Instruction::GetElementPtr) {
3366 if (ParseType(Ty) ||
3367 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3368 return true;
3369 }
3370
Peter Collingbourned93620b2016-11-10 22:34:55 +00003371 Optional<unsigned> InRangeOp;
3372 if (ParseGlobalValueVector(
3373 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003374 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3375 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003376
Chris Lattnerac161bf2009-01-02 07:01:27 +00003377 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003378 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003379 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003380 return Error(ID.Loc, "base of getelementptr must be a pointer");
3381
3382 Type *BaseType = Elts[0]->getType();
3383 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003384 if (Ty != BasePointerType->getElementType())
3385 return Error(
3386 ExplicitTypeLoc,
3387 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003388
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003389 unsigned GEPWidth =
3390 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3391
Jay Foaded8db7d2011-07-21 14:31:17 +00003392 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003393 for (Constant *Val : Indices) {
3394 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003395 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003396 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003397 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003398 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003399 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003400 return Error(
3401 ID.Loc,
3402 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003403 // GEPWidth may have been unknown because the base is a scalar,
3404 // but it is known now.
3405 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003406 }
3407 }
3408
Craig Toppere3dcce92015-08-01 22:20:21 +00003409 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003410 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003411 return Error(ID.Loc, "base element of getelementptr must be sized");
3412
David Blaikie4a2e73b2015-04-02 18:55:32 +00003413 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003414 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003415
3416 if (InRangeOp) {
3417 if (*InRangeOp == 0)
3418 return Error(ID.Loc,
3419 "inrange keyword may not appear on pointer operand");
3420 --*InRangeOp;
3421 }
3422
3423 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3424 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003425 } else if (Opc == Instruction::Select) {
3426 if (Elts.size() != 3)
3427 return Error(ID.Loc, "expected three operands to select");
3428 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3429 Elts[2]))
3430 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003431 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003432 } else if (Opc == Instruction::ShuffleVector) {
3433 if (Elts.size() != 3)
3434 return Error(ID.Loc, "expected three operands to shufflevector");
3435 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3436 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003437 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003438 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003439 } else if (Opc == Instruction::ExtractElement) {
3440 if (Elts.size() != 2)
3441 return Error(ID.Loc, "expected two operands to extractelement");
3442 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3443 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003444 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003445 } else {
3446 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3447 if (Elts.size() != 3)
3448 return Error(ID.Loc, "expected three operands to insertelement");
3449 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3450 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003451 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003452 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003453 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003454
Chris Lattnerac161bf2009-01-02 07:01:27 +00003455 ID.Kind = ValID::t_Constant;
3456 return false;
3457 }
3458 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003459
Chris Lattnerac161bf2009-01-02 07:01:27 +00003460 Lex.Lex();
3461 return false;
3462}
3463
3464/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003465bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003466 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003467 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003468 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003469 bool Parsed = ParseValID(ID) ||
Alexander Richardsonc11ae182018-02-27 11:15:11 +00003470 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003471 if (V && !(C = dyn_cast<Constant>(V)))
3472 return Error(ID.Loc, "global values must be constants");
3473 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003474}
3475
Victor Hernandez9d75c962010-01-11 22:31:58 +00003476bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003477 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003478 return ParseType(Ty) ||
3479 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003480}
3481
Rafael Espindola83a362c2015-01-06 22:55:16 +00003482bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003483 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003484
3485 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003486 if (!EatIfPresent(lltok::kw_comdat))
3487 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003488
3489 if (EatIfPresent(lltok::lparen)) {
3490 if (Lex.getKind() != lltok::ComdatVar)
3491 return TokError("expected comdat variable");
3492 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3493 Lex.Lex();
3494 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3495 return true;
3496 } else {
3497 if (GlobalName.empty())
3498 return TokError("comdat cannot be unnamed");
3499 C = getComdat(GlobalName, KwLoc);
3500 }
3501
David Majnemerdad0a642014-06-27 18:19:56 +00003502 return false;
3503}
3504
Victor Hernandez9d75c962010-01-11 22:31:58 +00003505/// ParseGlobalValueVector
3506/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003507/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3508bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3509 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003510 // Empty list.
3511 if (Lex.getKind() == lltok::rbrace ||
3512 Lex.getKind() == lltok::rsquare ||
3513 Lex.getKind() == lltok::greater ||
3514 Lex.getKind() == lltok::rparen)
3515 return false;
3516
Peter Collingbourned93620b2016-11-10 22:34:55 +00003517 do {
3518 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3519 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003520
Peter Collingbourned93620b2016-11-10 22:34:55 +00003521 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003522 if (ParseGlobalTypeAndValue(C)) return true;
3523 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003524 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003525
3526 return false;
3527}
3528
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003529bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003530 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003531 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003532 return true;
3533
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003534 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003535 return false;
3536}
3537
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003538/// MDNode:
3539/// ::= !{ ... }
3540/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003541/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003542bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003543 if (Lex.getKind() == lltok::MetadataVar)
3544 return ParseSpecializedMDNode(N);
3545
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003546 return ParseToken(lltok::exclaim, "expected '!' here") ||
3547 ParseMDNodeTail(N);
3548}
3549
3550bool LLParser::ParseMDNodeTail(MDNode *&N) {
3551 // !{ ... }
3552 if (Lex.getKind() == lltok::lbrace)
3553 return ParseMDTuple(N);
3554
3555 // !42
3556 return ParseMDNodeID(N);
3557}
3558
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003559namespace {
3560
3561/// Structure to represent an optional metadata field.
3562template <class FieldTy> struct MDFieldImpl {
3563 typedef MDFieldImpl ImplTy;
3564 FieldTy Val;
3565 bool Seen;
3566
3567 void assign(FieldTy Val) {
3568 Seen = true;
3569 this->Val = std::move(Val);
3570 }
3571
3572 explicit MDFieldImpl(FieldTy Default)
3573 : Val(std::move(Default)), Seen(false) {}
3574};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003575
Sander de Smalenfdf40912018-01-24 09:56:07 +00003576/// Structure to represent an optional metadata field that
3577/// can be of either type (A or B) and encapsulates the
3578/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3579/// to reimplement the specifics for representing each Field.
3580template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3581 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3582 FieldTypeA A;
3583 FieldTypeB B;
3584 bool Seen;
3585
3586 enum {
3587 IsInvalid = 0,
3588 IsTypeA = 1,
3589 IsTypeB = 2
3590 } WhatIs;
3591
3592 void assign(FieldTypeA A) {
3593 Seen = true;
3594 this->A = std::move(A);
3595 WhatIs = IsTypeA;
3596 }
3597
3598 void assign(FieldTypeB B) {
3599 Seen = true;
3600 this->B = std::move(B);
3601 WhatIs = IsTypeB;
3602 }
3603
3604 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3605 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3606 WhatIs(IsInvalid) {}
3607};
3608
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003609struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3610 uint64_t Max;
3611
3612 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3613 : ImplTy(Default), Max(Max) {}
3614};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003615
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003616struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003617 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003618};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003619
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003620struct ColumnField : public MDUnsignedField {
3621 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3622};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003623
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003624struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003625 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003626 DwarfTagField(dwarf::Tag DefaultTag)
3627 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003628};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003629
Amjad Abouda9bcf162015-12-10 12:56:35 +00003630struct DwarfMacinfoTypeField : public MDUnsignedField {
3631 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3632 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3633 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3634};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003635
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003636struct DwarfAttEncodingField : public MDUnsignedField {
3637 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3638};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003639
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003640struct DwarfVirtualityField : public MDUnsignedField {
3641 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3642};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003643
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003644struct DwarfLangField : public MDUnsignedField {
3645 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3646};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003647
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003648struct DwarfCCField : public MDUnsignedField {
3649 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3650};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003651
Adrian Prantlb939a252016-03-31 23:56:58 +00003652struct EmissionKindField : public MDUnsignedField {
3653 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3654};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003655
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003656struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3657 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003658};
3659
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003660struct MDSignedField : public MDFieldImpl<int64_t> {
3661 int64_t Min;
3662 int64_t Max;
3663
3664 MDSignedField(int64_t Default = 0)
3665 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3666 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3667 : ImplTy(Default), Min(Min), Max(Max) {}
3668};
3669
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003670struct MDBoolField : public MDFieldImpl<bool> {
3671 MDBoolField(bool Default = false) : ImplTy(Default) {}
3672};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003673
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003674struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003675 bool AllowNull;
3676
3677 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003678};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003679
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003680struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3681 MDConstant() : ImplTy(nullptr) {}
3682};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003683
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003684struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003685 bool AllowEmpty;
3686 MDStringField(bool AllowEmpty = true)
3687 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003688};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003689
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003690struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3691 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3692};
3693
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003694struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003695 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3696};
3697
Sander de Smalenfdf40912018-01-24 09:56:07 +00003698struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3699 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3700 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3701
3702 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3703 bool AllowNull = true)
3704 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3705
3706 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3707 bool isMDField() const { return WhatIs == IsTypeB; }
3708 int64_t getMDSignedValue() const {
3709 assert(isMDSignedField() && "Wrong field type");
3710 return A.Val;
3711 }
3712 Metadata *getMDFieldValue() const {
3713 assert(isMDField() && "Wrong field type");
3714 return B.Val;
3715 }
3716};
3717
Momchil Velikov08dc66e2018-02-12 16:10:09 +00003718struct MDSignedOrUnsignedField
3719 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3720 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3721
3722 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3723 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3724 int64_t getMDSignedValue() const {
3725 assert(isMDSignedField() && "Wrong field type");
3726 return A.Val;
3727 }
3728 uint64_t getMDUnsignedValue() const {
3729 assert(isMDUnsignedField() && "Wrong field type");
3730 return B.Val;
3731 }
3732};
3733
Eugene Zelenko1804a772016-08-25 00:45:04 +00003734} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003735
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003736namespace llvm {
3737
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003738template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003739bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003740 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003741 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3742 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003743
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003744 auto &U = Lex.getAPSIntVal();
3745 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003746 return TokError("value for '" + Name + "' too large, limit is " +
3747 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003748 Result.assign(U.getZExtValue());
3749 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003750 Lex.Lex();
3751 return false;
3752}
3753
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003754template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003755bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3756 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3757}
3758template <>
3759bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3760 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3761}
3762
3763template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003764bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3765 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003766 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003767
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003768 if (Lex.getKind() != lltok::DwarfTag)
3769 return TokError("expected DWARF tag");
3770
3771 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3772 if (Tag == dwarf::DW_TAG_invalid)
3773 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003774 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003775
3776 Result.assign(Tag);
3777 Lex.Lex();
3778 return false;
3779}
3780
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003781template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003782bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003783 DwarfMacinfoTypeField &Result) {
3784 if (Lex.getKind() == lltok::APSInt)
3785 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3786
3787 if (Lex.getKind() != lltok::DwarfMacinfo)
3788 return TokError("expected DWARF macinfo type");
3789
3790 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3791 if (Macinfo == dwarf::DW_MACINFO_invalid)
3792 return TokError(
3793 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3794 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3795
3796 Result.assign(Macinfo);
3797 Lex.Lex();
3798 return false;
3799}
3800
3801template <>
3802bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003803 DwarfVirtualityField &Result) {
3804 if (Lex.getKind() == lltok::APSInt)
3805 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3806
3807 if (Lex.getKind() != lltok::DwarfVirtuality)
3808 return TokError("expected DWARF virtuality code");
3809
3810 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003811 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003812 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3813 Lex.getStrVal() + "'");
3814 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3815 Result.assign(Virtuality);
3816 Lex.Lex();
3817 return false;
3818}
3819
3820template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003821bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3822 if (Lex.getKind() == lltok::APSInt)
3823 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3824
3825 if (Lex.getKind() != lltok::DwarfLang)
3826 return TokError("expected DWARF language");
3827
3828 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3829 if (!Lang)
3830 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3831 "'");
3832 assert(Lang <= Result.Max && "Expected valid DWARF language");
3833 Result.assign(Lang);
3834 Lex.Lex();
3835 return false;
3836}
3837
3838template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003839bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3840 if (Lex.getKind() == lltok::APSInt)
3841 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3842
3843 if (Lex.getKind() != lltok::DwarfCC)
3844 return TokError("expected DWARF calling convention");
3845
3846 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3847 if (!CC)
3848 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3849 "'");
3850 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3851 Result.assign(CC);
3852 Lex.Lex();
3853 return false;
3854}
3855
3856template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003857bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3858 if (Lex.getKind() == lltok::APSInt)
3859 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3860
3861 if (Lex.getKind() != lltok::EmissionKind)
3862 return TokError("expected emission kind");
3863
3864 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3865 if (!Kind)
3866 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3867 "'");
3868 assert(*Kind <= Result.Max && "Expected valid emission kind");
3869 Result.assign(*Kind);
3870 Lex.Lex();
3871 return false;
3872}
3873
3874template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003875bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003876 DwarfAttEncodingField &Result) {
3877 if (Lex.getKind() == lltok::APSInt)
3878 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3879
3880 if (Lex.getKind() != lltok::DwarfAttEncoding)
3881 return TokError("expected DWARF type attribute encoding");
3882
3883 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3884 if (!Encoding)
3885 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3886 Lex.getStrVal() + "'");
3887 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3888 Result.assign(Encoding);
3889 Lex.Lex();
3890 return false;
3891}
3892
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003893/// DIFlagField
3894/// ::= uint32
3895/// ::= DIFlagVector
3896/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3897template <>
3898bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003899
3900 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003901 auto parseFlag = [&](DINode::DIFlags &Val) {
3902 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3903 uint32_t TempVal = static_cast<uint32_t>(Val);
3904 bool Res = ParseUInt32(TempVal);
3905 Val = static_cast<DINode::DIFlags>(TempVal);
3906 return Res;
3907 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003908
3909 if (Lex.getKind() != lltok::DIFlag)
3910 return TokError("expected debug info flag");
3911
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003912 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003913 if (!Val)
3914 return TokError(Twine("invalid debug info flag flag '") +
3915 Lex.getStrVal() + "'");
3916 Lex.Lex();
3917 return false;
3918 };
3919
3920 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003921 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003922 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003923 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003924 if (parseFlag(Val))
3925 return true;
3926 Combined |= Val;
3927 } while (EatIfPresent(lltok::bar));
3928
3929 Result.assign(Combined);
3930 return false;
3931}
3932
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003933template <>
3934bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003935 MDSignedField &Result) {
3936 if (Lex.getKind() != lltok::APSInt)
3937 return TokError("expected signed integer");
3938
3939 auto &S = Lex.getAPSIntVal();
3940 if (S < Result.Min)
3941 return TokError("value for '" + Name + "' too small, limit is " +
3942 Twine(Result.Min));
3943 if (S > Result.Max)
3944 return TokError("value for '" + Name + "' too large, limit is " +
3945 Twine(Result.Max));
3946 Result.assign(S.getExtValue());
3947 assert(Result.Val >= Result.Min && "Expected value in range");
3948 assert(Result.Val <= Result.Max && "Expected value in range");
3949 Lex.Lex();
3950 return false;
3951}
3952
3953template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003954bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3955 switch (Lex.getKind()) {
3956 default:
3957 return TokError("expected 'true' or 'false'");
3958 case lltok::kw_true:
3959 Result.assign(true);
3960 break;
3961 case lltok::kw_false:
3962 Result.assign(false);
3963 break;
3964 }
3965 Lex.Lex();
3966 return false;
3967}
3968
3969template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003970bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003971 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003972 if (!Result.AllowNull)
3973 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003974 Lex.Lex();
3975 Result.assign(nullptr);
3976 return false;
3977 }
3978
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003979 Metadata *MD;
3980 if (ParseMetadata(MD, nullptr))
3981 return true;
3982
3983 Result.assign(MD);
3984 return false;
3985}
3986
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003987template <>
Sander de Smalenfdf40912018-01-24 09:56:07 +00003988bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3989 MDSignedOrMDField &Result) {
3990 // Try to parse a signed int.
3991 if (Lex.getKind() == lltok::APSInt) {
3992 MDSignedField Res = Result.A;
3993 if (!ParseMDField(Loc, Name, Res)) {
3994 Result.assign(Res);
3995 return false;
3996 }
3997 return true;
3998 }
3999
4000 // Otherwise, try to parse as an MDField.
4001 MDField Res = Result.B;
4002 if (!ParseMDField(Loc, Name, Res)) {
4003 Result.assign(Res);
4004 return false;
4005 }
4006
4007 return true;
4008}
4009
4010template <>
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004011bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4012 MDSignedOrUnsignedField &Result) {
4013 if (Lex.getKind() != lltok::APSInt)
4014 return false;
4015
4016 if (Lex.getAPSIntVal().isSigned()) {
4017 MDSignedField Res = Result.A;
4018 if (ParseMDField(Loc, Name, Res))
4019 return true;
4020 Result.assign(Res);
4021 return false;
4022 }
4023
4024 MDUnsignedField Res = Result.B;
4025 if (ParseMDField(Loc, Name, Res))
4026 return true;
4027 Result.assign(Res);
4028 return false;
4029}
4030
4031template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004032bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004033 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004034 std::string S;
4035 if (ParseStringConstant(S))
4036 return true;
4037
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004038 if (!Result.AllowEmpty && S.empty())
4039 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4040
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00004041 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004042 return false;
4043}
4044
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00004045template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004046bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4047 SmallVector<Metadata *, 4> MDs;
4048 if (ParseMDNodeVector(MDs))
4049 return true;
4050
4051 Result.assign(std::move(MDs));
4052 return false;
4053}
4054
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004055template <>
4056bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4057 ChecksumKindField &Result) {
Scott Linder71603842018-02-12 19:45:54 +00004058 Optional<DIFile::ChecksumKind> CSKind =
4059 DIFile::getChecksumKind(Lex.getStrVal());
4060
4061 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004062 return TokError(
4063 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4064
Scott Linder71603842018-02-12 19:45:54 +00004065 Result.assign(*CSKind);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004066 Lex.Lex();
4067 return false;
4068}
4069
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00004070} // end namespace llvm
4071
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004072template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004073bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004074 do {
4075 if (Lex.getKind() != lltok::LabelStr)
4076 return TokError("expected field label here");
4077
4078 if (parseField())
4079 return true;
4080 } while (EatIfPresent(lltok::comma));
4081
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00004082 return false;
4083}
4084
4085template <class ParserTy>
4086bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4087 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4088 Lex.Lex();
4089
4090 if (ParseToken(lltok::lparen, "expected '(' here"))
4091 return true;
4092 if (Lex.getKind() != lltok::rparen)
4093 if (ParseMDFieldsImplBody(parseField))
4094 return true;
4095
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00004096 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004097 return ParseToken(lltok::rparen, "expected ')' here");
4098}
4099
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004100template <class FieldTy>
4101bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4102 if (Result.Seen)
4103 return TokError("field '" + Name + "' cannot be specified more than once");
4104
4105 LocTy Loc = Lex.getLoc();
4106 Lex.Lex();
4107 return ParseMDField(Loc, Name, Result);
4108}
4109
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004110bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4111 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004112
4113#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004114 if (Lex.getStrVal() == #CLASS) \
4115 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004116#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004117
4118 return TokError("expected metadata type");
4119}
4120
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004121#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4122#define NOP_FIELD(NAME, TYPE, INIT)
4123#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4124 if (!NAME.Seen) \
4125 return Error(ClosingLoc, "missing required field '" #NAME "'");
4126#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00004127 if (Lex.getStrVal() == #NAME) \
4128 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004129#define PARSE_MD_FIELDS() \
4130 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4131 do { \
4132 LocTy ClosingLoc; \
4133 if (ParseMDFieldsImpl([&]() -> bool { \
4134 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4135 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4136 }, ClosingLoc)) \
4137 return true; \
4138 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4139 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004140#define GET_OR_DISTINCT(CLASS, ARGS) \
4141 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143/// ParseDILocationFields:
4144/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4145bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004146#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00004147 OPTIONAL(line, LineField, ); \
4148 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004149 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004150 OPTIONAL(inlinedAt, MDField, );
4151 PARSE_MD_FIELDS();
4152#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004153
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00004154 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004155 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004156 return false;
4157}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004158
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004159/// ParseGenericDINode:
4160/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4161bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004162#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00004163 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004164 OPTIONAL(header, MDStringField, ); \
4165 OPTIONAL(operands, MDFieldList, );
4166 PARSE_MD_FIELDS();
4167#undef VISIT_MD_FIELDS
4168
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004169 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00004170 (Context, tag.Val, header.Val, operands.Val));
4171 return false;
4172}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004173
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004174/// ParseDISubrange:
4175/// ::= !DISubrange(count: 30, lowerBound: 2)
Sander de Smalenfdf40912018-01-24 09:56:07 +00004176/// ::= !DISubrange(count: !node, lowerBound: 2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004177bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004178#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Sander de Smalenfdf40912018-01-24 09:56:07 +00004179 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004180 OPTIONAL(lowerBound, MDSignedField, );
4181 PARSE_MD_FIELDS();
4182#undef VISIT_MD_FIELDS
4183
Sander de Smalenfdf40912018-01-24 09:56:07 +00004184 if (count.isMDSignedField())
4185 Result = GET_OR_DISTINCT(
4186 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4187 else if (count.isMDField())
4188 Result = GET_OR_DISTINCT(
4189 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4190 else
4191 return true;
4192
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004193 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004194}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00004195
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004196/// ParseDIEnumerator:
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004197/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004198bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004199#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00004200 REQUIRED(name, MDStringField, ); \
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004201 REQUIRED(value, MDSignedOrUnsignedField, ); \
4202 OPTIONAL(isUnsigned, MDBoolField, (false));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004203 PARSE_MD_FIELDS();
4204#undef VISIT_MD_FIELDS
4205
Momchil Velikov08dc66e2018-02-12 16:10:09 +00004206 if (isUnsigned.Val && value.isMDSignedField())
4207 return TokError("unsigned enumerator with negative value");
4208
4209 int64_t Value = value.isMDSignedField()
4210 ? value.getMDSignedValue()
4211 : static_cast<int64_t>(value.getMDUnsignedValue());
4212 Result =
4213 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4214
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004215 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004216}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004217
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004218/// ParseDIBasicType:
4219/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4220bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004221#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004222 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004223 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004224 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004225 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004226 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004227 PARSE_MD_FIELDS();
4228#undef VISIT_MD_FIELDS
4229
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004230 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004231 align.Val, encoding.Val));
4232 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004233}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004234
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004235/// ParseDIDerivedType:
4236/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004237/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004238/// align: 32, offset: 0, flags: 0, extraData: !3,
4239/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004240bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004241#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4242 REQUIRED(tag, DwarfTagField, ); \
4243 OPTIONAL(name, MDStringField, ); \
4244 OPTIONAL(file, MDField, ); \
4245 OPTIONAL(line, LineField, ); \
4246 OPTIONAL(scope, MDField, ); \
4247 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004248 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004249 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004250 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004251 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004252 OPTIONAL(extraData, MDField, ); \
4253 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004254 PARSE_MD_FIELDS();
4255#undef VISIT_MD_FIELDS
4256
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004257 Optional<unsigned> DWARFAddressSpace;
4258 if (dwarfAddressSpace.Val != UINT32_MAX)
4259 DWARFAddressSpace = dwarfAddressSpace.Val;
4260
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004261 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004262 (Context, tag.Val, name.Val, file.Val, line.Val,
4263 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004264 offset.Val, DWARFAddressSpace, flags.Val,
4265 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004266 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004267}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004268
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004269bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004270#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4271 REQUIRED(tag, DwarfTagField, ); \
4272 OPTIONAL(name, MDStringField, ); \
4273 OPTIONAL(file, MDField, ); \
4274 OPTIONAL(line, LineField, ); \
4275 OPTIONAL(scope, MDField, ); \
4276 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004277 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004278 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004279 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004280 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004281 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004282 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004283 OPTIONAL(vtableHolder, MDField, ); \
4284 OPTIONAL(templateParams, MDField, ); \
Adrian Prantl8c599212018-02-06 23:45:59 +00004285 OPTIONAL(identifier, MDStringField, ); \
4286 OPTIONAL(discriminator, MDField, );
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004287 PARSE_MD_FIELDS();
4288#undef VISIT_MD_FIELDS
4289
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004290 // If this has an identifier try to build an ODR type.
4291 if (identifier.Val)
4292 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004293 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4294 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4295 elements.Val, runtimeLang.Val, vtableHolder.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004296 templateParams.Val, discriminator.Val)) {
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004297 Result = CT;
4298 return false;
4299 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004300
4301 // Create a new node, and save it in the context if it belongs in the type
4302 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004303 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004304 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004305 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4306 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
Adrian Prantl8c599212018-02-06 23:45:59 +00004307 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4308 discriminator.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004309 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004310}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004311
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004312bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004313#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004314 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004315 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004316 REQUIRED(types, MDField, );
4317 PARSE_MD_FIELDS();
4318#undef VISIT_MD_FIELDS
4319
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004320 Result = GET_OR_DISTINCT(DISubroutineType,
4321 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004322 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004323}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004324
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004325/// ParseDIFileType:
Scott Linder16c7bda2018-02-23 23:01:06 +00004326/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004327/// checksumkind: CSK_MD5,
Scott Linder16c7bda2018-02-23 23:01:06 +00004328/// checksum: "000102030405060708090a0b0c0d0e0f",
4329/// source: "source file contents")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004330bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Scott Linder71603842018-02-12 19:45:54 +00004331 // The default constructed value for checksumkind is required, but will never
4332 // be used, as the parser checks if the field was actually Seen before using
4333 // the Val.
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004334#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4335 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004336 REQUIRED(directory, MDStringField, ); \
Scott Linder71603842018-02-12 19:45:54 +00004337 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
Scott Linder16c7bda2018-02-23 23:01:06 +00004338 OPTIONAL(checksum, MDStringField, ); \
4339 OPTIONAL(source, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004340 PARSE_MD_FIELDS();
4341#undef VISIT_MD_FIELDS
4342
Scott Linder71603842018-02-12 19:45:54 +00004343 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4344 if (checksumkind.Seen && checksum.Seen)
4345 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4346 else if (checksumkind.Seen || checksum.Seen)
4347 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4348
Scott Linder16c7bda2018-02-23 23:01:06 +00004349 Optional<MDString *> OptSource;
4350 if (source.Seen)
4351 OptSource = source.Val;
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004352 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
Scott Linder16c7bda2018-02-23 23:01:06 +00004353 OptChecksum, OptSource));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004354 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004355}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004356
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004357/// ParseDICompileUnit:
4358/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004359/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004360/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004361/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004362/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004363bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004364 if (!IsDistinct)
4365 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4366
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004367#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4368 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004369 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004370 OPTIONAL(producer, MDStringField, ); \
4371 OPTIONAL(isOptimized, MDBoolField, ); \
4372 OPTIONAL(flags, MDStringField, ); \
4373 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4374 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004375 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004376 OPTIONAL(enums, MDField, ); \
4377 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004378 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004379 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004380 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004381 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004382 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004383 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4384 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004385 PARSE_MD_FIELDS();
4386#undef VISIT_MD_FIELDS
4387
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004388 Result = DICompileUnit::getDistinct(
4389 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4390 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004391 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004392 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004393 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004394}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004395
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004396/// ParseDISubprogram:
4397/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004398/// file: !1, line: 7, type: !2, isLocal: false,
4399/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004400/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004401/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004402/// isOptimized: false, templateParams: !4, declaration: !5,
Shiva Chen2c864552018-05-09 02:40:45 +00004403/// retainedNodes: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004404bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004405 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004406#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4407 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004408 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004409 OPTIONAL(linkageName, MDStringField, ); \
4410 OPTIONAL(file, MDField, ); \
4411 OPTIONAL(line, LineField, ); \
4412 OPTIONAL(type, MDField, ); \
4413 OPTIONAL(isLocal, MDBoolField, ); \
4414 OPTIONAL(isDefinition, MDBoolField, (true)); \
4415 OPTIONAL(scopeLine, LineField, ); \
4416 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004417 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004418 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004419 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004420 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004421 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004422 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004423 OPTIONAL(templateParams, MDField, ); \
4424 OPTIONAL(declaration, MDField, ); \
Shiva Chen2c864552018-05-09 02:40:45 +00004425 OPTIONAL(retainedNodes, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004426 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004427 PARSE_MD_FIELDS();
4428#undef VISIT_MD_FIELDS
4429
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004430 if (isDefinition.Val && !IsDistinct)
4431 return Lex.Error(
4432 Loc,
4433 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4434
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004435 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004436 DISubprogram,
4437 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4438 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4439 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4440 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
Shiva Chen2c864552018-05-09 02:40:45 +00004441 declaration.Val, retainedNodes.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004442 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004443}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004444
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004445/// ParseDILexicalBlock:
4446/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4447bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004448#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004449 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004450 OPTIONAL(file, MDField, ); \
4451 OPTIONAL(line, LineField, ); \
4452 OPTIONAL(column, ColumnField, );
4453 PARSE_MD_FIELDS();
4454#undef VISIT_MD_FIELDS
4455
4456 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004457 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004458 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004459}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004460
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004461/// ParseDILexicalBlockFile:
4462/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4463bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004464#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004465 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004466 OPTIONAL(file, MDField, ); \
4467 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4468 PARSE_MD_FIELDS();
4469#undef VISIT_MD_FIELDS
4470
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004471 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004472 (Context, scope.Val, file.Val, discriminator.Val));
4473 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004474}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004475
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004476/// ParseDINamespace:
4477/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4478bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004479#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4480 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004481 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004482 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004483 PARSE_MD_FIELDS();
4484#undef VISIT_MD_FIELDS
4485
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004486 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004487 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004488 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004489}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004490
Amjad Abouda9bcf162015-12-10 12:56:35 +00004491/// ParseDIMacro:
4492/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4493bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4494#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4495 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004496 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004497 REQUIRED(name, MDStringField, ); \
4498 OPTIONAL(value, MDStringField, );
4499 PARSE_MD_FIELDS();
4500#undef VISIT_MD_FIELDS
4501
4502 Result = GET_OR_DISTINCT(DIMacro,
4503 (Context, type.Val, line.Val, name.Val, value.Val));
4504 return false;
4505}
4506
4507/// ParseDIMacroFile:
4508/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4509bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4510#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4511 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004512 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004513 REQUIRED(file, MDField, ); \
4514 OPTIONAL(nodes, MDField, );
4515 PARSE_MD_FIELDS();
4516#undef VISIT_MD_FIELDS
4517
4518 Result = GET_OR_DISTINCT(DIMacroFile,
4519 (Context, type.Val, line.Val, file.Val, nodes.Val));
4520 return false;
4521}
4522
Adrian Prantlab1243f2015-06-29 23:03:47 +00004523/// ParseDIModule:
4524/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4525/// includePath: "/usr/include", isysroot: "/")
4526bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4528 REQUIRED(scope, MDField, ); \
4529 REQUIRED(name, MDStringField, ); \
4530 OPTIONAL(configMacros, MDStringField, ); \
4531 OPTIONAL(includePath, MDStringField, ); \
4532 OPTIONAL(isysroot, MDStringField, );
4533 PARSE_MD_FIELDS();
4534#undef VISIT_MD_FIELDS
4535
4536 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4537 configMacros.Val, includePath.Val, isysroot.Val));
4538 return false;
4539}
4540
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004541/// ParseDITemplateTypeParameter:
4542/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4543bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004544#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004545 OPTIONAL(name, MDStringField, ); \
4546 REQUIRED(type, MDField, );
4547 PARSE_MD_FIELDS();
4548#undef VISIT_MD_FIELDS
4549
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004550 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004551 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004552 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004553}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004554
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004555/// ParseDITemplateValueParameter:
4556/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004557/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004558bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004559#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004560 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004561 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004562 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004563 REQUIRED(value, MDField, );
4564 PARSE_MD_FIELDS();
4565#undef VISIT_MD_FIELDS
4566
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004567 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004568 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004569 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004570}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004571
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004572/// ParseDIGlobalVariable:
4573/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004574/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004575/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004576bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004577#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004578 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004579 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004580 OPTIONAL(linkageName, MDStringField, ); \
4581 OPTIONAL(file, MDField, ); \
4582 OPTIONAL(line, LineField, ); \
4583 OPTIONAL(type, MDField, ); \
4584 OPTIONAL(isLocal, MDBoolField, ); \
4585 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004586 OPTIONAL(declaration, MDField, ); \
4587 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004588 PARSE_MD_FIELDS();
4589#undef VISIT_MD_FIELDS
4590
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004591 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004592 (Context, scope.Val, name.Val, linkageName.Val,
4593 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004594 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004595 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004596}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004597
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004598/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004599/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004600/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4601/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004602/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004603/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4604/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004605bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004606#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004607 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004608 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004609 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004610 OPTIONAL(file, MDField, ); \
4611 OPTIONAL(line, LineField, ); \
4612 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004613 OPTIONAL(flags, DIFlagField, ); \
4614 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004615 PARSE_MD_FIELDS();
4616#undef VISIT_MD_FIELDS
4617
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004618 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004619 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004620 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004621 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004622}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004623
Shiva Chen2c864552018-05-09 02:40:45 +00004624/// ParseDILabel:
4625/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4626bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4627#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4628 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4629 REQUIRED(name, MDStringField, ); \
4630 REQUIRED(file, MDField, ); \
4631 REQUIRED(line, LineField, );
4632 PARSE_MD_FIELDS();
4633#undef VISIT_MD_FIELDS
4634
4635 Result = GET_OR_DISTINCT(DILabel,
4636 (Context, scope.Val, name.Val, file.Val, line.Val));
4637 return false;
4638}
4639
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004640/// ParseDIExpression:
4641/// ::= !DIExpression(0, 7, -1)
4642bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004643 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4644 Lex.Lex();
4645
4646 if (ParseToken(lltok::lparen, "expected '(' here"))
4647 return true;
4648
4649 SmallVector<uint64_t, 8> Elements;
4650 if (Lex.getKind() != lltok::rparen)
4651 do {
4652 if (Lex.getKind() == lltok::DwarfOp) {
4653 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4654 Lex.Lex();
4655 Elements.push_back(Op);
4656 continue;
4657 }
4658 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4659 }
4660
4661 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4662 return TokError("expected unsigned integer");
4663
4664 auto &U = Lex.getAPSIntVal();
4665 if (U.ugt(UINT64_MAX))
4666 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4667 Elements.push_back(U.getZExtValue());
4668 Lex.Lex();
4669 } while (EatIfPresent(lltok::comma));
4670
4671 if (ParseToken(lltok::rparen, "expected ')' here"))
4672 return true;
4673
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004674 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004675 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004676}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004677
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004678/// ParseDIGlobalVariableExpression:
4679/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4680bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4681 bool IsDistinct) {
4682#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4683 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004684 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004685 PARSE_MD_FIELDS();
4686#undef VISIT_MD_FIELDS
4687
4688 Result =
4689 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4690 return false;
4691}
4692
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004693/// ParseDIObjCProperty:
4694/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004695/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004696bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004698 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004699 OPTIONAL(file, MDField, ); \
4700 OPTIONAL(line, LineField, ); \
4701 OPTIONAL(setter, MDStringField, ); \
4702 OPTIONAL(getter, MDStringField, ); \
4703 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4704 OPTIONAL(type, MDField, );
4705 PARSE_MD_FIELDS();
4706#undef VISIT_MD_FIELDS
4707
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004708 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004709 (Context, name.Val, file.Val, line.Val, setter.Val,
4710 getter.Val, attributes.Val, type.Val));
4711 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004712}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004713
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004714/// ParseDIImportedEntity:
4715/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004716/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004717bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004718#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4719 REQUIRED(tag, DwarfTagField, ); \
4720 REQUIRED(scope, MDField, ); \
4721 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004722 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004723 OPTIONAL(line, LineField, ); \
4724 OPTIONAL(name, MDStringField, );
4725 PARSE_MD_FIELDS();
4726#undef VISIT_MD_FIELDS
4727
Adrian Prantld63bfd22017-07-19 00:09:54 +00004728 Result = GET_OR_DISTINCT(
4729 DIImportedEntity,
4730 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004731 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004732}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004733
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004734#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004735#undef NOP_FIELD
4736#undef REQUIRE_FIELD
4737#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004738
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004739/// ParseMetadataAsValue
4740/// ::= metadata i32 %local
4741/// ::= metadata i32 @global
4742/// ::= metadata i32 7
4743/// ::= metadata !0
4744/// ::= metadata !{...}
4745/// ::= metadata !"string"
4746bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4747 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004748 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004749 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004750 return true;
4751
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004752 V = MetadataAsValue::get(Context, MD);
4753 return false;
4754}
4755
4756/// ParseValueAsMetadata
4757/// ::= i32 %local
4758/// ::= i32 @global
4759/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004760bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4761 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004762 Type *Ty;
4763 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004764 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004765 return true;
4766 if (Ty->isMetadataTy())
4767 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4768
4769 Value *V;
4770 if (ParseValue(Ty, V, PFS))
4771 return true;
4772
4773 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004774 return false;
4775}
4776
4777/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004778/// ::= i32 %local
4779/// ::= i32 @global
4780/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004781/// ::= !42
4782/// ::= !{...}
4783/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004784/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004785bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004786 if (Lex.getKind() == lltok::MetadataVar) {
4787 MDNode *N;
4788 if (ParseSpecializedMDNode(N))
4789 return true;
4790 MD = N;
4791 return false;
4792 }
4793
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004794 // ValueAsMetadata:
4795 // <type> <value>
4796 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004797 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004798
4799 // '!'.
4800 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4801 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004802
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004803 // MDString:
4804 // ::= '!' STRINGCONSTANT
4805 if (Lex.getKind() == lltok::StringConstant) {
4806 MDString *S;
4807 if (ParseMDString(S))
4808 return true;
4809 MD = S;
4810 return false;
4811 }
4812
Dan Gohman8939ba332010-07-14 18:26:50 +00004813 // MDNode:
4814 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004815 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004816 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004817 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004818 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004819 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004820 return false;
4821}
4822
Victor Hernandez9d75c962010-01-11 22:31:58 +00004823//===----------------------------------------------------------------------===//
4824// Function Parsing.
4825//===----------------------------------------------------------------------===//
4826
Chris Lattner229907c2011-07-18 04:54:35 +00004827bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004828 PerFunctionState *PFS, bool IsCall) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004829 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004831
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004834 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004835 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004836 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004838 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004839 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
Craig Topper2617dcc2014-04-15 06:32:26 +00004840 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004841 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004842 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004843 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004844 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4845 (ID.UIntVal >> 1) & 1,
4846 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004847 return false;
4848 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 case ValID::t_GlobalName:
4850 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004851 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004852 case ValID::t_GlobalID:
4853 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004854 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004856 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004857 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004858 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004859 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 return false;
4861 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004862 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004863 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4864 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004865
Dan Gohman518cda42011-12-17 00:04:22 +00004866 // The lexer has no type info, so builds all half, float, and double FP
4867 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004868 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004869 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004870 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004871 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004872 &Ignored);
4873 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004874 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004875 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004876 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004877 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004878
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004879 if (V->getType() != Ty)
4880 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004881 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004882
Chris Lattnerac161bf2009-01-02 07:01:27 +00004883 return false;
4884 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004885 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004886 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004887 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004888 return false;
4889 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004890 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004891 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004892 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004893 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004895 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004896 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004897 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004898 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004899 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004900 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004901 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004902 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004903 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004904 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004906 case ValID::t_None:
4907 if (!Ty->isTokenTy())
4908 return Error(ID.Loc, "invalid type for none constant");
4909 V = Constant::getNullValue(Ty);
4910 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004911 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004912 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004914
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 V = ID.ConstantVal;
4916 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004917 case ValID::t_ConstantStruct:
4918 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004919 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004920 if (ST->getNumElements() != ID.UIntVal)
4921 return Error(ID.Loc,
4922 "initializer with struct type has wrong # elements");
4923 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4924 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004925
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004926 // Verify that the elements are compatible with the structtype.
4927 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4928 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4929 return Error(ID.Loc, "element " + Twine(i) +
4930 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004931
David Blaikieadbda4b2015-08-03 20:08:41 +00004932 V = ConstantStruct::get(
4933 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004934 } else
4935 return Error(ID.Loc, "constant expression type mismatch");
4936 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004937 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004938 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004939}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Alex Lorenzd2255952015-07-17 22:07:03 +00004941bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4942 C = nullptr;
4943 ValID ID;
4944 auto Loc = Lex.getLoc();
4945 if (ParseValID(ID, /*PFS=*/nullptr))
4946 return true;
4947 switch (ID.Kind) {
4948 case ValID::t_APSInt:
4949 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004950 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004951 case ValID::t_Constant:
4952 case ValID::t_ConstantStruct:
4953 case ValID::t_PackedConstantStruct: {
4954 Value *V;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004955 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
Alex Lorenzd2255952015-07-17 22:07:03 +00004956 return true;
4957 assert(isa<Constant>(V) && "Expected a constant value");
4958 C = cast<Constant>(V);
4959 return false;
4960 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004961 case ValID::t_Null:
4962 C = Constant::getNullValue(Ty);
4963 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004964 default:
4965 return Error(Loc, "expected a constant value");
4966 }
4967}
4968
David Majnemer8a1c45d2015-12-12 05:38:55 +00004969bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004970 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 ValID ID;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00004972 return ParseValID(ID, PFS) ||
4973 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004974}
4975
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004976bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004977 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004978 return ParseType(Ty) ||
4979 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004980}
4981
Chris Lattner3ed871f2009-10-27 19:13:16 +00004982bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4983 PerFunctionState &PFS) {
4984 Value *V;
4985 Loc = Lex.getLoc();
4986 if (ParseTypeAndValue(V, PFS)) return true;
4987 if (!isa<BasicBlock>(V))
4988 return Error(Loc, "expected a basic block");
4989 BB = cast<BasicBlock>(V);
4990 return false;
4991}
4992
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00004994/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4995/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4996/// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4997/// OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4999 // Parse the linkage.
5000 LocTy LinkageLoc = Lex.getLoc();
5001 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00005002 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00005003 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00005004 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00005005 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005006 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005007 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00005008 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00005010 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5011 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00005012 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005013 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 return true;
5015
5016 // Verify that the linkage is ok.
5017 switch ((GlobalValue::LinkageTypes)Linkage) {
5018 case GlobalValue::ExternalLinkage:
5019 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00005020 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 if (isDefine)
5022 return Error(LinkageLoc, "invalid linkage for function definition");
5023 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00005024 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005025 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00005026 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00005027 case GlobalValue::LinkOnceAnyLinkage:
5028 case GlobalValue::LinkOnceODRLinkage:
5029 case GlobalValue::WeakAnyLinkage:
5030 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031 if (!isDefine)
5032 return Error(LinkageLoc, "invalid linkage for function declaration");
5033 break;
5034 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00005035 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 return Error(LinkageLoc, "invalid function linkage type");
5037 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005038
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00005039 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5040 return Error(LinkageLoc,
5041 "symbol with local linkage must have default visibility");
5042
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005043 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005044 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005045
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00005047
5048 std::string FunctionName;
5049 if (Lex.getKind() == lltok::GlobalVar) {
5050 FunctionName = Lex.getStrVal();
5051 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5052 unsigned NameID = Lex.getUIntVal();
5053
5054 if (NameID != NumberedVals.size())
5055 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005056 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00005057 } else {
5058 return TokError("expected function name");
5059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005060
Chris Lattner3822f632009-01-02 08:05:26 +00005061 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005062
Chris Lattner3822f632009-01-02 08:05:26 +00005063 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005065
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005066 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005067 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00005068 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005069 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005070 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005071 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00005073 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005074 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Craig Topper2617dcc2014-04-15 06:32:26 +00005075 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005076 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00005077 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00005078 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00005079
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005080 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00005081 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005082 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005083 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005084 (EatIfPresent(lltok::kw_section) &&
5085 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00005086 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00005087 ParseOptionalAlignment(Alignment) ||
5088 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005089 ParseStringConstant(GC)) ||
5090 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005091 ParseGlobalTypeAndValue(Prefix)) ||
5092 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00005093 ParseGlobalTypeAndValue(Prologue)) ||
5094 (EatIfPresent(lltok::kw_personality) &&
5095 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00005096 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005097
Michael Gottesman41748d72013-06-27 00:25:01 +00005098 if (FuncAttrs.contains(Attribute::Builtin))
5099 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00005100
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00005102 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00005103 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005104 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005105 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005106
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 // Okay, if we got here, the function is syntactically valid. Convert types
5108 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00005109 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005110 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005111
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005113 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005114 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005115 }
5116
Reid Kleckner7f720332017-04-13 00:58:09 +00005117 AttributeList PAL =
5118 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5119 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005120
Bill Wendling749a43d2012-12-30 13:50:49 +00005121 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005122 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5123
Chris Lattner229907c2011-07-18 04:54:35 +00005124 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00005125 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00005126 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005127
Craig Topper2617dcc2014-04-15 06:32:26 +00005128 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 if (!FunctionName.empty()) {
5130 // If this was a definition of a forward reference, remove the definition
5131 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00005132 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 if (FRVI != ForwardRefVals.end()) {
5134 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00005135 if (!Fn)
5136 return Error(FRVI->second.second, "invalid forward reference to "
5137 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00005138 if (Fn->getType() != PFT)
5139 return Error(FRVI->second.second, "invalid forward reference to "
5140 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005141
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 ForwardRefVals.erase(FRVI);
5143 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00005144 // Reject redefinitions.
5145 return Error(NameLoc, "invalid redefinition of function '" +
5146 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00005147 } else if (M->getNamedValue(FunctionName)) {
5148 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005149 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005150
Dan Gohman399d6ae2009-08-29 23:37:49 +00005151 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005152 // If this is a definition of a forward referenced function, make sure the
5153 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00005154 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005155 if (I != ForwardRefValIDs.end()) {
5156 Fn = cast<Function>(I->second.first);
5157 if (Fn->getType() != PFT)
5158 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00005159 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005160 ForwardRefValIDs.erase(I);
5161 }
5162 }
5163
Craig Topper2617dcc2014-04-15 06:32:26 +00005164 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005165 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
5166 else // Move the forward-reference to the correct spot in the module.
5167 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5168
5169 if (FunctionName.empty())
5170 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005171
Chris Lattnerac161bf2009-01-02 07:01:27 +00005172 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Rafael Espindolae4b02312018-01-11 22:15:05 +00005173 maybeSetDSOLocal(DSOLocal, *Fn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005174 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00005175 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 Fn->setCallingConv(CC);
5177 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00005178 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005179 Fn->setAlignment(Alignment);
5180 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00005181 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00005182 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00005183 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00005184 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00005185 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005186 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005187
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 // Add all of the arguments we parsed to the function.
5189 Function::arg_iterator ArgIt = Fn->arg_begin();
5190 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5191 // If the argument has a name, insert it into the argument symbol table.
5192 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005193
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 // Set the name, if it conflicted, it will be auto-renamed.
5195 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005196
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00005197 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5199 ArgList[i].Name + "'");
5200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005201
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005202 if (isDefine)
5203 return false;
5204
Robin Morisset039781e2014-08-29 21:53:01 +00005205 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005206 ValID ID;
5207 if (FunctionName.empty()) {
5208 ID.Kind = ValID::t_GlobalID;
5209 ID.UIntVal = NumberedVals.size() - 1;
5210 } else {
5211 ID.Kind = ValID::t_GlobalName;
5212 ID.StrVal = FunctionName;
5213 }
5214 auto Blocks = ForwardRefBlockAddresses.find(ID);
5215 if (Blocks != ForwardRefBlockAddresses.end())
5216 return Error(Blocks->first.Loc,
5217 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 return false;
5219}
5220
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005221bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5222 ValID ID;
5223 if (FunctionNumber == -1) {
5224 ID.Kind = ValID::t_GlobalName;
5225 ID.StrVal = F.getName();
5226 } else {
5227 ID.Kind = ValID::t_GlobalID;
5228 ID.UIntVal = FunctionNumber;
5229 }
5230
5231 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5232 if (Blocks == P.ForwardRefBlockAddresses.end())
5233 return false;
5234
5235 for (const auto &I : Blocks->second) {
5236 const ValID &BBID = I.first;
5237 GlobalValue *GV = I.second;
5238
5239 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5240 "Expected local id or name");
5241 BasicBlock *BB;
5242 if (BBID.Kind == ValID::t_LocalName)
5243 BB = GetBB(BBID.StrVal, BBID.Loc);
5244 else
5245 BB = GetBB(BBID.UIntVal, BBID.Loc);
5246 if (!BB)
5247 return P.Error(BBID.Loc, "referenced value is not a basic block");
5248
5249 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5250 GV->eraseFromParent();
5251 }
5252
5253 P.ForwardRefBlockAddresses.erase(Blocks);
5254 return false;
5255}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256
5257/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005258/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005259bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005260 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005261 return TokError("expected '{' in function body");
5262 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005263
Chris Lattner3432c622009-10-28 03:39:23 +00005264 int FunctionNumber = -1;
5265 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005266
Chris Lattner3432c622009-10-28 03:39:23 +00005267 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005268
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005269 // Resolve block addresses and allow basic blocks to be forward-declared
5270 // within this function.
5271 if (PFS.resolveForwardRefBlockAddresses())
5272 return true;
5273 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5274
Chris Lattnerbbddd962010-01-09 19:20:07 +00005275 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005276 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005277 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005278
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005279 while (Lex.getKind() != lltok::rbrace &&
5280 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005281 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005283 while (Lex.getKind() != lltok::rbrace)
5284 if (ParseUseListOrder(&PFS))
5285 return true;
5286
Chris Lattnerac161bf2009-01-02 07:01:27 +00005287 // Eat the }.
5288 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005289
Chris Lattnerac161bf2009-01-02 07:01:27 +00005290 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005291 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005292}
5293
5294/// ParseBasicBlock
5295/// ::= LabelStr? Instruction*
5296bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5297 // If this basic block starts out with a name, remember it.
5298 std::string Name;
5299 LocTy NameLoc = Lex.getLoc();
5300 if (Lex.getKind() == lltok::LabelStr) {
5301 Name = Lex.getStrVal();
5302 Lex.Lex();
5303 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005304
Chris Lattnerac161bf2009-01-02 07:01:27 +00005305 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005306 if (!BB)
5307 return Error(NameLoc,
5308 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005309
Chris Lattnerac161bf2009-01-02 07:01:27 +00005310 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005311
Chris Lattnerac161bf2009-01-02 07:01:27 +00005312 // Parse the instructions in this block until we get a terminator.
5313 Instruction *Inst;
5314 do {
5315 // This instruction may have three possibilities for a name: a) none
5316 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5317 LocTy NameLoc = Lex.getLoc();
5318 int NameID = -1;
5319 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005320
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321 if (Lex.getKind() == lltok::LocalVarID) {
5322 NameID = Lex.getUIntVal();
5323 Lex.Lex();
5324 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5325 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005326 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327 NameStr = Lex.getStrVal();
5328 Lex.Lex();
5329 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5330 return true;
5331 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005332
Chris Lattner77b89dc2009-12-30 05:23:43 +00005333 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005334 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005335 case InstError: return true;
5336 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005337 BB->getInstList().push_back(Inst);
5338
Chris Lattner77b89dc2009-12-30 05:23:43 +00005339 // With a normal result, we check to see if the instruction is followed by
5340 // a comma and metadata.
5341 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005342 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005343 return true;
5344 break;
5345 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005346 BB->getInstList().push_back(Inst);
5347
Chris Lattner77b89dc2009-12-30 05:23:43 +00005348 // If the instruction parser ate an extra comma at the end of it, it
5349 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005350 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005351 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005352 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005353 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005354
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355 // Set the name on the instruction.
5356 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5357 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359 return false;
5360}
5361
5362//===----------------------------------------------------------------------===//
5363// Instruction Parsing.
5364//===----------------------------------------------------------------------===//
5365
5366/// ParseInstruction - Parse one of the many different instructions.
5367///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005368int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5369 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005370 lltok::Kind Token = Lex.getKind();
5371 if (Token == lltok::Eof)
5372 return TokError("found end of file when expecting more instructions");
5373 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005374 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005376
Chris Lattnerac161bf2009-01-02 07:01:27 +00005377 switch (Token) {
5378 default: return Error(Loc, "expected instruction opcode");
5379 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005380 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5382 case lltok::kw_br: return ParseBr(Inst, PFS);
5383 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005384 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005386 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005387 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5388 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005389 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5390 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005391 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005392 // Binary Operators.
5393 case lltok::kw_add:
5394 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005395 case lltok::kw_mul:
5396 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005397 bool NUW = EatIfPresent(lltok::kw_nuw);
5398 bool NSW = EatIfPresent(lltok::kw_nsw);
5399 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005400
Chris Lattnera676c0f2011-02-07 16:40:21 +00005401 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005402
Chris Lattnera676c0f2011-02-07 16:40:21 +00005403 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5404 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5405 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005406 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005407 case lltok::kw_fadd:
5408 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005409 case lltok::kw_fmul:
5410 case lltok::kw_fdiv:
5411 case lltok::kw_frem: {
5412 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5413 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5414 if (Res != 0)
5415 return Res;
5416 if (FMF.any())
5417 Inst->setFastMathFlags(FMF);
5418 return 0;
5419 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005420
Chris Lattner35315d02011-02-06 21:44:57 +00005421 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005422 case lltok::kw_udiv:
5423 case lltok::kw_lshr:
5424 case lltok::kw_ashr: {
5425 bool Exact = EatIfPresent(lltok::kw_exact);
5426
5427 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5428 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5429 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005430 }
5431
Chris Lattnerac161bf2009-01-02 07:01:27 +00005432 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005433 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434 case lltok::kw_and:
5435 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005436 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005437 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5438 case lltok::kw_fcmp: {
5439 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5440 int Res = ParseCompare(Inst, PFS, KeywordVal);
5441 if (Res != 0)
5442 return Res;
5443 if (FMF.any())
5444 Inst->setFastMathFlags(FMF);
5445 return 0;
5446 }
5447
Chris Lattnerac161bf2009-01-02 07:01:27 +00005448 // Casts.
5449 case lltok::kw_trunc:
5450 case lltok::kw_zext:
5451 case lltok::kw_sext:
5452 case lltok::kw_fptrunc:
5453 case lltok::kw_fpext:
5454 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005455 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005456 case lltok::kw_uitofp:
5457 case lltok::kw_sitofp:
5458 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005459 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005460 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005461 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005462 // Other.
5463 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005464 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005465 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5466 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5467 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5468 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005469 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005470 // Call.
5471 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5472 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5473 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005474 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005475 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005476 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005477 case lltok::kw_load: return ParseLoad(Inst, PFS);
5478 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005479 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5480 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005481 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005482 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5483 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5484 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5485 }
5486}
5487
5488/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5489bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005490 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005491 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005492 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005493 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5494 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5495 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5496 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5497 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5498 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5499 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5500 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5501 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5502 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5503 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5504 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5505 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5506 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5507 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5508 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5509 }
5510 } else {
5511 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005512 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005513 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5514 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5515 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5516 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5517 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5518 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5519 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5520 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5521 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5522 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5523 }
5524 }
5525 Lex.Lex();
5526 return false;
5527}
5528
5529//===----------------------------------------------------------------------===//
5530// Terminator Instructions.
5531//===----------------------------------------------------------------------===//
5532
5533/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005534/// ::= 'ret' void (',' !dbg, !1)*
5535/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005536bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005537 PerFunctionState &PFS) {
5538 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005539 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005540 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005541
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005542 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005543
Chris Lattnerfdd87902009-10-05 05:54:46 +00005544 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005545 if (!ResType->isVoidTy())
5546 return Error(TypeLoc, "value doesn't match function result type '" +
5547 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005548
Owen Anderson55f1c092009-08-13 21:58:54 +00005549 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005550 return false;
5551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005552
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 Value *RV;
5554 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005556 if (ResType != RV->getType())
5557 return Error(TypeLoc, "value doesn't match function result type '" +
5558 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005559
Owen Anderson55f1c092009-08-13 21:58:54 +00005560 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005561 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005562}
5563
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564/// ParseBr
5565/// ::= 'br' TypeAndValue
5566/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5567bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5568 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005569 Value *Op0;
5570 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005571 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005572
Chris Lattnerac161bf2009-01-02 07:01:27 +00005573 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5574 Inst = BranchInst::Create(BB);
5575 return false;
5576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005577
Owen Anderson55f1c092009-08-13 21:58:54 +00005578 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005579 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005580
Chris Lattnerac161bf2009-01-02 07:01:27 +00005581 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005582 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005583 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005584 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005585 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005586
Chris Lattner3ed871f2009-10-27 19:13:16 +00005587 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005588 return false;
5589}
5590
5591/// ParseSwitch
5592/// Instruction
5593/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5594/// JumpTable
5595/// ::= (TypeAndValue ',' TypeAndValue)*
5596bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5597 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005598 Value *Cond;
5599 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005600 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5601 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005602 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5604 return true;
5605
Duncan Sands19d0b472010-02-16 11:11:14 +00005606 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005607 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005608
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609 // Parse the jump table pairs.
5610 SmallPtrSet<Value*, 32> SeenCases;
5611 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5612 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005613 Value *Constant;
5614 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005615
Chris Lattnerac161bf2009-01-02 07:01:27 +00005616 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5617 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005618 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005620
David Blaikie70573dc2014-11-19 07:49:26 +00005621 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005622 return Error(CondLoc, "duplicate case value in switch");
5623 if (!isa<ConstantInt>(Constant))
5624 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005625
Chris Lattner3ed871f2009-10-27 19:13:16 +00005626 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005627 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005628
Chris Lattnerac161bf2009-01-02 07:01:27 +00005629 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005630
Chris Lattner3ed871f2009-10-27 19:13:16 +00005631 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005632 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5633 SI->addCase(Table[i].first, Table[i].second);
5634 Inst = SI;
5635 return false;
5636}
5637
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005638/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005639/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005640/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5641bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005642 LocTy AddrLoc;
5643 Value *Address;
5644 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005645 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5646 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005647 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005648
Duncan Sands19d0b472010-02-16 11:11:14 +00005649 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005650 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005651
Chris Lattner3ed871f2009-10-27 19:13:16 +00005652 // Parse the destination list.
5653 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005654
Chris Lattner3ed871f2009-10-27 19:13:16 +00005655 if (Lex.getKind() != lltok::rsquare) {
5656 BasicBlock *DestBB;
5657 if (ParseTypeAndBasicBlock(DestBB, PFS))
5658 return true;
5659 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005660
Chris Lattner3ed871f2009-10-27 19:13:16 +00005661 while (EatIfPresent(lltok::comma)) {
5662 if (ParseTypeAndBasicBlock(DestBB, PFS))
5663 return true;
5664 DestList.push_back(DestBB);
5665 }
5666 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005667
Chris Lattner3ed871f2009-10-27 19:13:16 +00005668 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5669 return true;
5670
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005671 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005672 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5673 IBI->addDestination(DestList[i]);
5674 Inst = IBI;
5675 return false;
5676}
5677
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678/// ParseInvoke
5679/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5680/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5681bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5682 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005683 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005684 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005685 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005686 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005687 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005688 LocTy RetTypeLoc;
5689 ValID CalleeID;
5690 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005691 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692
Chris Lattner3ed871f2009-10-27 19:13:16 +00005693 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005694 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005695 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005696 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005697 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5698 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005699 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005701 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005702 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005703 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005704 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005705
Chris Lattnerac161bf2009-01-02 07:01:27 +00005706 // If RetType is a non-function pointer type, then this is the short syntax
5707 // for the call, which means that RetType is just the return type. Infer the
5708 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005709 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5710 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005711 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005712 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5714 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005715
Chris Lattnerac161bf2009-01-02 07:01:27 +00005716 if (!FunctionType::isValidReturnType(RetType))
5717 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005718
Owen Anderson4056ca92009-07-29 22:17:13 +00005719 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005721
David Blaikie41ba2b42015-07-27 23:32:19 +00005722 CalleeID.FTy = Ty;
5723
Chris Lattnerac161bf2009-01-02 07:01:27 +00005724 // Look up the callee.
5725 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00005726 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
5727 /*IsCall=*/true))
David Blaikie445e3fb2015-04-24 19:32:54 +00005728 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005729
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005730 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005731 SmallVector<Value *, 8> Args;
5732 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005733
Chris Lattnerac161bf2009-01-02 07:01:27 +00005734 // Loop through FunctionType's arguments and ensure they are specified
5735 // correctly. Also, gather any parameter attributes.
5736 FunctionType::param_iterator I = Ty->param_begin();
5737 FunctionType::param_iterator E = Ty->param_end();
5738 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005739 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005740 if (I != E) {
5741 ExpectedTy = *I++;
5742 } else if (!Ty->isVarArg()) {
5743 return Error(ArgList[i].Loc, "too many arguments specified");
5744 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005745
Chris Lattnerac161bf2009-01-02 07:01:27 +00005746 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5747 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005748 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005750 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005752
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 if (I != E)
5754 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005755
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005756 if (FnAttrs.hasAlignmentAttr())
5757 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005758
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005759 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005760 AttributeList PAL =
5761 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5762 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005764 InvokeInst *II =
5765 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005766 II->setCallingConv(CC);
5767 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005768 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769 Inst = II;
5770 return false;
5771}
5772
Bill Wendlingf891bf82011-07-31 06:30:59 +00005773/// ParseResume
5774/// ::= 'resume' TypeAndValue
5775bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5776 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005777 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5778 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005779
Bill Wendlingf891bf82011-07-31 06:30:59 +00005780 ResumeInst *RI = ResumeInst::Create(Exn);
5781 Inst = RI;
5782 return false;
5783}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005784
David Majnemer654e1302015-07-31 17:58:14 +00005785bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5786 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005787 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005788 return true;
5789
5790 while (Lex.getKind() != lltok::rsquare) {
5791 // If this isn't the first argument, we need a comma.
5792 if (!Args.empty() &&
5793 ParseToken(lltok::comma, "expected ',' in argument list"))
5794 return true;
5795
5796 // Parse the argument.
5797 LocTy ArgLoc;
5798 Type *ArgTy = nullptr;
5799 if (ParseType(ArgTy, ArgLoc))
5800 return true;
5801
5802 Value *V;
5803 if (ArgTy->isMetadataTy()) {
5804 if (ParseMetadataAsValue(V, PFS))
5805 return true;
5806 } else {
5807 if (ParseValue(ArgTy, V, PFS))
5808 return true;
5809 }
5810 Args.push_back(V);
5811 }
5812
5813 Lex.Lex(); // Lex the ']'.
5814 return false;
5815}
5816
5817/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005818/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005819bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005820 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005821
David Majnemer8a1c45d2015-12-12 05:38:55 +00005822 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5823 return true;
5824
5825 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005826 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005827
5828 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5829 return true;
5830
5831 BasicBlock *UnwindBB = nullptr;
5832 if (Lex.getKind() == lltok::kw_to) {
5833 Lex.Lex();
5834 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5835 return true;
5836 } else {
5837 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5838 return true;
5839 }
5840 }
5841
David Majnemer8a1c45d2015-12-12 05:38:55 +00005842 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005843 return false;
5844}
5845
5846/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005847/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005848bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005849 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005850
David Majnemer8a1c45d2015-12-12 05:38:55 +00005851 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5852 return true;
5853
5854 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005855 return true;
5856
David Majnemer0bc0eef2015-08-15 02:46:08 +00005857 BasicBlock *BB;
5858 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5859 ParseTypeAndBasicBlock(BB, PFS))
5860 return true;
5861
David Majnemer8a1c45d2015-12-12 05:38:55 +00005862 Inst = CatchReturnInst::Create(CatchPad, BB);
5863 return false;
5864}
5865
5866/// ParseCatchSwitch
5867/// ::= 'catchswitch' within Parent
5868bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5869 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005870
5871 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5872 return true;
5873
5874 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5875 Lex.getKind() != lltok::LocalVarID)
5876 return TokError("expected scope value for catchswitch");
5877
5878 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5879 return true;
5880
5881 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5882 return true;
5883
5884 SmallVector<BasicBlock *, 32> Table;
5885 do {
5886 BasicBlock *DestBB;
5887 if (ParseTypeAndBasicBlock(DestBB, PFS))
5888 return true;
5889 Table.push_back(DestBB);
5890 } while (EatIfPresent(lltok::comma));
5891
5892 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5893 return true;
5894
5895 if (ParseToken(lltok::kw_unwind,
5896 "expected 'unwind' after catchswitch scope"))
5897 return true;
5898
5899 BasicBlock *UnwindBB = nullptr;
5900 if (EatIfPresent(lltok::kw_to)) {
5901 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5902 return true;
5903 } else {
5904 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5905 return true;
5906 }
5907
5908 auto *CatchSwitch =
5909 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5910 for (BasicBlock *DestBB : Table)
5911 CatchSwitch->addHandler(DestBB);
5912 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005913 return false;
5914}
5915
5916/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005917/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005918bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005919 Value *CatchSwitch = nullptr;
5920
5921 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5922 return true;
5923
5924 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5925 return TokError("expected scope value for catchpad");
5926
5927 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5928 return true;
5929
David Majnemer654e1302015-07-31 17:58:14 +00005930 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005931 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005932 return true;
5933
David Majnemer8a1c45d2015-12-12 05:38:55 +00005934 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005935 return false;
5936}
5937
David Majnemer654e1302015-07-31 17:58:14 +00005938/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005939/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005940bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005941 Value *ParentPad = nullptr;
5942
5943 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5944 return true;
5945
5946 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5947 Lex.getKind() != lltok::LocalVarID)
5948 return TokError("expected scope value for cleanuppad");
5949
5950 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5951 return true;
5952
David Majnemer654e1302015-07-31 17:58:14 +00005953 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005954 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005955 return true;
5956
David Majnemer8a1c45d2015-12-12 05:38:55 +00005957 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005958 return false;
5959}
5960
Chris Lattnerac161bf2009-01-02 07:01:27 +00005961//===----------------------------------------------------------------------===//
5962// Binary Operators.
5963//===----------------------------------------------------------------------===//
5964
5965/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005966/// ::= ArithmeticOps TypeAndValue ',' Value
5967///
5968/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5969/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005970bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005971 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005972 LocTy Loc; Value *LHS, *RHS;
5973 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5974 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5975 ParseValue(LHS->getType(), RHS, PFS))
5976 return true;
5977
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005978 bool Valid;
5979 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005980 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005981 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005982 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5983 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005984 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005985 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5986 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005988
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005989 if (!Valid)
5990 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005991
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5993 return false;
5994}
5995
5996/// ParseLogical
5997/// ::= ArithmeticOps TypeAndValue ',' Value {
5998bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5999 unsigned Opc) {
6000 LocTy Loc; Value *LHS, *RHS;
6001 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6002 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6003 ParseValue(LHS->getType(), RHS, PFS))
6004 return true;
6005
Duncan Sands9dff9be2010-02-15 16:12:20 +00006006 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006007 return Error(Loc,"instruction requires integer or integer vector operands");
6008
6009 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6010 return false;
6011}
6012
Chris Lattnerac161bf2009-01-02 07:01:27 +00006013/// ParseCompare
6014/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6015/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00006016bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6017 unsigned Opc) {
6018 // Parse the integer/fp comparison predicate.
6019 LocTy Loc;
6020 unsigned Pred;
6021 Value *LHS, *RHS;
6022 if (ParseCmpPredicate(Pred, Opc) ||
6023 ParseTypeAndValue(LHS, Loc, PFS) ||
6024 ParseToken(lltok::comma, "expected ',' after compare value") ||
6025 ParseValue(LHS->getType(), RHS, PFS))
6026 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006027
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00006029 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006031 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00006032 } else {
6033 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00006034 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00006035 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006036 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00006037 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006038 }
6039 return false;
6040}
6041
6042//===----------------------------------------------------------------------===//
6043// Other Instructions.
6044//===----------------------------------------------------------------------===//
6045
6046
6047/// ParseCast
6048/// ::= CastOpc TypeAndValue 'to' Type
6049bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6050 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006051 LocTy Loc;
6052 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006053 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006054 if (ParseTypeAndValue(Op, Loc, PFS) ||
6055 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6056 ParseType(DestTy))
6057 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006058
Chris Lattner89d856e2009-03-01 00:53:13 +00006059 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6060 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006061 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006062 getTypeString(Op->getType()) + "' to '" +
6063 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00006064 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6066 return false;
6067}
6068
6069/// ParseSelect
6070/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6071bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6072 LocTy Loc;
6073 Value *Op0, *Op1, *Op2;
6074 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6075 ParseToken(lltok::comma, "expected ',' after select condition") ||
6076 ParseTypeAndValue(Op1, PFS) ||
6077 ParseToken(lltok::comma, "expected ',' after select value") ||
6078 ParseTypeAndValue(Op2, PFS))
6079 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006080
Chris Lattnerac161bf2009-01-02 07:01:27 +00006081 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6082 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006083
Chris Lattnerac161bf2009-01-02 07:01:27 +00006084 Inst = SelectInst::Create(Op0, Op1, Op2);
6085 return false;
6086}
6087
Chris Lattnerb55ab542009-01-05 08:18:44 +00006088/// ParseVA_Arg
6089/// ::= 'va_arg' TypeAndValue ',' Type
6090bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006091 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00006092 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00006093 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006094 if (ParseTypeAndValue(Op, PFS) ||
6095 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00006096 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006097 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006098
Chris Lattnerb55ab542009-01-05 08:18:44 +00006099 if (!EltTy->isFirstClassType())
6100 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006101
6102 Inst = new VAArgInst(Op, EltTy);
6103 return false;
6104}
6105
6106/// ParseExtractElement
6107/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6108bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6109 LocTy Loc;
6110 Value *Op0, *Op1;
6111 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6112 ParseToken(lltok::comma, "expected ',' after extract value") ||
6113 ParseTypeAndValue(Op1, PFS))
6114 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006115
Chris Lattnerac161bf2009-01-02 07:01:27 +00006116 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6117 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006118
Eric Christopherc9742252009-07-25 02:28:41 +00006119 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006120 return false;
6121}
6122
6123/// ParseInsertElement
6124/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6125bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6126 LocTy Loc;
6127 Value *Op0, *Op1, *Op2;
6128 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6129 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6130 ParseTypeAndValue(Op1, PFS) ||
6131 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6132 ParseTypeAndValue(Op2, PFS))
6133 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006134
Chris Lattnerac161bf2009-01-02 07:01:27 +00006135 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00006136 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006137
Chris Lattnerac161bf2009-01-02 07:01:27 +00006138 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6139 return false;
6140}
6141
6142/// ParseShuffleVector
6143/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6144bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6145 LocTy Loc;
6146 Value *Op0, *Op1, *Op2;
6147 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6148 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6149 ParseTypeAndValue(Op1, PFS) ||
6150 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6151 ParseTypeAndValue(Op2, PFS))
6152 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006153
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00006155 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006156
Chris Lattnerac161bf2009-01-02 07:01:27 +00006157 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6158 return false;
6159}
6160
6161/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00006162/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006163int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006164 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006165 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006166
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00006167 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006168 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6169 ParseValue(Ty, Op0, PFS) ||
6170 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006171 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006172 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6173 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006174
Chris Lattnerf4f03422009-12-30 05:27:33 +00006175 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006176 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006177
6178 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006179 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006180
Chris Lattner3822f632009-01-02 08:05:26 +00006181 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006182 break;
6183
Chris Lattnerf4f03422009-12-30 05:27:33 +00006184 if (Lex.getKind() == lltok::MetadataVar) {
6185 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00006186 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006187 }
Devang Patel8f842d32009-10-16 18:45:49 +00006188
Chris Lattner3822f632009-01-02 08:05:26 +00006189 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006190 ParseValue(Ty, Op0, PFS) ||
6191 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00006192 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006193 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6194 return true;
6195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006196
Chris Lattnerac161bf2009-01-02 07:01:27 +00006197 if (!Ty->isFirstClassType())
6198 return Error(TypeLoc, "phi node must have first class type");
6199
Jay Foad52131342011-03-30 11:28:46 +00006200 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00006201 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6202 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6203 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006204 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006205}
6206
Bill Wendlingfae14752011-08-12 20:24:12 +00006207/// ParseLandingPad
6208/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6209/// Clause
6210/// ::= 'catch' TypeAndValue
6211/// ::= 'filter'
6212/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6213bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006214 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00006215
David Majnemer7fddecc2015-06-17 20:52:32 +00006216 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00006217 return true;
6218
David Majnemer7fddecc2015-06-17 20:52:32 +00006219 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00006220 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6221
6222 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6223 LandingPadInst::ClauseType CT;
6224 if (EatIfPresent(lltok::kw_catch))
6225 CT = LandingPadInst::Catch;
6226 else if (EatIfPresent(lltok::kw_filter))
6227 CT = LandingPadInst::Filter;
6228 else
6229 return TokError("expected 'catch' or 'filter' clause type");
6230
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00006231 Value *V;
6232 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00006233 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00006234 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00006235
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00006236 // A 'catch' type expects a non-array constant. A filter clause expects an
6237 // array constant.
6238 if (CT == LandingPadInst::Catch) {
6239 if (isa<ArrayType>(V->getType()))
6240 Error(VLoc, "'catch' clause has an invalid type");
6241 } else {
6242 if (!isa<ArrayType>(V->getType()))
6243 Error(VLoc, "'filter' clause has an invalid type");
6244 }
6245
Owen Andersonf8f259d2015-03-09 07:13:42 +00006246 Constant *CV = dyn_cast<Constant>(V);
6247 if (!CV)
6248 return Error(VLoc, "clause argument must be a constant");
6249 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006250 }
6251
Owen Andersonf8f259d2015-03-09 07:13:42 +00006252 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006253 return false;
6254}
6255
Chris Lattnerac161bf2009-01-02 07:01:27 +00006256/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006257/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6258/// OptionalAttrs Type Value ParameterList OptionalAttrs
6259/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6260/// OptionalAttrs Type Value ParameterList OptionalAttrs
6261/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6262/// OptionalAttrs Type Value ParameterList OptionalAttrs
6263/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6264/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006265bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006266 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006267 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006268 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006269 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006270 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006271 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006272 LocTy RetTypeLoc;
6273 ValID CalleeID;
6274 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006275 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006276 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006277
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006278 if (TCK != CallInst::TCK_None &&
6279 ParseToken(lltok::kw_call,
6280 "expected 'tail call', 'musttail call', or 'notail call'"))
6281 return true;
6282
6283 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6284
6285 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006286 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006287 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006288 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6289 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006290 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6291 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006292 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006293
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006294 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6295 return Error(CallLoc, "fast-math-flags specified for call without "
6296 "floating-point scalar or vector return type");
6297
Chris Lattnerac161bf2009-01-02 07:01:27 +00006298 // If RetType is a non-function pointer type, then this is the short syntax
6299 // for the call, which means that RetType is just the return type. Infer the
6300 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006301 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6302 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006304 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006305 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6306 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006307
Chris Lattnerac161bf2009-01-02 07:01:27 +00006308 if (!FunctionType::isValidReturnType(RetType))
6309 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006310
Owen Anderson4056ca92009-07-29 22:17:13 +00006311 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006312 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006313
David Blaikie41ba2b42015-07-27 23:32:19 +00006314 CalleeID.FTy = Ty;
6315
Chris Lattnerac161bf2009-01-02 07:01:27 +00006316 // Look up the callee.
6317 Value *Callee;
Alexander Richardsonc11ae182018-02-27 11:15:11 +00006318 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6319 /*IsCall=*/true))
David Blaikie23af6482015-04-16 23:24:18 +00006320 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006321
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006322 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006323 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006324
Chris Lattnerac161bf2009-01-02 07:01:27 +00006325 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006326
Chris Lattnerac161bf2009-01-02 07:01:27 +00006327 // Loop through FunctionType's arguments and ensure they are specified
6328 // correctly. Also, gather any parameter attributes.
6329 FunctionType::param_iterator I = Ty->param_begin();
6330 FunctionType::param_iterator E = Ty->param_end();
6331 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006332 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006333 if (I != E) {
6334 ExpectedTy = *I++;
6335 } else if (!Ty->isVarArg()) {
6336 return Error(ArgList[i].Loc, "too many arguments specified");
6337 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006338
Chris Lattnerac161bf2009-01-02 07:01:27 +00006339 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6340 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006341 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006342 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006343 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006344 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006345
Chris Lattnerac161bf2009-01-02 07:01:27 +00006346 if (I != E)
6347 return Error(CallLoc, "not enough parameters specified for call");
6348
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006349 if (FnAttrs.hasAlignmentAttr())
6350 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006351
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006352 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006353 AttributeList PAL =
6354 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6355 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006356
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006357 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006358 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006359 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006360 if (FMF.any())
6361 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006362 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006363 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006364 Inst = CI;
6365 return false;
6366}
6367
6368//===----------------------------------------------------------------------===//
6369// Memory Instructions.
6370//===----------------------------------------------------------------------===//
6371
6372/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006373/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006374/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006375int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006376 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006377 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006378 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006379 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006380 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006381
6382 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006383 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006384
David Majnemera3b0eb22015-02-16 08:38:03 +00006385 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006386
David Majnemera3b0eb22015-02-16 08:38:03 +00006387 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6388 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006389
Chris Lattnerb2f39502009-12-30 05:44:30 +00006390 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006391 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006392 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006393 if (ParseOptionalAlignment(Alignment))
6394 return true;
6395 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6396 return true;
6397 } else if (Lex.getKind() == lltok::kw_addrspace) {
6398 ASLoc = Lex.getLoc();
6399 if (ParseOptionalAddrSpace(AddrSpace))
6400 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006401 } else if (Lex.getKind() == lltok::MetadataVar) {
6402 AteExtraComma = true;
6403 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006404 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006405 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006406 if (EatIfPresent(lltok::comma)) {
6407 if (Lex.getKind() == lltok::kw_align) {
6408 if (ParseOptionalAlignment(Alignment))
6409 return true;
6410 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6411 return true;
6412 } else if (Lex.getKind() == lltok::kw_addrspace) {
6413 ASLoc = Lex.getLoc();
6414 if (ParseOptionalAddrSpace(AddrSpace))
6415 return true;
6416 } else if (Lex.getKind() == lltok::MetadataVar) {
6417 AteExtraComma = true;
6418 }
6419 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006420 }
6421 }
6422
Dan Gohman2140a742010-05-28 01:14:11 +00006423 if (Size && !Size->getType()->isIntegerTy())
6424 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006425
Yaxun Liuc00d81e2018-01-30 22:32:39 +00006426 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006427 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006428 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006429 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006430 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431}
6432
6433/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006434/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006435/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006436/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006437int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006438 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006439 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006440 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006441 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006442 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006443 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006444
6445 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006446 isAtomic = true;
6447 Lex.Lex();
6448 }
6449
Chris Lattnerbc639292011-11-27 06:56:53 +00006450 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006451 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006452 isVolatile = true;
6453 Lex.Lex();
6454 }
6455
David Blaikie15d9a4c2015-04-06 20:59:48 +00006456 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006457 LocTy ExplicitTypeLoc = Lex.getLoc();
6458 if (ParseType(Ty) ||
6459 ParseToken(lltok::comma, "expected comma after load's type") ||
6460 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006461 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006462 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6463 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006464
David Blaikie15d9a4c2015-04-06 20:59:48 +00006465 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006466 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006467 if (isAtomic && !Alignment)
6468 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006469 if (Ordering == AtomicOrdering::Release ||
6470 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006471 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006472
David Blaikiea79ac142015-02-27 21:17:42 +00006473 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6474 return Error(ExplicitTypeLoc,
6475 "explicit pointee type doesn't match operand's pointee type");
6476
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006477 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006478 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006479}
6480
6481/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006482
6483/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6484/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006485/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006486int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006487 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006488 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006489 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006490 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006491 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006492 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006493
6494 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006495 isAtomic = true;
6496 Lex.Lex();
6497 }
6498
Chris Lattnerbc639292011-11-27 06:56:53 +00006499 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006500 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006501 isVolatile = true;
6502 Lex.Lex();
6503 }
6504
Chris Lattnerac161bf2009-01-02 07:01:27 +00006505 if (ParseTypeAndValue(Val, Loc, PFS) ||
6506 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006507 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006508 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006509 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006510 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006511
Duncan Sands19d0b472010-02-16 11:11:14 +00006512 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006513 return Error(PtrLoc, "store operand must be a pointer");
6514 if (!Val->getType()->isFirstClassType())
6515 return Error(Loc, "store operand must be a first class value");
6516 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6517 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006518 if (isAtomic && !Alignment)
6519 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006520 if (Ordering == AtomicOrdering::Acquire ||
6521 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006522 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006523
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006524 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006525 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006526}
6527
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006528/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006529/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6530/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006531int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006532 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6533 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006534 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6535 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006536 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006537 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006538 bool isWeak = false;
6539
6540 if (EatIfPresent(lltok::kw_weak))
6541 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006542
6543 if (EatIfPresent(lltok::kw_volatile))
6544 isVolatile = true;
6545
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006546 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6547 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6548 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6549 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6550 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006551 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006552 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006553 return true;
6554
JF Bastien800f87a2016-04-06 21:19:33 +00006555 if (SuccessOrdering == AtomicOrdering::Unordered ||
6556 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006557 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006558 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6559 return TokError("cmpxchg failure argument shall be no stronger than the "
6560 "success argument");
6561 if (FailureOrdering == AtomicOrdering::Release ||
6562 FailureOrdering == AtomicOrdering::AcquireRelease)
6563 return TokError(
6564 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006565 if (!Ptr->getType()->isPointerTy())
6566 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6567 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6568 return Error(CmpLoc, "compare value and pointer type do not match");
6569 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6570 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006571 if (!New->getType()->isFirstClassType())
6572 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006573 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006574 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006575 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006576 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006577 Inst = CXI;
6578 return AteExtraComma ? InstExtraComma : InstNormal;
6579}
6580
6581/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006582/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6583/// 'singlethread'? AtomicOrdering
6584int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006585 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6586 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006587 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006588 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006589 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006590 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006591
6592 if (EatIfPresent(lltok::kw_volatile))
6593 isVolatile = true;
6594
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006595 switch (Lex.getKind()) {
6596 default: return TokError("expected binary operation in atomicrmw");
6597 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6598 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6599 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6600 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6601 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6602 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6603 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6604 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6605 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6606 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6607 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6608 }
6609 Lex.Lex(); // Eat the operation.
6610
6611 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6612 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6613 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006614 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006615 return true;
6616
JF Bastien800f87a2016-04-06 21:19:33 +00006617 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006618 return TokError("atomicrmw cannot be unordered");
6619 if (!Ptr->getType()->isPointerTy())
6620 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6621 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6622 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6623 if (!Val->getType()->isIntegerTy())
6624 return Error(ValLoc, "atomicrmw operand must be an integer");
6625 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6626 if (Size < 8 || (Size & (Size - 1)))
6627 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6628 " integer");
6629
6630 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006631 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006632 RMWI->setVolatile(isVolatile);
6633 Inst = RMWI;
6634 return AteExtraComma ? InstExtraComma : InstNormal;
6635}
6636
Eli Friedmanfee02c62011-07-25 23:16:38 +00006637/// ParseFence
6638/// ::= 'fence' 'singlethread'? AtomicOrdering
6639int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006640 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006641 SyncScope::ID SSID = SyncScope::System;
6642 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006643 return true;
6644
JF Bastien800f87a2016-04-06 21:19:33 +00006645 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006646 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006647 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006648 return TokError("fence cannot be monotonic");
6649
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006650 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006651 return InstNormal;
6652}
6653
Chris Lattnerac161bf2009-01-02 07:01:27 +00006654/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006655/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006656int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006657 Value *Ptr = nullptr;
6658 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006659 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006660
Dan Gohman16cbbe42009-07-29 15:58:36 +00006661 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006662
David Blaikie79e6c742015-02-27 19:29:02 +00006663 Type *Ty = nullptr;
6664 LocTy ExplicitTypeLoc = Lex.getLoc();
6665 if (ParseType(Ty) ||
6666 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6667 ParseTypeAndValue(Ptr, Loc, PFS))
6668 return true;
6669
Eli Benderskyd9806682013-04-22 17:03:42 +00006670 Type *BaseType = Ptr->getType();
6671 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6672 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006673 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006674
David Blaikie8d757942015-03-09 23:08:44 +00006675 if (Ty != BasePointerType->getElementType())
6676 return Error(ExplicitTypeLoc,
6677 "explicit pointee type doesn't match operand's pointee type");
6678
Chris Lattnerac161bf2009-01-02 07:01:27 +00006679 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006680 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006681 // GEP returns a vector of pointers if at least one of parameters is a vector.
6682 // All vector parameters should have the same vector width.
6683 unsigned GEPWidth = BaseType->isVectorTy() ?
6684 BaseType->getVectorNumElements() : 0;
6685
Chris Lattner3822f632009-01-02 08:05:26 +00006686 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006687 if (Lex.getKind() == lltok::MetadataVar) {
6688 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006689 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006690 }
Chris Lattner3822f632009-01-02 08:05:26 +00006691 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006692 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006693 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006694
Nadav Rotem3924cb02011-12-05 06:29:09 +00006695 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006696 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6697 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006698 return Error(EltLoc,
6699 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006700 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006701 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006702 Indices.push_back(Val);
6703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006704
Craig Toppere3dcce92015-08-01 22:20:21 +00006705 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006706 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006707 return Error(Loc, "base element of getelementptr must be sized");
6708
David Blaikied33bad32015-04-17 22:32:13 +00006709 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006710 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006711 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006712 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006713 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006714 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006715}
6716
6717/// ParseExtractValue
6718/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006719int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006720 Value *Val; LocTy Loc;
6721 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006722 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006723 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006724 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006725 return true;
6726
Chris Lattner392be582010-02-12 20:49:41 +00006727 if (!Val->getType()->isAggregateType())
6728 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006729
Jay Foad57aa6362011-07-13 10:26:04 +00006730 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006731 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006732 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006733 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006734}
6735
6736/// ParseInsertValue
6737/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006738int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006739 Value *Val0, *Val1; LocTy Loc0, Loc1;
6740 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006741 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006742 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6743 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6744 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006745 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006746 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006747
Chris Lattner392be582010-02-12 20:49:41 +00006748 if (!Val0->getType()->isAggregateType())
6749 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006750
David Majnemer30074532015-02-11 07:43:58 +00006751 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6752 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006753 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006754 if (IndexedType != Val1->getType())
6755 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6756 getTypeString(Val1->getType()) + "' instead of '" +
6757 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006758 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006759 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006760}
Nick Lewycky49f89192009-04-04 07:22:01 +00006761
6762//===----------------------------------------------------------------------===//
6763// Embedded metadata.
6764//===----------------------------------------------------------------------===//
6765
6766/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006767/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006768/// Element
6769/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006770bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006771 if (ParseToken(lltok::lbrace, "expected '{' here"))
6772 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006773
Dan Gohman1e0213a2010-07-13 19:33:27 +00006774 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006775 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006776 return false;
6777
Nick Lewycky49f89192009-04-04 07:22:01 +00006778 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006779 // Null is a special case since it is typeless.
6780 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006781 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006782 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006783 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006784
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006785 Metadata *MD;
6786 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006787 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006788 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006789 } while (EatIfPresent(lltok::comma));
6790
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006791 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006792}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006793
6794//===----------------------------------------------------------------------===//
6795// Use-list order directives.
6796//===----------------------------------------------------------------------===//
6797bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6798 SMLoc Loc) {
6799 if (V->use_empty())
6800 return Error(Loc, "value has no uses");
6801
6802 unsigned NumUses = 0;
6803 SmallDenseMap<const Use *, unsigned, 16> Order;
6804 for (const Use &U : V->uses()) {
6805 if (++NumUses > Indexes.size())
6806 break;
6807 Order[&U] = Indexes[NumUses - 1];
6808 }
6809 if (NumUses < 2)
6810 return Error(Loc, "value only has one use");
6811 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
Vedant Kumare0b5f862018-05-10 23:01:54 +00006812 return Error(Loc,
6813 "wrong number of indexes, expected " + Twine(V->getNumUses()));
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006814
6815 V->sortUseList([&](const Use &L, const Use &R) {
6816 return Order.lookup(&L) < Order.lookup(&R);
6817 });
6818 return false;
6819}
6820
6821/// ParseUseListOrderIndexes
6822/// ::= '{' uint32 (',' uint32)+ '}'
6823bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6824 SMLoc Loc = Lex.getLoc();
6825 if (ParseToken(lltok::lbrace, "expected '{' here"))
6826 return true;
6827 if (Lex.getKind() == lltok::rbrace)
6828 return Lex.Error("expected non-empty list of uselistorder indexes");
6829
6830 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6831 // indexes should be distinct numbers in the range [0, size-1], and should
6832 // not be in order.
6833 unsigned Offset = 0;
6834 unsigned Max = 0;
6835 bool IsOrdered = true;
6836 assert(Indexes.empty() && "Expected empty order vector");
6837 do {
6838 unsigned Index;
6839 if (ParseUInt32(Index))
6840 return true;
6841
6842 // Update consistency checks.
6843 Offset += Index - Indexes.size();
6844 Max = std::max(Max, Index);
6845 IsOrdered &= Index == Indexes.size();
6846
6847 Indexes.push_back(Index);
6848 } while (EatIfPresent(lltok::comma));
6849
6850 if (ParseToken(lltok::rbrace, "expected '}' here"))
6851 return true;
6852
6853 if (Indexes.size() < 2)
6854 return Error(Loc, "expected >= 2 uselistorder indexes");
6855 if (Offset != 0 || Max >= Indexes.size())
6856 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6857 if (IsOrdered)
6858 return Error(Loc, "expected uselistorder indexes to change the order");
6859
6860 return false;
6861}
6862
6863/// ParseUseListOrder
6864/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6865bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6866 SMLoc Loc = Lex.getLoc();
6867 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6868 return true;
6869
6870 Value *V;
6871 SmallVector<unsigned, 16> Indexes;
6872 if (ParseTypeAndValue(V, PFS) ||
6873 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6874 ParseUseListOrderIndexes(Indexes))
6875 return true;
6876
6877 return sortUseListOrder(V, Indexes, Loc);
6878}
6879
6880/// ParseUseListOrderBB
6881/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6882bool LLParser::ParseUseListOrderBB() {
6883 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6884 SMLoc Loc = Lex.getLoc();
6885 Lex.Lex();
6886
6887 ValID Fn, Label;
6888 SmallVector<unsigned, 16> Indexes;
6889 if (ParseValID(Fn) ||
6890 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6891 ParseValID(Label) ||
6892 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6893 ParseUseListOrderIndexes(Indexes))
6894 return true;
6895
6896 // Check the function.
6897 GlobalValue *GV;
6898 if (Fn.Kind == ValID::t_GlobalName)
6899 GV = M->getNamedValue(Fn.StrVal);
6900 else if (Fn.Kind == ValID::t_GlobalID)
6901 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6902 else
6903 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6904 if (!GV)
6905 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6906 auto *F = dyn_cast<Function>(GV);
6907 if (!F)
6908 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6909 if (F->isDeclaration())
6910 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6911
6912 // Check the basic block.
6913 if (Label.Kind == ValID::t_LocalID)
6914 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6915 if (Label.Kind != ValID::t_LocalName)
6916 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006917 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006918 if (!V)
6919 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6920 if (!isa<BasicBlock>(V))
6921 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6922
6923 return sortUseListOrder(V, Indexes, Loc);
6924}