blob: c3ab95550e03ef13ac1659a06bb35485f443d1ad [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;
Bill Wendling63b88192013-02-06 06:52:58 +0000285 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000287 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
288 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000289 if (ParseUseListOrderBB())
290 return true;
291 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 }
293 }
294}
295
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296/// toplevelentity
297/// ::= 'module' 'asm' STRINGCONSTANT
298bool LLParser::ParseModuleAsm() {
299 assert(Lex.getKind() == lltok::kw_module);
300 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000301
302 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000303 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
304 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000305
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000306 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000307 return false;
308}
309
310/// toplevelentity
311/// ::= 'target' 'triple' '=' STRINGCONSTANT
312/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
313bool LLParser::ParseTargetDefinition() {
314 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000315 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000316 switch (Lex.Lex()) {
317 default: return TokError("unknown target property");
318 case lltok::kw_triple:
319 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000320 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
321 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000323 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324 return false;
325 case lltok::kw_datalayout:
326 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000327 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
328 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000330 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000331 return false;
332 }
333}
334
Bill Wendling706d3d62012-11-28 08:41:48 +0000335/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000336/// ::= 'source_filename' '=' STRINGCONSTANT
337bool LLParser::ParseSourceFileName() {
338 assert(Lex.getKind() == lltok::kw_source_filename);
339 std::string Str;
340 Lex.Lex();
341 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
342 ParseStringConstant(Str))
343 return true;
344 M->setSourceFileName(Str);
345 return false;
346}
347
348/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000349/// ::= 'deplibs' '=' '[' ']'
350/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
351/// FIXME: Remove in 4.0. Currently parse, but ignore.
352bool LLParser::ParseDepLibs() {
353 assert(Lex.getKind() == lltok::kw_deplibs);
354 Lex.Lex();
355 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
356 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
357 return true;
358
359 if (EatIfPresent(lltok::rsquare))
360 return false;
361
362 do {
363 std::string Str;
364 if (ParseStringConstant(Str)) return true;
365 } while (EatIfPresent(lltok::comma));
366
367 return ParseToken(lltok::rsquare, "expected ']' at end of list");
368}
369
Dan Gohman466876b2009-08-12 23:32:33 +0000370/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000371/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000372bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000373 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000374 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000375 Lex.Lex(); // eat LocalVarID;
376
377 if (ParseToken(lltok::equal, "expected '=' after name") ||
378 ParseToken(lltok::kw_type, "expected 'type' after '='"))
379 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000380
Craig Topper2617dcc2014-04-15 06:32:26 +0000381 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382 if (ParseStructDefinition(TypeLoc, "",
383 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385 if (!isa<StructType>(Result)) {
386 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
387 if (Entry.first)
388 return Error(TypeLoc, "non-struct types may not be recursive");
389 Entry.first = Result;
390 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000391 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392
Chris Lattnerac161bf2009-01-02 07:01:27 +0000393 return false;
394}
395
396/// toplevelentity
397/// ::= LocalVar '=' 'type' type
398bool LLParser::ParseNamedType() {
399 std::string Name = Lex.getStrVal();
400 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000401 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000402
Chris Lattner3822f632009-01-02 08:05:26 +0000403 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000404 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000405 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000406
Craig Topper2617dcc2014-04-15 06:32:26 +0000407 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000408 if (ParseStructDefinition(NameLoc, Name,
409 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 if (!isa<StructType>(Result)) {
412 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
413 if (Entry.first)
414 return Error(NameLoc, "non-struct types may not be recursive");
415 Entry.first = Result;
416 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000417 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420}
421
Chris Lattnerac161bf2009-01-02 07:01:27 +0000422/// toplevelentity
423/// ::= 'declare' FunctionHeader
424bool LLParser::ParseDeclare() {
425 assert(Lex.getKind() == lltok::kw_declare);
426 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000427
Peter Collingbourne21521892016-06-21 23:42:48 +0000428 std::vector<std::pair<unsigned, MDNode *>> MDs;
429 while (Lex.getKind() == lltok::MetadataVar) {
430 unsigned MDK;
431 MDNode *N;
432 if (ParseMetadataAttachment(MDK, N))
433 return true;
434 MDs.push_back({MDK, N});
435 }
436
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000438 if (ParseFunctionHeader(F, false))
439 return true;
440 for (auto &MD : MDs)
441 F->addMetadata(MD.first, *MD.second);
442 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443}
444
445/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000446/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000447bool LLParser::ParseDefine() {
448 assert(Lex.getKind() == lltok::kw_define);
449 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000452 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000453 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000454 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000455}
456
Chris Lattner3822f632009-01-02 08:05:26 +0000457/// ParseGlobalType
458/// ::= 'constant'
459/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000460bool LLParser::ParseGlobalType(bool &IsConstant) {
461 if (Lex.getKind() == lltok::kw_constant)
462 IsConstant = true;
463 else if (Lex.getKind() == lltok::kw_global)
464 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000465 else {
466 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000467 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000468 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000469 Lex.Lex();
470 return false;
471}
472
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000473bool LLParser::ParseOptionalUnnamedAddr(
474 GlobalVariable::UnnamedAddr &UnnamedAddr) {
475 if (EatIfPresent(lltok::kw_unnamed_addr))
476 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
477 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
478 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
479 else
480 UnnamedAddr = GlobalValue::UnnamedAddr::None;
481 return false;
482}
483
Dan Gohman466876b2009-08-12 23:32:33 +0000484/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000485/// OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000486/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
487/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000488/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000489/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000490/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
491/// OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000492/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000493bool LLParser::ParseUnnamedGlobal() {
494 unsigned VarID = NumberedVals.size();
495 std::string Name;
496 LocTy NameLoc = Lex.getLoc();
497
498 // Handle the GlobalID form.
499 if (Lex.getKind() == lltok::GlobalID) {
500 if (Lex.getUIntVal() != VarID)
501 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000502 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000503 Lex.Lex(); // eat GlobalID;
504
505 if (ParseToken(lltok::equal, "expected '=' after name"))
506 return true;
507 }
508
509 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000510 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000511 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000512 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000513 GlobalVariable::UnnamedAddr UnnamedAddr;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000514 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
515 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000516 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000517 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000518
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000519 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000520 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000521 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000522
523 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000524 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000525}
526
Chris Lattnerac161bf2009-01-02 07:01:27 +0000527/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000528/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Sean Fertilec70d28b2017-10-26 15:00:26 +0000529/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
530/// OptionalVisibility OptionalDLLStorageClass
Nico Rieck7157bb72014-01-14 15:22:47 +0000531/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000532bool LLParser::ParseNamedGlobal() {
533 assert(Lex.getKind() == lltok::GlobalVar);
534 LocTy NameLoc = Lex.getLoc();
535 std::string Name = Lex.getStrVal();
536 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Chris Lattnerac161bf2009-01-02 07:01:27 +0000538 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000539 unsigned Linkage, Visibility, DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +0000540 bool DSOLocal;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000541 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000542 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000543 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Sean Fertilec70d28b2017-10-26 15:00:26 +0000544 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
545 DSOLocal) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000546 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000547 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000548
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000549 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000550 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000551 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000552
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000553 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000554 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000555}
556
David Majnemerdad0a642014-06-27 18:19:56 +0000557bool LLParser::parseComdat() {
558 assert(Lex.getKind() == lltok::ComdatVar);
559 std::string Name = Lex.getStrVal();
560 LocTy NameLoc = Lex.getLoc();
561 Lex.Lex();
562
563 if (ParseToken(lltok::equal, "expected '=' here"))
564 return true;
565
566 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
567 return TokError("expected comdat type");
568
569 Comdat::SelectionKind SK;
570 switch (Lex.getKind()) {
571 default:
572 return TokError("unknown selection kind");
573 case lltok::kw_any:
574 SK = Comdat::Any;
575 break;
576 case lltok::kw_exactmatch:
577 SK = Comdat::ExactMatch;
578 break;
579 case lltok::kw_largest:
580 SK = Comdat::Largest;
581 break;
582 case lltok::kw_noduplicates:
583 SK = Comdat::NoDuplicates;
584 break;
585 case lltok::kw_samesize:
586 SK = Comdat::SameSize;
587 break;
588 }
589 Lex.Lex();
590
591 // See if the comdat was forward referenced, if so, use the comdat.
592 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
593 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
594 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
595 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
596
597 Comdat *C;
598 if (I != ComdatSymTab.end())
599 C = &I->second;
600 else
601 C = M->getOrInsertComdat(Name);
602 C->setSelectionKind(SK);
603
604 return false;
605}
606
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000607// MDString:
608// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000609bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000610 std::string Str;
611 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000612 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000613 return false;
614}
615
616// MDNode:
617// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000618bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000619 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000620 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000621 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000622 if (ParseUInt32(MID))
623 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000624
Chris Lattner8eff0152010-04-01 05:14:45 +0000625 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000626 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000627 Result = NumberedMetadata[MID];
628 return false;
629 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630
Chris Lattner8eff0152010-04-01 05:14:45 +0000631 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000632 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000633 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000634
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000635 Result = FwdRef.first.get();
636 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000637 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000638}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000639
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000641/// !foo = !{ !1, !2 }
642bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000643 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000644 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000645 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000646
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000647 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000648 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000649 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000650 return true;
651
Dan Gohman2637cc12010-07-21 23:38:33 +0000652 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000653 if (Lex.getKind() != lltok::rbrace)
654 do {
Craig Topper2617dcc2014-04-15 06:32:26 +0000655 MDNode *N = nullptr;
Reid Kleckner6d353342017-08-23 20:31:27 +0000656 // Parse DIExpressions inline as a special case. They are still MDNodes,
657 // so they can still appear in named metadata. Remove this logic if they
658 // become plain Metadata.
659 if (Lex.getKind() == lltok::MetadataVar &&
660 Lex.getStrVal() == "DIExpression") {
661 if (ParseDIExpression(N, /*IsDistinct=*/false))
662 return true;
663 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
664 ParseMDNodeID(N)) {
665 return true;
666 }
Dan Gohman2637cc12010-07-21 23:38:33 +0000667 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000668 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000669
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000670 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000671}
672
Devang Patel39e64d42009-07-01 19:21:12 +0000673/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000675bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000676 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000677 Lex.Lex();
678 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000679
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000681 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000682 ParseToken(lltok::equal, "expected '=' here"))
683 return true;
684
685 // Detect common error, from old metadata syntax.
686 if (Lex.getKind() == lltok::Type)
687 return TokError("unexpected type in metadata definition");
688
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000689 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000690 if (Lex.getKind() == lltok::MetadataVar) {
691 if (ParseSpecializedMDNode(Init, IsDistinct))
692 return true;
693 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
694 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000695 return true;
696
Chris Lattnerfc58af22009-12-30 04:51:58 +0000697 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000698 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000699 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000700 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000701 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000702
Chris Lattnerfc58af22009-12-30 04:51:58 +0000703 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
704 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000705 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000706 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000707 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000708 }
709
Devang Patel39e64d42009-07-01 19:21:12 +0000710 return false;
711}
712
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000713static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
714 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
715 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
716}
717
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000718/// parseIndirectSymbol:
Sean Fertilec70d28b2017-10-26 15:00:26 +0000719/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
720/// OptionalVisibility OptionalDLLStorageClass
721/// OptionalThreadLocal OptionalUnnamedAddr
722// 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000723///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000724/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000725/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726///
Eric Christopher536f0a92015-05-28 23:07:39 +0000727/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000728///
Sean Fertilec70d28b2017-10-26 15:00:26 +0000729bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
730 unsigned L, unsigned Visibility,
731 unsigned DLLStorageClass, bool DSOLocal,
732 GlobalVariable::ThreadLocalMode TLM,
733 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000734 bool IsAlias;
735 if (Lex.getKind() == lltok::kw_alias)
736 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000737 else if (Lex.getKind() == lltok::kw_ifunc)
738 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000739 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000740 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000742
Rafael Espindola78527052013-10-06 15:10:43 +0000743 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
744
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000745 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000746 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000747
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000748 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000749 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000750 "symbol with local linkage must have default visibility");
751
Sean Fertilec70d28b2017-10-26 15:00:26 +0000752 if (DSOLocal && !IsAlias) {
753 return Error(NameLoc,
754 "dso_local is invalid on ifunc");
755 }
756
David Blaikie2f408302015-09-11 03:22:04 +0000757 Type *Ty;
758 LocTy ExplicitTypeLoc = Lex.getLoc();
759 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000760 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000761 return true;
762
Rafael Espindola64c1e182014-06-03 02:41:57 +0000763 Constant *Aliasee;
764 LocTy AliaseeLoc = Lex.getLoc();
765 if (Lex.getKind() != lltok::kw_bitcast &&
766 Lex.getKind() != lltok::kw_getelementptr &&
767 Lex.getKind() != lltok::kw_addrspacecast &&
768 Lex.getKind() != lltok::kw_inttoptr) {
769 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000770 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000771 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000772 // The bitcast dest type is not present, it is implied by the dest type.
773 ValID ID;
774 if (ParseValID(ID))
775 return true;
776 if (ID.Kind != ValID::t_Constant)
777 return Error(AliaseeLoc, "invalid aliasee");
778 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000779 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Rafael Espindola64c1e182014-06-03 02:41:57 +0000781 Type *AliaseeType = Aliasee->getType();
782 auto *PTy = dyn_cast<PointerType>(AliaseeType);
783 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000784 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000785 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000786
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000787 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000788 return Error(
789 ExplicitTypeLoc,
790 "explicit pointee type doesn't match operand's pointee type");
791
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000792 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
793 return Error(
794 ExplicitTypeLoc,
795 "explicit pointee type should be a function type");
796
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000797 GlobalValue *GVal = nullptr;
798
799 // See if the alias was forward referenced, if so, prepare to replace the
800 // forward reference.
801 if (!Name.empty()) {
802 GVal = M->getNamedValue(Name);
803 if (GVal) {
804 if (!ForwardRefVals.erase(Name))
805 return Error(NameLoc, "redefinition of global '@" + Name + "'");
806 }
807 } else {
808 auto I = ForwardRefValIDs.find(NumberedVals.size());
809 if (I != ForwardRefValIDs.end()) {
810 GVal = I->second.first;
811 ForwardRefValIDs.erase(I);
812 }
813 }
814
Chris Lattnerac161bf2009-01-02 07:01:27 +0000815 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000816 std::unique_ptr<GlobalIndirectSymbol> GA;
817 if (IsAlias)
818 GA.reset(GlobalAlias::create(Ty, AddrSpace,
819 (GlobalValue::LinkageTypes)Linkage, Name,
820 Aliasee, /*Parent*/ nullptr));
821 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000822 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
823 (GlobalValue::LinkageTypes)Linkage, Name,
824 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000825 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000826 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000827 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000828 GA->setUnnamedAddr(UnnamedAddr);
Sean Fertilec70d28b2017-10-26 15:00:26 +0000829 GA->setDSOLocal(DSOLocal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000830
Rafael Espindola54fc2982015-06-17 17:53:31 +0000831 if (Name.empty())
832 NumberedVals.push_back(GA.get());
833
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000834 if (GVal) {
835 // Verify that types agree.
836 if (GVal->getType() != GA->getType())
837 return Error(
838 ExplicitTypeLoc,
839 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000840
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841 // If they agree, just RAUW the old value with the alias and remove the
842 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000843 GVal->replaceAllUsesWith(GA.get());
844 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000846
Chris Lattnerac161bf2009-01-02 07:01:27 +0000847 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000848 if (IsAlias)
849 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
850 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000851 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000852 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000853
Rafael Espindolaaa273822014-05-09 21:49:17 +0000854 // The module owns this now
855 GA.release();
856
Chris Lattnerac161bf2009-01-02 07:01:27 +0000857 return false;
858}
859
860/// ParseGlobal
Sean Fertilec70d28b2017-10-26 15:00:26 +0000861/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
862/// OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000863/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Javed Absarf3d79042017-05-11 12:28:08 +0000864/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
Sean Fertilec70d28b2017-10-26 15:00:26 +0000865/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
866/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
867/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
868/// Const OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +0000869///
Eric Christopher536f0a92015-05-28 23:07:39 +0000870/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000871/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872///
873bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
874 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000875 unsigned Visibility, unsigned DLLStorageClass,
Sean Fertilec70d28b2017-10-26 15:00:26 +0000876 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000877 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000878 if (!isValidVisibilityForLinkage(Visibility, Linkage))
879 return Error(NameLoc,
880 "symbol with local linkage must have default visibility");
881
Chris Lattnerac161bf2009-01-02 07:01:27 +0000882 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000883 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000884 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000885 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000886
Craig Topper2617dcc2014-04-15 06:32:26 +0000887 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000888 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000889 ParseOptionalToken(lltok::kw_externally_initialized,
890 IsExternallyInitialized,
891 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 ParseGlobalType(IsConstant) ||
893 ParseType(Ty, TyLoc))
894 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000895
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 // If the linkage is specified and is external, then no initializer is
897 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000898 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000899 if (!HasLinkage ||
900 !GlobalValue::isValidDeclarationLinkage(
901 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000902 if (ParseGlobalValue(Ty, Init))
903 return true;
904 }
905
David Majnemer49b3d9b2015-02-16 08:41:08 +0000906 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000907 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000908
David Majnemer598bd052014-12-09 05:56:09 +0000909 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000910
911 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000912 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000913 GVal = M->getNamedValue(Name);
914 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000915 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000916 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000917 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000918 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000919 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000920 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000921 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000922 ForwardRefValIDs.erase(I);
923 }
924 }
925
David Majnemer598bd052014-12-09 05:56:09 +0000926 GlobalVariable *GV;
927 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000928 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
929 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000930 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000931 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000932 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000933 return Error(TyLoc,
934 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000935
David Majnemer598bd052014-12-09 05:56:09 +0000936 GV = cast<GlobalVariable>(GVal);
937
Chris Lattnerac161bf2009-01-02 07:01:27 +0000938 // Move the forward-reference to the correct spot in the module.
939 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
940 }
941
942 if (Name.empty())
943 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000944
Chris Lattnerac161bf2009-01-02 07:01:27 +0000945 // Set the parsed properties on the global.
946 if (Init)
947 GV->setInitializer(Init);
948 GV->setConstant(IsConstant);
949 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
Sean Fertilec70d28b2017-10-26 15:00:26 +0000950 GV->setDSOLocal(DSOLocal);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000951 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000952 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000953 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000954 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000955 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000956
Chris Lattnerac161bf2009-01-02 07:01:27 +0000957 // Parse attributes on the global.
958 while (Lex.getKind() == lltok::comma) {
959 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000960
Chris Lattnerac161bf2009-01-02 07:01:27 +0000961 if (Lex.getKind() == lltok::kw_section) {
962 Lex.Lex();
963 GV->setSection(Lex.getStrVal());
964 if (ParseToken(lltok::StringConstant, "expected global section string"))
965 return true;
966 } else if (Lex.getKind() == lltok::kw_align) {
967 unsigned Alignment;
968 if (ParseOptionalAlignment(Alignment)) return true;
969 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000970 } else if (Lex.getKind() == lltok::MetadataVar) {
971 if (ParseGlobalObjectMetadataAttachment(*GV))
972 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000973 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000974 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000975 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000976 return true;
977 if (C)
978 GV->setComdat(C);
979 else
980 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000981 }
982 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000983
Javed Absarf3d79042017-05-11 12:28:08 +0000984 AttrBuilder Attrs;
985 LocTy BuiltinLoc;
986 std::vector<unsigned> FwdRefAttrGrps;
987 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
988 return true;
989 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
990 GV->setAttributes(AttributeSet::get(Context, Attrs));
991 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
992 }
993
Chris Lattnerac161bf2009-01-02 07:01:27 +0000994 return false;
995}
996
Bill Wendling63b88192013-02-06 06:52:58 +0000997/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000998/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000999bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +00001000 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +00001001 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +00001002 Lex.Lex();
1003
David Majnemerb39e22b2014-12-09 18:33:57 +00001004 if (Lex.getKind() != lltok::AttrGrpID)
1005 return TokError("expected attribute group id");
1006
Bill Wendling63b88192013-02-06 06:52:58 +00001007 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +00001008 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +00001009 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +00001010 Lex.Lex();
1011
1012 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +00001013 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00001014 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +00001015 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +00001016 ParseToken(lltok::rbrace, "expected end of attribute group"))
1017 return true;
1018
Bill Wendlingb32b0412013-02-08 06:32:06 +00001019 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +00001020 return Error(AttrGrpLoc, "attribute group has no attributes");
1021
1022 return false;
1023}
1024
Bill Wendling8b0321d2013-02-08 00:52:31 +00001025/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +00001026/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +00001027bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1028 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +00001029 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +00001030 bool HaveError = false;
1031
1032 B.clear();
1033
Bill Wendling63b88192013-02-06 06:52:58 +00001034 while (true) {
1035 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001036 if (Token == lltok::kw_builtin)
1037 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001038 switch (Token) {
1039 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001040 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001041 return Error(Lex.getLoc(), "unterminated attribute group");
1042 case lltok::rbrace:
1043 // Finished.
1044 return false;
1045
Bill Wendlingb32b0412013-02-08 06:32:06 +00001046 case lltok::AttrGrpID: {
1047 // Allow a function to reference an attribute group:
1048 //
1049 // define void @foo() #1 { ... }
1050 if (inAttrGrp)
1051 HaveError |=
1052 Error(Lex.getLoc(),
1053 "cannot have an attribute group reference in an attribute group");
1054
1055 unsigned AttrGrpNum = Lex.getUIntVal();
1056 if (inAttrGrp) break;
1057
1058 // Save the reference to the attribute group. We'll fill it in later.
1059 FwdRefAttrGrps.push_back(AttrGrpNum);
1060 break;
1061 }
Bill Wendling63b88192013-02-06 06:52:58 +00001062 // Target-dependent attributes:
1063 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001064 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001065 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001066 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001067 }
1068
1069 // Target-independent attributes:
1070 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001071 // As a hack, we allow function alignment to be initially parsed as an
1072 // attribute on a function declaration/definition or added to an attribute
1073 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001074 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001075 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001076 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001077 if (ParseToken(lltok::equal, "expected '=' here") ||
1078 ParseUInt32(Alignment))
1079 return true;
1080 } else {
1081 if (ParseOptionalAlignment(Alignment))
1082 return true;
1083 }
Bill Wendling63b88192013-02-06 06:52:58 +00001084 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001085 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001086 }
1087 case lltok::kw_alignstack: {
1088 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001089 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001090 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001091 if (ParseToken(lltok::equal, "expected '=' here") ||
1092 ParseUInt32(Alignment))
1093 return true;
1094 } else {
1095 if (ParseOptionalStackAlignment(Alignment))
1096 return true;
1097 }
Bill Wendling63b88192013-02-06 06:52:58 +00001098 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001099 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001100 }
George Burgess IV278199f2016-04-12 01:05:35 +00001101 case lltok::kw_allocsize: {
1102 unsigned ElemSizeArg;
1103 Optional<unsigned> NumElemsArg;
1104 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1105 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1106 return true;
1107 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1108 continue;
1109 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001110 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1111 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1112 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1113 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1114 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001115 case lltok::kw_inaccessiblememonly:
1116 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1117 case lltok::kw_inaccessiblemem_or_argmemonly:
1118 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001119 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1120 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1121 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1122 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1123 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1124 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1125 case lltok::kw_noimplicitfloat:
1126 B.addAttribute(Attribute::NoImplicitFloat); break;
1127 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1128 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1129 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1130 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001131 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001132 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1133 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1134 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1135 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1136 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1137 case lltok::kw_returns_twice:
1138 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001139 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001140 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1141 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1142 case lltok::kw_sspstrong:
1143 B.addAttribute(Attribute::StackProtectStrong); break;
1144 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1145 case lltok::kw_sanitize_address:
1146 B.addAttribute(Attribute::SanitizeAddress); break;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001147 case lltok::kw_sanitize_hwaddress:
1148 B.addAttribute(Attribute::SanitizeHWAddress); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001149 case lltok::kw_sanitize_thread:
1150 B.addAttribute(Attribute::SanitizeThread); break;
1151 case lltok::kw_sanitize_memory:
1152 B.addAttribute(Attribute::SanitizeMemory); break;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001153 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001154 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001155 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001156
1157 // Error handling.
1158 case lltok::kw_inreg:
1159 case lltok::kw_signext:
1160 case lltok::kw_zeroext:
1161 HaveError |=
1162 Error(Lex.getLoc(),
1163 "invalid use of attribute on a function");
1164 break;
1165 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001166 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001167 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001168 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001169 case lltok::kw_nest:
1170 case lltok::kw_noalias:
1171 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001172 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001173 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001174 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001175 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001176 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001177 HaveError |=
1178 Error(Lex.getLoc(),
1179 "invalid use of parameter-only attribute on a function");
1180 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001181 }
1182
1183 Lex.Lex();
1184 }
1185}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001186
1187//===----------------------------------------------------------------------===//
1188// GlobalValue Reference/Resolution Routines.
1189//===----------------------------------------------------------------------===//
1190
Karl Schimpf77729782015-09-03 18:06:44 +00001191static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1192 const std::string &Name) {
1193 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1194 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1195 else
1196 return new GlobalVariable(*M, PTy->getElementType(), false,
1197 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1198 nullptr, GlobalVariable::NotThreadLocal,
1199 PTy->getAddressSpace());
1200}
1201
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202/// GetGlobalVal - Get a value with the specified name or ID, creating a
1203/// forward reference record if needed. This can return null if the value
1204/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001205GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001207 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001208 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001209 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001210 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001211 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001212
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 // Look this name up in the normal function symbol table.
1214 GlobalValue *Val =
1215 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001216
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 // If this is a forward reference for the value, see if we already created a
1218 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001219 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001220 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221 if (I != ForwardRefVals.end())
1222 Val = I->second.first;
1223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 // If we have the value in the symbol table or fwd-ref table, return it.
1226 if (Val) {
1227 if (Val->getType() == Ty) return Val;
1228 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001229 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001230 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001232
Chris Lattnerac161bf2009-01-02 07:01:27 +00001233 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001234 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001235 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1236 return FwdVal;
1237}
1238
Chris Lattner229907c2011-07-18 04:54:35 +00001239GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1240 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001241 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001242 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001243 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001245
Craig Topper2617dcc2014-04-15 06:32:26 +00001246 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001247
Chris Lattnerac161bf2009-01-02 07:01:27 +00001248 // If this is a forward reference for the value, see if we already created a
1249 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001250 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001251 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001252 if (I != ForwardRefValIDs.end())
1253 Val = I->second.first;
1254 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001255
Chris Lattnerac161bf2009-01-02 07:01:27 +00001256 // If we have the value in the symbol table or fwd-ref table, return it.
1257 if (Val) {
1258 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001259 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001260 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001261 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001263
Chris Lattnerac161bf2009-01-02 07:01:27 +00001264 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001265 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001266 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1267 return FwdVal;
1268}
1269
Chris Lattnerac161bf2009-01-02 07:01:27 +00001270//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001271// Comdat Reference/Resolution Routines.
1272//===----------------------------------------------------------------------===//
1273
1274Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1275 // Look this name up in the comdat symbol table.
1276 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1277 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1278 if (I != ComdatSymTab.end())
1279 return &I->second;
1280
1281 // Otherwise, create a new forward reference for this value and remember it.
1282 Comdat *C = M->getOrInsertComdat(Name);
1283 ForwardRefComdats[Name] = Loc;
1284 return C;
1285}
1286
David Majnemerdad0a642014-06-27 18:19:56 +00001287//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001288// Helper Routines.
1289//===----------------------------------------------------------------------===//
1290
1291/// ParseToken - If the current token has the specified kind, eat it and return
1292/// success. Otherwise, emit the specified error and return failure.
1293bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1294 if (Lex.getKind() != T)
1295 return TokError(ErrMsg);
1296 Lex.Lex();
1297 return false;
1298}
1299
Chris Lattner3822f632009-01-02 08:05:26 +00001300/// ParseStringConstant
1301/// ::= StringConstant
1302bool LLParser::ParseStringConstant(std::string &Result) {
1303 if (Lex.getKind() != lltok::StringConstant)
1304 return TokError("expected string constant");
1305 Result = Lex.getStrVal();
1306 Lex.Lex();
1307 return false;
1308}
1309
1310/// ParseUInt32
1311/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001312bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001313 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1314 return TokError("expected integer");
1315 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1316 if (Val64 != unsigned(Val64))
1317 return TokError("expected 32-bit integer (too large)");
1318 Val = Val64;
1319 Lex.Lex();
1320 return false;
1321}
1322
Hal Finkelb0407ba2014-07-18 15:51:28 +00001323/// ParseUInt64
1324/// ::= uint64
1325bool LLParser::ParseUInt64(uint64_t &Val) {
1326 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1327 return TokError("expected integer");
1328 Val = Lex.getAPSIntVal().getLimitedValue();
1329 Lex.Lex();
1330 return false;
1331}
1332
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001333/// ParseTLSModel
1334/// := 'localdynamic'
1335/// := 'initialexec'
1336/// := 'localexec'
1337bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1338 switch (Lex.getKind()) {
1339 default:
1340 return TokError("expected localdynamic, initialexec or localexec");
1341 case lltok::kw_localdynamic:
1342 TLM = GlobalVariable::LocalDynamicTLSModel;
1343 break;
1344 case lltok::kw_initialexec:
1345 TLM = GlobalVariable::InitialExecTLSModel;
1346 break;
1347 case lltok::kw_localexec:
1348 TLM = GlobalVariable::LocalExecTLSModel;
1349 break;
1350 }
1351
1352 Lex.Lex();
1353 return false;
1354}
1355
1356/// ParseOptionalThreadLocal
1357/// := /*empty*/
1358/// := 'thread_local'
1359/// := 'thread_local' '(' tlsmodel ')'
1360bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1361 TLM = GlobalVariable::NotThreadLocal;
1362 if (!EatIfPresent(lltok::kw_thread_local))
1363 return false;
1364
1365 TLM = GlobalVariable::GeneralDynamicTLSModel;
1366 if (Lex.getKind() == lltok::lparen) {
1367 Lex.Lex();
1368 return ParseTLSModel(TLM) ||
1369 ParseToken(lltok::rparen, "expected ')' after thread local model");
1370 }
1371 return false;
1372}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001373
1374/// ParseOptionalAddrSpace
1375/// := /*empty*/
1376/// := 'addrspace' '(' uint32 ')'
1377bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1378 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001379 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001380 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001382 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001383 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001384}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385
Artur Pilipenko17376c42015-08-03 14:31:49 +00001386/// ParseStringAttribute
1387/// := StringConstant
1388/// := StringConstant '=' StringConstant
1389bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1390 std::string Attr = Lex.getStrVal();
1391 Lex.Lex();
1392 std::string Val;
1393 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1394 return true;
1395 B.addAttribute(Attr, Val);
1396 return false;
1397}
1398
Bill Wendling34c2eb22012-12-04 23:40:58 +00001399/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1400bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1401 bool HaveError = false;
1402
1403 B.clear();
1404
Eugene Zelenko1804a772016-08-25 00:45:04 +00001405 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001406 lltok::Kind Token = Lex.getKind();
1407 switch (Token) {
1408 default: // End of attributes.
1409 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001410 case lltok::StringConstant: {
1411 if (ParseStringAttribute(B))
1412 return true;
1413 continue;
1414 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001415 case lltok::kw_align: {
1416 unsigned Alignment;
1417 if (ParseOptionalAlignment(Alignment))
1418 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001419 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001420 continue;
1421 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001422 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001423 case lltok::kw_dereferenceable: {
1424 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001425 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001426 return true;
1427 B.addDereferenceableAttr(Bytes);
1428 continue;
1429 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001430 case lltok::kw_dereferenceable_or_null: {
1431 uint64_t Bytes;
1432 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1433 return true;
1434 B.addDereferenceableOrNullAttr(Bytes);
1435 continue;
1436 }
Reid Klecknera534a382013-12-19 02:14:12 +00001437 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001438 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1439 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1440 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1441 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001442 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001443 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1444 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001445 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001446 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1447 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001448 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001449 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001450 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001451 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001452
Stephen Lin7577ed52013-04-20 13:16:13 +00001453 case lltok::kw_alignstack:
1454 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001455 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001456 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001457 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001458 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001459 case lltok::kw_minsize:
1460 case lltok::kw_naked:
1461 case lltok::kw_nobuiltin:
1462 case lltok::kw_noduplicate:
1463 case lltok::kw_noimplicitfloat:
1464 case lltok::kw_noinline:
1465 case lltok::kw_nonlazybind:
1466 case lltok::kw_noredzone:
1467 case lltok::kw_noreturn:
1468 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001469 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001470 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001471 case lltok::kw_returns_twice:
1472 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001473 case lltok::kw_sanitize_hwaddress:
Stephen Lin7577ed52013-04-20 13:16:13 +00001474 case lltok::kw_sanitize_memory:
1475 case lltok::kw_sanitize_thread:
1476 case lltok::kw_ssp:
1477 case lltok::kw_sspreq:
1478 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001479 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001480 case lltok::kw_strictfp:
Stephen Lin7577ed52013-04-20 13:16:13 +00001481 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001482 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1483 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001484 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001485
Bill Wendling34c2eb22012-12-04 23:40:58 +00001486 Lex.Lex();
1487 }
1488}
1489
1490/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1491bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1492 bool HaveError = false;
1493
1494 B.clear();
1495
Eugene Zelenko1804a772016-08-25 00:45:04 +00001496 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001497 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001498 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001499 default: // End of attributes.
1500 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001501 case lltok::StringConstant: {
1502 if (ParseStringAttribute(B))
1503 return true;
1504 continue;
1505 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001506 case lltok::kw_dereferenceable: {
1507 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001508 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001509 return true;
1510 B.addDereferenceableAttr(Bytes);
1511 continue;
1512 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001513 case lltok::kw_dereferenceable_or_null: {
1514 uint64_t Bytes;
1515 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1516 return true;
1517 B.addDereferenceableOrNullAttr(Bytes);
1518 continue;
1519 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001520 case lltok::kw_align: {
1521 unsigned Alignment;
1522 if (ParseOptionalAlignment(Alignment))
1523 return true;
1524 B.addAlignmentAttr(Alignment);
1525 continue;
1526 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001527 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1528 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001529 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001530 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1531 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001532
Bill Wendling34c2eb22012-12-04 23:40:58 +00001533 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001534 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001535 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001536 case lltok::kw_nest:
1537 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001538 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001539 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001540 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001541 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001542 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001543 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001544
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001545 case lltok::kw_alignstack:
1546 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001547 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001548 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001549 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001550 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001551 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001552 case lltok::kw_minsize:
1553 case lltok::kw_naked:
1554 case lltok::kw_nobuiltin:
1555 case lltok::kw_noduplicate:
1556 case lltok::kw_noimplicitfloat:
1557 case lltok::kw_noinline:
1558 case lltok::kw_nonlazybind:
1559 case lltok::kw_noredzone:
1560 case lltok::kw_noreturn:
1561 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001562 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001563 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001564 case lltok::kw_returns_twice:
1565 case lltok::kw_sanitize_address:
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001566 case lltok::kw_sanitize_hwaddress:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001567 case lltok::kw_sanitize_memory:
1568 case lltok::kw_sanitize_thread:
1569 case lltok::kw_ssp:
1570 case lltok::kw_sspreq:
1571 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001572 case lltok::kw_safestack:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001573 case lltok::kw_strictfp:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001574 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001575 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001576 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001577
1578 case lltok::kw_readnone:
1579 case lltok::kw_readonly:
1580 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001581 }
1582
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583 Lex.Lex();
1584 }
1585}
1586
Rafael Espindolac6269912016-05-10 17:16:45 +00001587static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1588 HasLinkage = true;
1589 switch (Kind) {
1590 default:
1591 HasLinkage = false;
1592 return GlobalValue::ExternalLinkage;
1593 case lltok::kw_private:
1594 return GlobalValue::PrivateLinkage;
1595 case lltok::kw_internal:
1596 return GlobalValue::InternalLinkage;
1597 case lltok::kw_weak:
1598 return GlobalValue::WeakAnyLinkage;
1599 case lltok::kw_weak_odr:
1600 return GlobalValue::WeakODRLinkage;
1601 case lltok::kw_linkonce:
1602 return GlobalValue::LinkOnceAnyLinkage;
1603 case lltok::kw_linkonce_odr:
1604 return GlobalValue::LinkOnceODRLinkage;
1605 case lltok::kw_available_externally:
1606 return GlobalValue::AvailableExternallyLinkage;
1607 case lltok::kw_appending:
1608 return GlobalValue::AppendingLinkage;
1609 case lltok::kw_common:
1610 return GlobalValue::CommonLinkage;
1611 case lltok::kw_extern_weak:
1612 return GlobalValue::ExternalWeakLinkage;
1613 case lltok::kw_external:
1614 return GlobalValue::ExternalLinkage;
1615 }
1616}
1617
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618/// ParseOptionalLinkage
1619/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001620/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621/// ::= 'internal'
1622/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001623/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001624/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001625/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001626/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001627/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001628/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001629/// ::= 'extern_weak'
1630/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001631bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1632 unsigned &Visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001633 unsigned &DLLStorageClass,
1634 bool &DSOLocal) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001635 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1636 if (HasLinkage)
1637 Lex.Lex();
Sean Fertilec70d28b2017-10-26 15:00:26 +00001638 ParseOptionalDSOLocal(DSOLocal);
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001639 ParseOptionalVisibility(Visibility);
1640 ParseOptionalDLLStorageClass(DLLStorageClass);
Sean Fertilec70d28b2017-10-26 15:00:26 +00001641
1642 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1643 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1644 }
1645
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646 return false;
1647}
1648
Sean Fertilec70d28b2017-10-26 15:00:26 +00001649void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1650 switch (Lex.getKind()) {
1651 default:
1652 DSOLocal = false;
1653 break;
1654 case lltok::kw_dso_local:
1655 DSOLocal = true;
1656 Lex.Lex();
1657 break;
1658 case lltok::kw_dso_preemptable:
1659 DSOLocal = false;
1660 Lex.Lex();
1661 break;
1662 }
1663}
1664
Chris Lattnerac161bf2009-01-02 07:01:27 +00001665/// ParseOptionalVisibility
1666/// ::= /*empty*/
1667/// ::= 'default'
1668/// ::= 'hidden'
1669/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001670///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001671void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001672 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001673 default:
1674 Res = GlobalValue::DefaultVisibility;
1675 return;
1676 case lltok::kw_default:
1677 Res = GlobalValue::DefaultVisibility;
1678 break;
1679 case lltok::kw_hidden:
1680 Res = GlobalValue::HiddenVisibility;
1681 break;
1682 case lltok::kw_protected:
1683 Res = GlobalValue::ProtectedVisibility;
1684 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 }
1686 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001687}
1688
Nico Rieck7157bb72014-01-14 15:22:47 +00001689/// ParseOptionalDLLStorageClass
1690/// ::= /*empty*/
1691/// ::= 'dllimport'
1692/// ::= 'dllexport'
1693///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001694void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001695 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001696 default:
1697 Res = GlobalValue::DefaultStorageClass;
1698 return;
1699 case lltok::kw_dllimport:
1700 Res = GlobalValue::DLLImportStorageClass;
1701 break;
1702 case lltok::kw_dllexport:
1703 Res = GlobalValue::DLLExportStorageClass;
1704 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001705 }
1706 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001707}
1708
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709/// ParseOptionalCallingConv
1710/// ::= /*empty*/
1711/// ::= 'ccc'
1712/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001713/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001714/// ::= 'coldcc'
1715/// ::= 'x86_stdcallcc'
1716/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001717/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001718/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001719/// ::= 'arm_apcscc'
1720/// ::= 'arm_aapcscc'
1721/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001722/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001723/// ::= 'avr_intrcc'
1724/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001725/// ::= 'ptx_kernel'
1726/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001727/// ::= 'spir_func'
1728/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001729/// ::= 'x86_64_sysvcc'
Martin Storsjo2f24e932017-07-17 20:05:19 +00001730/// ::= 'win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001731/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001732/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001733/// ::= 'preserve_mostcc'
1734/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001735/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001736/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001737/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001738/// ::= 'hhvmcc'
1739/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001740/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001741/// ::= 'amdgpu_vs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001742/// ::= 'amdgpu_ls'
Marek Olsaka302a7362017-05-02 15:41:10 +00001743/// ::= 'amdgpu_hs'
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001744/// ::= 'amdgpu_es'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001745/// ::= 'amdgpu_gs'
1746/// ::= 'amdgpu_ps'
1747/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001748/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001749/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001750///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001751bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 switch (Lex.getKind()) {
1753 default: CC = CallingConv::C; return false;
1754 case lltok::kw_ccc: CC = CallingConv::C; break;
1755 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1756 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1757 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1758 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001759 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001760 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001761 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001762 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1763 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1764 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001765 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001766 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1767 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001768 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1769 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001770 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1771 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001772 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001773 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +00001774 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001775 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001776 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001777 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1778 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001779 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001780 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001781 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001782 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1783 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001784 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001785 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001786 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
Marek Olsaka302a7362017-05-02 15:41:10 +00001787 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +00001788 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001789 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1790 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1791 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001792 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001793 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001794 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001795 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001796 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001797 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001798
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799 Lex.Lex();
1800 return false;
1801}
1802
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001803/// ParseMetadataAttachment
1804/// ::= !dbg !42
1805bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1806 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1807
1808 std::string Name = Lex.getStrVal();
1809 Kind = M->getMDKindID(Name);
1810 Lex.Lex();
1811
1812 return ParseMDNode(MD);
1813}
1814
Chris Lattner5c427632009-12-30 05:31:19 +00001815/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001816/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001817bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001818 do {
1819 if (Lex.getKind() != lltok::MetadataVar)
1820 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001821
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001822 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001823 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001824 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001825 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001826
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001827 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001828 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001829 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001830
Chris Lattner596760d2009-12-29 21:25:40 +00001831 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001832 } while (EatIfPresent(lltok::comma));
1833 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001834}
1835
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001836/// ParseGlobalObjectMetadataAttachment
1837/// ::= !dbg !57
1838bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1839 unsigned MDK;
1840 MDNode *N;
1841 if (ParseMetadataAttachment(MDK, N))
1842 return true;
1843
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001844 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001845 return false;
1846}
1847
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001848/// ParseOptionalFunctionMetadata
1849/// ::= (!dbg !57)*
1850bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001851 while (Lex.getKind() == lltok::MetadataVar)
1852 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001853 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001854 return false;
1855}
1856
Chris Lattnerac161bf2009-01-02 07:01:27 +00001857/// ParseOptionalAlignment
1858/// ::= /* empty */
1859/// ::= 'align' 4
1860bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1861 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001862 if (!EatIfPresent(lltok::kw_align))
1863 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001864 LocTy AlignLoc = Lex.getLoc();
1865 if (ParseUInt32(Alignment)) return true;
1866 if (!isPowerOf2_32(Alignment))
1867 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001868 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001869 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001870 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001871}
1872
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001873/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001874/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001875/// ::= AttrKind '(' 4 ')'
1876///
1877/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1878bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1879 uint64_t &Bytes) {
1880 assert((AttrKind == lltok::kw_dereferenceable ||
1881 AttrKind == lltok::kw_dereferenceable_or_null) &&
1882 "contract!");
1883
Hal Finkelb0407ba2014-07-18 15:51:28 +00001884 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001885 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001886 return false;
1887 LocTy ParenLoc = Lex.getLoc();
1888 if (!EatIfPresent(lltok::lparen))
1889 return Error(ParenLoc, "expected '('");
1890 LocTy DerefLoc = Lex.getLoc();
1891 if (ParseUInt64(Bytes)) return true;
1892 ParenLoc = Lex.getLoc();
1893 if (!EatIfPresent(lltok::rparen))
1894 return Error(ParenLoc, "expected ')'");
1895 if (!Bytes)
1896 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1897 return false;
1898}
1899
Chris Lattnerb2f39502009-12-30 05:44:30 +00001900/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001901/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001902/// ::= ',' align 4
1903///
1904/// This returns with AteExtraComma set to true if it ate an excess comma at the
1905/// end.
1906bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1907 bool &AteExtraComma) {
1908 AteExtraComma = false;
1909 while (EatIfPresent(lltok::comma)) {
1910 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001911 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001912 AteExtraComma = true;
1913 return false;
1914 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001915
Chris Lattner95b0ff42010-04-23 00:50:50 +00001916 if (Lex.getKind() != lltok::kw_align)
1917 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001918
Chris Lattner95b0ff42010-04-23 00:50:50 +00001919 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001920 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001921
Devang Patelea8a4b92009-09-17 23:04:48 +00001922 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923}
1924
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001925/// ParseOptionalCommaAddrSpace
1926/// ::=
1927/// ::= ',' addrspace(1)
1928///
1929/// This returns with AteExtraComma set to true if it ate an excess comma at the
1930/// end.
1931bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1932 LocTy &Loc,
1933 bool &AteExtraComma) {
1934 AteExtraComma = false;
1935 while (EatIfPresent(lltok::comma)) {
1936 // Metadata at the end is an early exit.
1937 if (Lex.getKind() == lltok::MetadataVar) {
1938 AteExtraComma = true;
1939 return false;
1940 }
1941
1942 Loc = Lex.getLoc();
1943 if (Lex.getKind() != lltok::kw_addrspace)
1944 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1945
1946 if (ParseOptionalAddrSpace(AddrSpace))
1947 return true;
1948 }
1949
1950 return false;
1951}
1952
George Burgess IV278199f2016-04-12 01:05:35 +00001953bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1954 Optional<unsigned> &HowManyArg) {
1955 Lex.Lex();
1956
1957 auto StartParen = Lex.getLoc();
1958 if (!EatIfPresent(lltok::lparen))
1959 return Error(StartParen, "expected '('");
1960
1961 if (ParseUInt32(BaseSizeArg))
1962 return true;
1963
1964 if (EatIfPresent(lltok::comma)) {
1965 auto HowManyAt = Lex.getLoc();
1966 unsigned HowMany;
1967 if (ParseUInt32(HowMany))
1968 return true;
1969 if (HowMany == BaseSizeArg)
1970 return Error(HowManyAt,
1971 "'allocsize' indices can't refer to the same parameter");
1972 HowManyArg = HowMany;
1973 } else
1974 HowManyArg = None;
1975
1976 auto EndParen = Lex.getLoc();
1977 if (!EatIfPresent(lltok::rparen))
1978 return Error(EndParen, "expected ')'");
1979 return false;
1980}
1981
Eli Friedmanfee02c62011-07-25 23:16:38 +00001982/// ParseScopeAndOrdering
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001983/// if isAtomic: ::= SyncScope? AtomicOrdering
Eli Friedmanfee02c62011-07-25 23:16:38 +00001984/// else: ::=
1985///
1986/// This sets Scope and Ordering to the parsed values.
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001987bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
Eli Friedmanfee02c62011-07-25 23:16:38 +00001988 AtomicOrdering &Ordering) {
1989 if (!isAtomic)
1990 return false;
1991
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001992 return ParseScope(SSID) || ParseOrdering(Ordering);
1993}
Tim Northovere94a5182014-03-11 10:48:52 +00001994
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001995/// ParseScope
1996/// ::= syncscope("singlethread" | "<target scope>")?
1997///
1998/// This sets synchronization scope ID to the ID of the parsed value.
1999bool LLParser::ParseScope(SyncScope::ID &SSID) {
2000 SSID = SyncScope::System;
2001 if (EatIfPresent(lltok::kw_syncscope)) {
2002 auto StartParenAt = Lex.getLoc();
2003 if (!EatIfPresent(lltok::lparen))
2004 return Error(StartParenAt, "Expected '(' in syncscope");
2005
2006 std::string SSN;
2007 auto SSNAt = Lex.getLoc();
2008 if (ParseStringConstant(SSN))
2009 return Error(SSNAt, "Expected synchronization scope name");
2010
2011 auto EndParenAt = Lex.getLoc();
2012 if (!EatIfPresent(lltok::rparen))
2013 return Error(EndParenAt, "Expected ')' in syncscope");
2014
2015 SSID = Context.getOrInsertSyncScopeID(SSN);
2016 }
2017
2018 return false;
Tim Northovere94a5182014-03-11 10:48:52 +00002019}
2020
2021/// ParseOrdering
2022/// ::= AtomicOrdering
2023///
2024/// This sets Ordering to the parsed value.
2025bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00002026 switch (Lex.getKind()) {
2027 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00002028 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2029 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2030 // Not specified yet:
2031 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2032 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2033 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2034 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2035 case lltok::kw_seq_cst:
2036 Ordering = AtomicOrdering::SequentiallyConsistent;
2037 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002038 }
2039 Lex.Lex();
2040 return false;
2041}
2042
Charles Davisbe5557e2010-02-12 00:31:15 +00002043/// ParseOptionalStackAlignment
2044/// ::= /* empty */
2045/// ::= 'alignstack' '(' 4 ')'
2046bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2047 Alignment = 0;
2048 if (!EatIfPresent(lltok::kw_alignstack))
2049 return false;
2050 LocTy ParenLoc = Lex.getLoc();
2051 if (!EatIfPresent(lltok::lparen))
2052 return Error(ParenLoc, "expected '('");
2053 LocTy AlignLoc = Lex.getLoc();
2054 if (ParseUInt32(Alignment)) return true;
2055 ParenLoc = Lex.getLoc();
2056 if (!EatIfPresent(lltok::rparen))
2057 return Error(ParenLoc, "expected ')'");
2058 if (!isPowerOf2_32(Alignment))
2059 return Error(AlignLoc, "stack alignment is not a power of two");
2060 return false;
2061}
Devang Patelea8a4b92009-09-17 23:04:48 +00002062
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002063/// ParseIndexList - This parses the index list for an insert/extractvalue
2064/// instruction. This sets AteExtraComma in the case where we eat an extra
2065/// comma at the end of the line and find that it is followed by metadata.
2066/// Clients that don't allow metadata can call the version of this function that
2067/// only takes one argument.
2068///
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069/// ParseIndexList
2070/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002071///
2072bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2073 bool &AteExtraComma) {
2074 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002075
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076 if (Lex.getKind() != lltok::comma)
2077 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002078
Chris Lattner3822f632009-01-02 08:05:26 +00002079 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002080 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00002081 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00002082 AteExtraComma = true;
2083 return false;
2084 }
Nick Lewycky83e47112010-09-29 23:32:20 +00002085 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00002086 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 Indices.push_back(Idx);
2088 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002089
Chris Lattnerac161bf2009-01-02 07:01:27 +00002090 return false;
2091}
2092
2093//===----------------------------------------------------------------------===//
2094// Type Parsing.
2095//===----------------------------------------------------------------------===//
2096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002097/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002098bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 switch (Lex.getKind()) {
2101 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002102 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002103 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002106 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002107 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109 // Type ::= StructType
2110 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002111 return true;
2112 break;
2113 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002114 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 Lex.Lex(); // eat the lsquare.
2116 if (ParseArrayVectorType(Result, false))
2117 return true;
2118 break;
2119 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002120 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002121 Lex.Lex();
2122 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002123 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002124 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126 } else if (ParseArrayVectorType(Result, true))
2127 return true;
2128 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002129 case lltok::LocalVar: {
2130 // Type ::= %foo
2131 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002132
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002133 // If the type hasn't been defined yet, create a forward definition and
2134 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002135 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002136 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002137 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002139 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 Lex.Lex();
2141 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002143
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002144 case lltok::LocalVarID: {
2145 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002146 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002147
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002148 // If the type hasn't been defined yet, create a forward definition and
2149 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002150 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002151 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002152 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002154 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 Lex.Lex();
2156 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 }
2158 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002159
2160 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002161 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 switch (Lex.getKind()) {
2163 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002164 default:
2165 if (!AllowVoid && Result->isVoidTy())
2166 return Error(TypeLoc, "void type only allowed for function results");
2167 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002169 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002170 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002171 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002172 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002173 if (Result->isVoidTy())
2174 return TokError("pointers to void are invalid - use i8* instead");
2175 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002176 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002177 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002178 Lex.Lex();
2179 break;
2180
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002181 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002183 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002185 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002186 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002187 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002188 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002189 unsigned AddrSpace;
2190 if (ParseOptionalAddrSpace(AddrSpace) ||
2191 ParseToken(lltok::star, "expected '*' in address space"))
2192 return true;
2193
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002194 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002195 break;
2196 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002197
Chris Lattnerac161bf2009-01-02 07:01:27 +00002198 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2199 case lltok::lparen:
2200 if (ParseFunctionType(Result))
2201 return true;
2202 break;
2203 }
2204 }
2205}
2206
2207/// ParseParameterList
2208/// ::= '(' ')'
2209/// ::= '(' Arg (',' Arg)* ')'
2210/// Arg
2211/// ::= Type OptionalAttributes Value OptionalAttributes
2212bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002213 PerFunctionState &PFS, bool IsMustTailCall,
2214 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002215 if (ParseToken(lltok::lparen, "expected '(' in call"))
2216 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002217
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 while (Lex.getKind() != lltok::rparen) {
2219 // If this isn't the first argument, we need a comma.
2220 if (!ArgList.empty() &&
2221 ParseToken(lltok::comma, "expected ',' in argument list"))
2222 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002223
Reid Kleckner83498642014-08-26 00:33:28 +00002224 // Parse an ellipsis if this is a musttail call in a variadic function.
2225 if (Lex.getKind() == lltok::dotdotdot) {
2226 const char *Msg = "unexpected ellipsis in argument list for ";
2227 if (!IsMustTailCall)
2228 return TokError(Twine(Msg) + "non-musttail call");
2229 if (!InVarArgsFunc)
2230 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2231 Lex.Lex(); // Lex the '...', it is purely for readability.
2232 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2233 }
2234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 // Parse the argument.
2236 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002237 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002238 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002240 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002242
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002243 if (ArgTy->isMetadataTy()) {
2244 if (ParseMetadataAsValue(V, PFS))
2245 return true;
2246 } else {
2247 // Otherwise, handle normal operands.
2248 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2249 return true;
2250 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002251 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002252 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 }
2254
Reid Kleckner83498642014-08-26 00:33:28 +00002255 if (IsMustTailCall && InVarArgsFunc)
2256 return TokError("expected '...' at end of argument list for musttail call "
2257 "in varargs function");
2258
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 Lex.Lex(); // Lex the ')'.
2260 return false;
2261}
2262
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002263/// ParseOptionalOperandBundles
2264/// ::= /*empty*/
2265/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2266///
2267/// OperandBundle
2268/// ::= bundle-tag '(' ')'
2269/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2270///
2271/// bundle-tag ::= String Constant
2272bool LLParser::ParseOptionalOperandBundles(
2273 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2274 LocTy BeginLoc = Lex.getLoc();
2275 if (!EatIfPresent(lltok::lsquare))
2276 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002278 while (Lex.getKind() != lltok::rsquare) {
2279 // If this isn't the first operand bundle, we need a comma.
2280 if (!BundleList.empty() &&
2281 ParseToken(lltok::comma, "expected ',' in input list"))
2282 return true;
2283
2284 std::string Tag;
2285 if (ParseStringConstant(Tag))
2286 return true;
2287
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002288 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2289 return true;
2290
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002291 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002292 while (Lex.getKind() != lltok::rparen) {
2293 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002294 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002295 ParseToken(lltok::comma, "expected ',' in input list"))
2296 return true;
2297
2298 Type *Ty = nullptr;
2299 Value *Input = nullptr;
2300 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2301 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002302 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002303 }
2304
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002305 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2306
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002307 Lex.Lex(); // Lex the ')'.
2308 }
2309
2310 if (BundleList.empty())
2311 return Error(BeginLoc, "operand bundle set must not be empty");
2312
2313 Lex.Lex(); // Lex the ']'.
2314 return false;
2315}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316
Chris Lattner2ed06b42009-01-05 18:34:07 +00002317/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002318/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319/// ::= '(' ArgTypeListI ')'
2320/// ArgTypeListI
2321/// ::= /*empty*/
2322/// ::= '...'
2323/// ::= ArgTypeList ',' '...'
2324/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002325///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2327 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002328 isVarArg = false;
2329 assert(Lex.getKind() == lltok::lparen);
2330 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002331
Chris Lattnerac161bf2009-01-02 07:01:27 +00002332 if (Lex.getKind() == lltok::rparen) {
2333 // empty
2334 } else if (Lex.getKind() == lltok::dotdotdot) {
2335 isVarArg = true;
2336 Lex.Lex();
2337 } else {
2338 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002339 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002340 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002343 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002344 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002345
Chris Lattnerfdd87902009-10-05 05:54:46 +00002346 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002347 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerdef19492011-06-17 06:36:20 +00002349 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 Name = Lex.getStrVal();
2351 Lex.Lex();
2352 }
Chris Lattner3822f632009-01-02 08:05:26 +00002353
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002354 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002355 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002356
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002357 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002358 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002359 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002360
Chris Lattner3822f632009-01-02 08:05:26 +00002361 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002362 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002363 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002364 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002365 break;
2366 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002367
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368 // Otherwise must be an argument type.
2369 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002370 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002371
Chris Lattnerfdd87902009-10-05 05:54:46 +00002372 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002373 return Error(TypeLoc, "argument can not have void type");
2374
Chris Lattnerdef19492011-06-17 06:36:20 +00002375 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002376 Name = Lex.getStrVal();
2377 Lex.Lex();
2378 } else {
2379 Name = "";
2380 }
Chris Lattner3822f632009-01-02 08:05:26 +00002381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002382 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002383 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002385 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002386 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002387 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002388 }
2389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002390
Chris Lattner3822f632009-01-02 08:05:26 +00002391 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002392}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002393
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394/// ParseFunctionType
2395/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 assert(Lex.getKind() == lltok::lparen);
2398
Chris Lattnerce473c72009-01-05 08:04:33 +00002399 if (!FunctionType::isValidReturnType(Result))
2400 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002402 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002404 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002406
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 // Reject names on the arguments lists.
2408 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2409 if (!ArgList[i].Name.empty())
2410 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002411 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002412 return Error(ArgList[i].Loc,
2413 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002415
Jay Foadb804a2b2011-07-12 14:06:48 +00002416 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002417 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002418 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002420 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002421 return false;
2422}
2423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002424/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2425/// other structs.
2426bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2427 SmallVector<Type*, 8> Elts;
2428 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002429
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430 Result = StructType::get(Context, Elts, Packed);
2431 return false;
2432}
2433
2434/// ParseStructDefinition - Parse a struct in a 'type' definition.
2435bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2436 std::pair<Type*, LocTy> &Entry,
2437 Type *&ResultTy) {
2438 // If the type was already defined, diagnose the redefinition.
2439 if (Entry.first && !Entry.second.isValid())
2440 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002442 // If we have opaque, just return without filling in the definition for the
2443 // struct. This counts as a definition as far as the .ll file goes.
2444 if (EatIfPresent(lltok::kw_opaque)) {
2445 // This type is being defined, so clear the location to indicate this.
2446 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002448 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002449 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002450 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002451 ResultTy = Entry.first;
2452 return false;
2453 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002454
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002455 // If the type starts with '<', then it is either a packed struct or a vector.
2456 bool isPacked = EatIfPresent(lltok::less);
2457
2458 // If we don't have a struct, then we have a random type alias, which we
2459 // accept for compatibility with old files. These types are not allowed to be
2460 // forward referenced and not allowed to be recursive.
2461 if (Lex.getKind() != lltok::lbrace) {
2462 if (Entry.first)
2463 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002464
Craig Topper2617dcc2014-04-15 06:32:26 +00002465 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002466 if (isPacked)
2467 return ParseArrayVectorType(ResultTy, true);
2468 return ParseType(ResultTy);
2469 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002470
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002471 // This type is being defined, so clear the location to indicate this.
2472 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002473
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002474 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002475 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002476 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002478 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002479
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002480 SmallVector<Type*, 8> Body;
2481 if (ParseStructBody(Body) ||
2482 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2483 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002484
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002485 STy->setBody(Body, isPacked);
2486 ResultTy = STy;
2487 return false;
2488}
2489
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002491/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002493/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002495/// ::= '<' '{' Type (',' Type)* '}' '>'
2496bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002497 assert(Lex.getKind() == lltok::lbrace);
2498 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002500 // Handle the empty struct.
2501 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002502 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503
Chris Lattnerf880ca22009-03-09 04:49:14 +00002504 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002505 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002506 if (ParseType(Ty)) return true;
2507 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002508
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002509 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002510 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002511
Chris Lattner3822f632009-01-02 08:05:26 +00002512 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002513 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002514 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002516 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002517 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002518
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002519 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002522 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523}
2524
2525/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2526/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002527/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528/// ::= '[' APSINTVAL 'x' Types ']'
2529/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002530bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2532 Lex.getAPSIntVal().getBitWidth() > 64)
2533 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002534
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 LocTy SizeLoc = Lex.getLoc();
2536 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002537 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002538
Chris Lattner3822f632009-01-02 08:05:26 +00002539 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2540 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541
2542 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002543 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002544 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002545
Chris Lattner3822f632009-01-02 08:05:26 +00002546 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2547 "expected end of sequential type"))
2548 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002549
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002551 if (Size == 0)
2552 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002553 if ((unsigned)Size != Size)
2554 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002555 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002556 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002557 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002559 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002561 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002562 }
2563 return false;
2564}
2565
2566//===----------------------------------------------------------------------===//
2567// Function Semantic Analysis.
2568//===----------------------------------------------------------------------===//
2569
Chris Lattner3432c622009-10-28 03:39:23 +00002570LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2571 int functionNumber)
2572 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573
2574 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002575 for (Argument &A : F.args())
2576 if (!A.hasName())
2577 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002578}
2579
2580LLParser::PerFunctionState::~PerFunctionState() {
2581 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002582
David Blaikie9ebdc692015-09-21 21:07:50 +00002583 for (const auto &P : ForwardRefVals) {
2584 if (isa<BasicBlock>(P.second.first))
2585 continue;
2586 P.second.first->replaceAllUsesWith(
2587 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002588 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002589 }
2590
2591 for (const auto &P : ForwardRefValIDs) {
2592 if (isa<BasicBlock>(P.second.first))
2593 continue;
2594 P.second.first->replaceAllUsesWith(
2595 UndefValue::get(P.second.first->getType()));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002596 P.second.first->deleteValue();
David Blaikie9ebdc692015-09-21 21:07:50 +00002597 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598}
2599
Chris Lattner3432c622009-10-28 03:39:23 +00002600bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002601 if (!ForwardRefVals.empty())
2602 return P.Error(ForwardRefVals.begin()->second.second,
2603 "use of undefined value '%" + ForwardRefVals.begin()->first +
2604 "'");
2605 if (!ForwardRefValIDs.empty())
2606 return P.Error(ForwardRefValIDs.begin()->second.second,
2607 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002608 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002609 return false;
2610}
2611
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612/// GetVal - Get a value with the specified name or ID, creating a
2613/// forward reference record if needed. This can return null if the value
2614/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002615Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002616 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002618 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619
Chris Lattnerac161bf2009-01-02 07:01:27 +00002620 // If this is a forward reference for the value, see if we already created a
2621 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002622 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002623 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 if (I != ForwardRefVals.end())
2625 Val = I->second.first;
2626 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002627
Chris Lattnerac161bf2009-01-02 07:01:27 +00002628 // If we have the value in the symbol table or fwd-ref table, return it.
2629 if (Val) {
2630 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002631 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 P.Error(Loc, "'%" + Name + "' is not a basic block");
2633 else
2634 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002635 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002636 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002638
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002640 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002642 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002644
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 // Otherwise, create a new forward reference for this value and remember it.
2646 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002647 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002648 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002649 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002650 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002651 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2654 return FwdVal;
2655}
2656
David Majnemer8a1c45d2015-12-12 05:38:55 +00002657Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002658 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002659 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002660
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 // If this is a forward reference for the value, see if we already created a
2662 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002663 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002664 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 if (I != ForwardRefValIDs.end())
2666 Val = I->second.first;
2667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002668
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669 // If we have the value in the symbol table or fwd-ref table, return it.
2670 if (Val) {
2671 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002672 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002673 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002675 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002676 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002677 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002680 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002681 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002682 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattnerac161bf2009-01-02 07:01:27 +00002685 // Otherwise, create a new forward reference for this value and remember it.
2686 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002687 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002688 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002689 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002690 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002691 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002692
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2694 return FwdVal;
2695}
2696
2697/// SetInstName - After an instruction is parsed and inserted into its
2698/// basic block, this installs its name.
2699bool LLParser::PerFunctionState::SetInstName(int NameID,
2700 const std::string &NameStr,
2701 LocTy NameLoc, Instruction *Inst) {
2702 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002703 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 if (NameID != -1 || !NameStr.empty())
2705 return P.Error(NameLoc, "instructions returning void cannot have a name");
2706 return false;
2707 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 // If this was a numbered instruction, verify that the instruction is the
2710 // expected value and resolve any forward references.
2711 if (NameStr.empty()) {
2712 // If neither a name nor an ID was specified, just use the next ID.
2713 if (NameID == -1)
2714 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002715
Chris Lattnerac161bf2009-01-02 07:01:27 +00002716 if (unsigned(NameID) != NumberedVals.size())
2717 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002718 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002719
David Blaikie9ebdc692015-09-21 21:07:50 +00002720 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002721 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002722 Value *Sentinel = FI->second.first;
2723 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002724 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002725 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002726
2727 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002728 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729 ForwardRefValIDs.erase(FI);
2730 }
2731
2732 NumberedVals.push_back(Inst);
2733 return false;
2734 }
2735
2736 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002737 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002739 Value *Sentinel = FI->second.first;
2740 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002742 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002743
2744 Sentinel->replaceAllUsesWith(Inst);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002745 Sentinel->deleteValue();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 ForwardRefVals.erase(FI);
2747 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002748
Chris Lattnerac161bf2009-01-02 07:01:27 +00002749 // Set the name on the instruction.
2750 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002751
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002752 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754 NameStr + "'");
2755 return false;
2756}
2757
2758/// GetBB - Get a basic block with the specified name or ID, creating a
2759/// forward reference record if needed.
2760BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2761 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002762 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2763 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002764}
2765
2766BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002767 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2768 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002769}
2770
2771/// DefineBB - Define the specified basic block, which is either named or
2772/// unnamed. If there is an error, this returns null otherwise it returns
2773/// the block being defined.
2774BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2775 LocTy Loc) {
2776 BasicBlock *BB;
2777 if (Name.empty())
2778 BB = GetBB(NumberedVals.size(), Loc);
2779 else
2780 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002781 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002782
Chris Lattnerac161bf2009-01-02 07:01:27 +00002783 // Move the block to the end of the function. Forward ref'd blocks are
2784 // inserted wherever they happen to be referenced.
2785 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786
Chris Lattnerac161bf2009-01-02 07:01:27 +00002787 // Remove the block from forward ref sets.
2788 if (Name.empty()) {
2789 ForwardRefValIDs.erase(NumberedVals.size());
2790 NumberedVals.push_back(BB);
2791 } else {
2792 // BB forward references are already in the function symbol table.
2793 ForwardRefVals.erase(Name);
2794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002795
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 return BB;
2797}
2798
2799//===----------------------------------------------------------------------===//
2800// Constants.
2801//===----------------------------------------------------------------------===//
2802
2803/// ParseValID - Parse an abstract value that doesn't necessarily have a
2804/// type implied. For example, if we parse "4" we don't know what integer type
2805/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002806/// sanity. PFS is used to convert function-local operands of metadata (since
2807/// metadata operands are not just parsed here but also converted to values).
2808/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002809bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 ID.Loc = Lex.getLoc();
2811 switch (Lex.getKind()) {
2812 default: return TokError("expected value token");
2813 case lltok::GlobalID: // @42
2814 ID.UIntVal = Lex.getUIntVal();
2815 ID.Kind = ValID::t_GlobalID;
2816 break;
2817 case lltok::GlobalVar: // @foo
2818 ID.StrVal = Lex.getStrVal();
2819 ID.Kind = ValID::t_GlobalName;
2820 break;
2821 case lltok::LocalVarID: // %42
2822 ID.UIntVal = Lex.getUIntVal();
2823 ID.Kind = ValID::t_LocalID;
2824 break;
2825 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 ID.StrVal = Lex.getStrVal();
2827 ID.Kind = ValID::t_LocalName;
2828 break;
2829 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002830 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 ID.Kind = ValID::t_APSInt;
2832 break;
2833 case lltok::APFloat:
2834 ID.APFloatVal = Lex.getAPFloatVal();
2835 ID.Kind = ValID::t_APFloat;
2836 break;
2837 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002838 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002839 ID.Kind = ValID::t_Constant;
2840 break;
2841 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002842 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 ID.Kind = ValID::t_Constant;
2844 break;
2845 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2846 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2847 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002848 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002849
Chris Lattnerac161bf2009-01-02 07:01:27 +00002850 case lltok::lbrace: {
2851 // ValID ::= '{' ConstVector '}'
2852 Lex.Lex();
2853 SmallVector<Constant*, 16> Elts;
2854 if (ParseGlobalValueVector(Elts) ||
2855 ParseToken(lltok::rbrace, "expected end of struct constant"))
2856 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002857
David Blaikieadbda4b2015-08-03 20:08:41 +00002858 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002859 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002860 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2861 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002862 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 return false;
2864 }
2865 case lltok::less: {
2866 // ValID ::= '<' ConstVector '>' --> Vector.
2867 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2868 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002869 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002870
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 SmallVector<Constant*, 16> Elts;
2872 LocTy FirstEltLoc = Lex.getLoc();
2873 if (ParseGlobalValueVector(Elts) ||
2874 (isPackedStruct &&
2875 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2876 ParseToken(lltok::greater, "expected end of constant"))
2877 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002880 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2881 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2882 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002883 ID.UIntVal = Elts.size();
2884 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002885 return false;
2886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Chris Lattnerac161bf2009-01-02 07:01:27 +00002888 if (Elts.empty())
2889 return Error(ID.Loc, "constant vector must not be empty");
2890
Duncan Sands9dff9be2010-02-15 16:12:20 +00002891 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002892 !Elts[0]->getType()->isFloatingPointTy() &&
2893 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002894 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002895 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002896
Chris Lattnerac161bf2009-01-02 07:01:27 +00002897 // Verify that all the vector elements have the same type.
2898 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2899 if (Elts[i]->getType() != Elts[0]->getType())
2900 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002901 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002902 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002903
Chris Lattner69229312011-02-15 00:14:00 +00002904 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002905 ID.Kind = ValID::t_Constant;
2906 return false;
2907 }
2908 case lltok::lsquare: { // Array Constant
2909 Lex.Lex();
2910 SmallVector<Constant*, 16> Elts;
2911 LocTy FirstEltLoc = Lex.getLoc();
2912 if (ParseGlobalValueVector(Elts) ||
2913 ParseToken(lltok::rsquare, "expected end of array constant"))
2914 return true;
2915
2916 // Handle empty element.
2917 if (Elts.empty()) {
2918 // Use undef instead of an array because it's inconvenient to determine
2919 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002920 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002921 return false;
2922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002923
Chris Lattnerac161bf2009-01-02 07:01:27 +00002924 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002925 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002926 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002927
Owen Anderson4056ca92009-07-29 22:17:13 +00002928 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Chris Lattnerac161bf2009-01-02 07:01:27 +00002930 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002931 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002932 if (Elts[i]->getType() != Elts[0]->getType())
2933 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002934 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002935 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002937
Jay Foad83be3612011-06-22 09:24:39 +00002938 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002939 ID.Kind = ValID::t_Constant;
2940 return false;
2941 }
2942 case lltok::kw_c: // c "foo"
2943 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002944 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2945 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2947 ID.Kind = ValID::t_Constant;
2948 return false;
2949
2950 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002951 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2952 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002953 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002954 Lex.Lex();
2955 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002956 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002957 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002958 ParseStringConstant(ID.StrVal) ||
2959 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 ParseToken(lltok::StringConstant, "expected constraint string"))
2961 return true;
2962 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002963 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002964 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002965 ID.Kind = ValID::t_InlineAsm;
2966 return false;
2967 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002968
Chris Lattner3432c622009-10-28 03:39:23 +00002969 case lltok::kw_blockaddress: {
2970 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2971 Lex.Lex();
2972
2973 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002974
Chris Lattner3432c622009-10-28 03:39:23 +00002975 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2976 ParseValID(Fn) ||
2977 ParseToken(lltok::comma, "expected comma in block address expression")||
2978 ParseValID(Label) ||
2979 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2980 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002981
Chris Lattner3432c622009-10-28 03:39:23 +00002982 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2983 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002984 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002985 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002986
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002987 // Try to find the function (but skip it if it's forward-referenced).
2988 GlobalValue *GV = nullptr;
2989 if (Fn.Kind == ValID::t_GlobalID) {
2990 if (Fn.UIntVal < NumberedVals.size())
2991 GV = NumberedVals[Fn.UIntVal];
2992 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2993 GV = M->getNamedValue(Fn.StrVal);
2994 }
2995 Function *F = nullptr;
2996 if (GV) {
2997 // Confirm that it's actually a function with a definition.
2998 if (!isa<Function>(GV))
2999 return Error(Fn.Loc, "expected function name in blockaddress");
3000 F = cast<Function>(GV);
3001 if (F->isDeclaration())
3002 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3003 }
3004
3005 if (!F) {
3006 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00003007 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00003008 ForwardRefBlockAddresses.insert(std::make_pair(
3009 std::move(Fn),
3010 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00003011 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3012 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003013 if (!FwdRef)
3014 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3015 GlobalValue::InternalLinkage, nullptr, "");
3016 ID.ConstantVal = FwdRef;
3017 ID.Kind = ValID::t_Constant;
3018 return false;
3019 }
3020
3021 // We found the function; now find the basic block. Don't use PFS, since we
3022 // might be inside a constant expression.
3023 BasicBlock *BB;
3024 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3025 if (Label.Kind == ValID::t_LocalID)
3026 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3027 else
3028 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3029 if (!BB)
3030 return Error(Label.Loc, "referenced value is not a basic block");
3031 } else {
3032 if (Label.Kind == ValID::t_LocalID)
3033 return Error(Label.Loc, "cannot take address of numeric label after "
3034 "the function is defined");
3035 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003036 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003037 if (!BB)
3038 return Error(Label.Loc, "referenced value is not a basic block");
3039 }
3040
3041 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00003042 ID.Kind = ValID::t_Constant;
3043 return false;
3044 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003045
Chris Lattnerac161bf2009-01-02 07:01:27 +00003046 case lltok::kw_trunc:
3047 case lltok::kw_zext:
3048 case lltok::kw_sext:
3049 case lltok::kw_fptrunc:
3050 case lltok::kw_fpext:
3051 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003052 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 case lltok::kw_uitofp:
3054 case lltok::kw_sitofp:
3055 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003056 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003057 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003058 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003059 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00003060 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 Constant *SrcVal;
3062 Lex.Lex();
3063 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3064 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00003065 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 ParseType(DestTy) ||
3067 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3068 return true;
3069 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3070 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003071 getTypeString(SrcVal->getType()) + "' to '" +
3072 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00003074 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 ID.Kind = ValID::t_Constant;
3076 return false;
3077 }
3078 case lltok::kw_extractvalue: {
3079 Lex.Lex();
3080 Constant *Val;
3081 SmallVector<unsigned, 4> Indices;
3082 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3083 ParseGlobalTypeAndValue(Val) ||
3084 ParseIndexList(Indices) ||
3085 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3086 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00003087
Chris Lattner392be582010-02-12 20:49:41 +00003088 if (!Val->getType()->isAggregateType())
3089 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00003090 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003091 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00003092 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 ID.Kind = ValID::t_Constant;
3094 return false;
3095 }
3096 case lltok::kw_insertvalue: {
3097 Lex.Lex();
3098 Constant *Val0, *Val1;
3099 SmallVector<unsigned, 4> Indices;
3100 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3101 ParseGlobalTypeAndValue(Val0) ||
3102 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3103 ParseGlobalTypeAndValue(Val1) ||
3104 ParseIndexList(Indices) ||
3105 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3106 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003107 if (!Val0->getType()->isAggregateType())
3108 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003109 Type *IndexedType =
3110 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3111 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003113 if (IndexedType != Val1->getType())
3114 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3115 getTypeString(Val1->getType()) +
3116 "' instead of '" + getTypeString(IndexedType) +
3117 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003118 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119 ID.Kind = ValID::t_Constant;
3120 return false;
3121 }
3122 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003123 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 unsigned PredVal, Opc = Lex.getUIntVal();
3125 Constant *Val0, *Val1;
3126 Lex.Lex();
3127 if (ParseCmpPredicate(PredVal, Opc) ||
3128 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3129 ParseGlobalTypeAndValue(Val0) ||
3130 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3131 ParseGlobalTypeAndValue(Val1) ||
3132 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3133 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003134
Chris Lattnerac161bf2009-01-02 07:01:27 +00003135 if (Val0->getType() != Val1->getType())
3136 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003137
Chris Lattnerac161bf2009-01-02 07:01:27 +00003138 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003139
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003141 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003143 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003144 } else {
3145 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003146 if (!Val0->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00003147 !Val0->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003148 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003149 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003150 }
3151 ID.Kind = ValID::t_Constant;
3152 return false;
3153 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003154
Chris Lattnerac161bf2009-01-02 07:01:27 +00003155 // Binary Operators.
3156 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003157 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003158 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003159 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003161 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 case lltok::kw_udiv:
3163 case lltok::kw_sdiv:
3164 case lltok::kw_fdiv:
3165 case lltok::kw_urem:
3166 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003167 case lltok::kw_frem:
3168 case lltok::kw_shl:
3169 case lltok::kw_lshr:
3170 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003171 bool NUW = false;
3172 bool NSW = false;
3173 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 unsigned Opc = Lex.getUIntVal();
3175 Constant *Val0, *Val1;
3176 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003177 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003178 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3179 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003180 if (EatIfPresent(lltok::kw_nuw))
3181 NUW = true;
3182 if (EatIfPresent(lltok::kw_nsw)) {
3183 NSW = true;
3184 if (EatIfPresent(lltok::kw_nuw))
3185 NUW = true;
3186 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003187 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3188 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003189 if (EatIfPresent(lltok::kw_exact))
3190 Exact = true;
3191 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3193 ParseGlobalTypeAndValue(Val0) ||
3194 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3195 ParseGlobalTypeAndValue(Val1) ||
3196 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3197 return true;
3198 if (Val0->getType() != Val1->getType())
3199 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003200 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003201 if (NUW)
3202 return Error(ModifierLoc, "nuw only applies to integer operations");
3203 if (NSW)
3204 return Error(ModifierLoc, "nsw only applies to integer operations");
3205 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003206 // Check that the type is valid for the operator.
3207 switch (Opc) {
3208 case Instruction::Add:
3209 case Instruction::Sub:
3210 case Instruction::Mul:
3211 case Instruction::UDiv:
3212 case Instruction::SDiv:
3213 case Instruction::URem:
3214 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003215 case Instruction::Shl:
3216 case Instruction::AShr:
3217 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003218 if (!Val0->getType()->isIntOrIntVectorTy())
3219 return Error(ID.Loc, "constexpr requires integer operands");
3220 break;
3221 case Instruction::FAdd:
3222 case Instruction::FSub:
3223 case Instruction::FMul:
3224 case Instruction::FDiv:
3225 case Instruction::FRem:
3226 if (!Val0->getType()->isFPOrFPVectorTy())
3227 return Error(ID.Loc, "constexpr requires fp operands");
3228 break;
3229 default: llvm_unreachable("Unknown binary operator!");
3230 }
Dan Gohman1b849082009-09-07 23:54:19 +00003231 unsigned Flags = 0;
3232 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3233 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003234 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003235 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003236 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003237 ID.Kind = ValID::t_Constant;
3238 return false;
3239 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003240
Chris Lattnerac161bf2009-01-02 07:01:27 +00003241 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003242 case lltok::kw_and:
3243 case lltok::kw_or:
3244 case lltok::kw_xor: {
3245 unsigned Opc = Lex.getUIntVal();
3246 Constant *Val0, *Val1;
3247 Lex.Lex();
3248 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3249 ParseGlobalTypeAndValue(Val0) ||
3250 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3251 ParseGlobalTypeAndValue(Val1) ||
3252 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3253 return true;
3254 if (Val0->getType() != Val1->getType())
3255 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003256 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003257 return Error(ID.Loc,
3258 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003259 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003260 ID.Kind = ValID::t_Constant;
3261 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003262 }
3263
Chris Lattnerac161bf2009-01-02 07:01:27 +00003264 case lltok::kw_getelementptr:
3265 case lltok::kw_shufflevector:
3266 case lltok::kw_insertelement:
3267 case lltok::kw_extractelement:
3268 case lltok::kw_select: {
3269 unsigned Opc = Lex.getUIntVal();
3270 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003271 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003272 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003274
Dan Gohman1639c392009-07-27 21:53:46 +00003275 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003276 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003277
3278 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3279 return true;
3280
3281 LocTy ExplicitTypeLoc = Lex.getLoc();
3282 if (Opc == Instruction::GetElementPtr) {
3283 if (ParseType(Ty) ||
3284 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3285 return true;
3286 }
3287
Peter Collingbourned93620b2016-11-10 22:34:55 +00003288 Optional<unsigned> InRangeOp;
3289 if (ParseGlobalValueVector(
3290 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003291 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3292 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003293
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003295 if (Elts.size() == 0 ||
Craig Topper95d23472017-07-09 07:04:00 +00003296 !Elts[0]->getType()->isPtrOrPtrVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003297 return Error(ID.Loc, "base of getelementptr must be a pointer");
3298
3299 Type *BaseType = Elts[0]->getType();
3300 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003301 if (Ty != BasePointerType->getElementType())
3302 return Error(
3303 ExplicitTypeLoc,
3304 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003305
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003306 unsigned GEPWidth =
3307 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3308
Jay Foaded8db7d2011-07-21 14:31:17 +00003309 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003310 for (Constant *Val : Indices) {
3311 Type *ValTy = Val->getType();
Craig Topper95d23472017-07-09 07:04:00 +00003312 if (!ValTy->isIntOrIntVectorTy())
David Majnemer00303b62015-02-22 23:14:52 +00003313 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003314 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003315 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003316 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003317 return Error(
3318 ID.Loc,
3319 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003320 // GEPWidth may have been unknown because the base is a scalar,
3321 // but it is known now.
3322 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003323 }
3324 }
3325
Craig Toppere3dcce92015-08-01 22:20:21 +00003326 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003327 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003328 return Error(ID.Loc, "base element of getelementptr must be sized");
3329
David Blaikie4a2e73b2015-04-02 18:55:32 +00003330 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003331 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003332
3333 if (InRangeOp) {
3334 if (*InRangeOp == 0)
3335 return Error(ID.Loc,
3336 "inrange keyword may not appear on pointer operand");
3337 --*InRangeOp;
3338 }
3339
3340 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3341 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003342 } else if (Opc == Instruction::Select) {
3343 if (Elts.size() != 3)
3344 return Error(ID.Loc, "expected three operands to select");
3345 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3346 Elts[2]))
3347 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003348 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003349 } else if (Opc == Instruction::ShuffleVector) {
3350 if (Elts.size() != 3)
3351 return Error(ID.Loc, "expected three operands to shufflevector");
3352 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3353 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003354 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003355 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003356 } else if (Opc == Instruction::ExtractElement) {
3357 if (Elts.size() != 2)
3358 return Error(ID.Loc, "expected two operands to extractelement");
3359 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3360 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003361 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003362 } else {
3363 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3364 if (Elts.size() != 3)
3365 return Error(ID.Loc, "expected three operands to insertelement");
3366 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3367 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003368 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003369 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003370 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003371
Chris Lattnerac161bf2009-01-02 07:01:27 +00003372 ID.Kind = ValID::t_Constant;
3373 return false;
3374 }
3375 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003376
Chris Lattnerac161bf2009-01-02 07:01:27 +00003377 Lex.Lex();
3378 return false;
3379}
3380
3381/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003382bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003383 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003384 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003385 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003386 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003387 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003388 if (V && !(C = dyn_cast<Constant>(V)))
3389 return Error(ID.Loc, "global values must be constants");
3390 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003391}
3392
Victor Hernandez9d75c962010-01-11 22:31:58 +00003393bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003394 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003395 return ParseType(Ty) ||
3396 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003397}
3398
Rafael Espindola83a362c2015-01-06 22:55:16 +00003399bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003400 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003401
3402 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003403 if (!EatIfPresent(lltok::kw_comdat))
3404 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003405
3406 if (EatIfPresent(lltok::lparen)) {
3407 if (Lex.getKind() != lltok::ComdatVar)
3408 return TokError("expected comdat variable");
3409 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3410 Lex.Lex();
3411 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3412 return true;
3413 } else {
3414 if (GlobalName.empty())
3415 return TokError("comdat cannot be unnamed");
3416 C = getComdat(GlobalName, KwLoc);
3417 }
3418
David Majnemerdad0a642014-06-27 18:19:56 +00003419 return false;
3420}
3421
Victor Hernandez9d75c962010-01-11 22:31:58 +00003422/// ParseGlobalValueVector
3423/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003424/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3425bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3426 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003427 // Empty list.
3428 if (Lex.getKind() == lltok::rbrace ||
3429 Lex.getKind() == lltok::rsquare ||
3430 Lex.getKind() == lltok::greater ||
3431 Lex.getKind() == lltok::rparen)
3432 return false;
3433
Peter Collingbourned93620b2016-11-10 22:34:55 +00003434 do {
3435 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3436 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003437
Peter Collingbourned93620b2016-11-10 22:34:55 +00003438 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003439 if (ParseGlobalTypeAndValue(C)) return true;
3440 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003441 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003442
3443 return false;
3444}
3445
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003446bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003447 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003448 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003449 return true;
3450
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003451 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003452 return false;
3453}
3454
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003455/// MDNode:
3456/// ::= !{ ... }
3457/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003458/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003459bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003460 if (Lex.getKind() == lltok::MetadataVar)
3461 return ParseSpecializedMDNode(N);
3462
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003463 return ParseToken(lltok::exclaim, "expected '!' here") ||
3464 ParseMDNodeTail(N);
3465}
3466
3467bool LLParser::ParseMDNodeTail(MDNode *&N) {
3468 // !{ ... }
3469 if (Lex.getKind() == lltok::lbrace)
3470 return ParseMDTuple(N);
3471
3472 // !42
3473 return ParseMDNodeID(N);
3474}
3475
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003476namespace {
3477
3478/// Structure to represent an optional metadata field.
3479template <class FieldTy> struct MDFieldImpl {
3480 typedef MDFieldImpl ImplTy;
3481 FieldTy Val;
3482 bool Seen;
3483
3484 void assign(FieldTy Val) {
3485 Seen = true;
3486 this->Val = std::move(Val);
3487 }
3488
3489 explicit MDFieldImpl(FieldTy Default)
3490 : Val(std::move(Default)), Seen(false) {}
3491};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003492
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003493struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3494 uint64_t Max;
3495
3496 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3497 : ImplTy(Default), Max(Max) {}
3498};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003499
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003500struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003501 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003502};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003503
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003504struct ColumnField : public MDUnsignedField {
3505 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3506};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003507
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003508struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003509 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003510 DwarfTagField(dwarf::Tag DefaultTag)
3511 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003512};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003513
Amjad Abouda9bcf162015-12-10 12:56:35 +00003514struct DwarfMacinfoTypeField : public MDUnsignedField {
3515 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3516 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3517 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3518};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003519
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003520struct DwarfAttEncodingField : public MDUnsignedField {
3521 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3522};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003523
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003524struct DwarfVirtualityField : public MDUnsignedField {
3525 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3526};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003527
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003528struct DwarfLangField : public MDUnsignedField {
3529 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3530};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003531
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003532struct DwarfCCField : public MDUnsignedField {
3533 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3534};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003535
Adrian Prantlb939a252016-03-31 23:56:58 +00003536struct EmissionKindField : public MDUnsignedField {
3537 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3538};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003539
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003540struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3541 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003542};
3543
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003544struct MDSignedField : public MDFieldImpl<int64_t> {
3545 int64_t Min;
3546 int64_t Max;
3547
3548 MDSignedField(int64_t Default = 0)
3549 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3550 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3551 : ImplTy(Default), Min(Min), Max(Max) {}
3552};
3553
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003554struct MDBoolField : public MDFieldImpl<bool> {
3555 MDBoolField(bool Default = false) : ImplTy(Default) {}
3556};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003557
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003558struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003559 bool AllowNull;
3560
3561 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003562};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003563
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003564struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3565 MDConstant() : ImplTy(nullptr) {}
3566};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003567
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003568struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003569 bool AllowEmpty;
3570 MDStringField(bool AllowEmpty = true)
3571 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003572};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003573
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003574struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3575 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3576};
3577
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003578struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3579 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3580 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3581};
3582
Eugene Zelenko1804a772016-08-25 00:45:04 +00003583} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003584
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003585namespace llvm {
3586
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003587template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003588bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003589 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003590 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3591 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003592
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003593 auto &U = Lex.getAPSIntVal();
3594 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003595 return TokError("value for '" + Name + "' too large, limit is " +
3596 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003597 Result.assign(U.getZExtValue());
3598 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003599 Lex.Lex();
3600 return false;
3601}
3602
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003603template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003604bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3605 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3606}
3607template <>
3608bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3609 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3610}
3611
3612template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003613bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3614 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003615 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003616
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003617 if (Lex.getKind() != lltok::DwarfTag)
3618 return TokError("expected DWARF tag");
3619
3620 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3621 if (Tag == dwarf::DW_TAG_invalid)
3622 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003623 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003624
3625 Result.assign(Tag);
3626 Lex.Lex();
3627 return false;
3628}
3629
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003630template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003631bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003632 DwarfMacinfoTypeField &Result) {
3633 if (Lex.getKind() == lltok::APSInt)
3634 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3635
3636 if (Lex.getKind() != lltok::DwarfMacinfo)
3637 return TokError("expected DWARF macinfo type");
3638
3639 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3640 if (Macinfo == dwarf::DW_MACINFO_invalid)
3641 return TokError(
3642 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3643 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3644
3645 Result.assign(Macinfo);
3646 Lex.Lex();
3647 return false;
3648}
3649
3650template <>
3651bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003652 DwarfVirtualityField &Result) {
3653 if (Lex.getKind() == lltok::APSInt)
3654 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3655
3656 if (Lex.getKind() != lltok::DwarfVirtuality)
3657 return TokError("expected DWARF virtuality code");
3658
3659 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003660 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003661 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3662 Lex.getStrVal() + "'");
3663 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3664 Result.assign(Virtuality);
3665 Lex.Lex();
3666 return false;
3667}
3668
3669template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003670bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3671 if (Lex.getKind() == lltok::APSInt)
3672 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3673
3674 if (Lex.getKind() != lltok::DwarfLang)
3675 return TokError("expected DWARF language");
3676
3677 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3678 if (!Lang)
3679 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3680 "'");
3681 assert(Lang <= Result.Max && "Expected valid DWARF language");
3682 Result.assign(Lang);
3683 Lex.Lex();
3684 return false;
3685}
3686
3687template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003688bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3689 if (Lex.getKind() == lltok::APSInt)
3690 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3691
3692 if (Lex.getKind() != lltok::DwarfCC)
3693 return TokError("expected DWARF calling convention");
3694
3695 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3696 if (!CC)
3697 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3698 "'");
3699 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3700 Result.assign(CC);
3701 Lex.Lex();
3702 return false;
3703}
3704
3705template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003706bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3707 if (Lex.getKind() == lltok::APSInt)
3708 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3709
3710 if (Lex.getKind() != lltok::EmissionKind)
3711 return TokError("expected emission kind");
3712
3713 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3714 if (!Kind)
3715 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3716 "'");
3717 assert(*Kind <= Result.Max && "Expected valid emission kind");
3718 Result.assign(*Kind);
3719 Lex.Lex();
3720 return false;
3721}
3722
3723template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003724bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003725 DwarfAttEncodingField &Result) {
3726 if (Lex.getKind() == lltok::APSInt)
3727 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3728
3729 if (Lex.getKind() != lltok::DwarfAttEncoding)
3730 return TokError("expected DWARF type attribute encoding");
3731
3732 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3733 if (!Encoding)
3734 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3735 Lex.getStrVal() + "'");
3736 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3737 Result.assign(Encoding);
3738 Lex.Lex();
3739 return false;
3740}
3741
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003742/// DIFlagField
3743/// ::= uint32
3744/// ::= DIFlagVector
3745/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3746template <>
3747bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003748
3749 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003750 auto parseFlag = [&](DINode::DIFlags &Val) {
3751 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3752 uint32_t TempVal = static_cast<uint32_t>(Val);
3753 bool Res = ParseUInt32(TempVal);
3754 Val = static_cast<DINode::DIFlags>(TempVal);
3755 return Res;
3756 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003757
3758 if (Lex.getKind() != lltok::DIFlag)
3759 return TokError("expected debug info flag");
3760
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003761 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003762 if (!Val)
3763 return TokError(Twine("invalid debug info flag flag '") +
3764 Lex.getStrVal() + "'");
3765 Lex.Lex();
3766 return false;
3767 };
3768
3769 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003770 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003771 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003772 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003773 if (parseFlag(Val))
3774 return true;
3775 Combined |= Val;
3776 } while (EatIfPresent(lltok::bar));
3777
3778 Result.assign(Combined);
3779 return false;
3780}
3781
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003782template <>
3783bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003784 MDSignedField &Result) {
3785 if (Lex.getKind() != lltok::APSInt)
3786 return TokError("expected signed integer");
3787
3788 auto &S = Lex.getAPSIntVal();
3789 if (S < Result.Min)
3790 return TokError("value for '" + Name + "' too small, limit is " +
3791 Twine(Result.Min));
3792 if (S > Result.Max)
3793 return TokError("value for '" + Name + "' too large, limit is " +
3794 Twine(Result.Max));
3795 Result.assign(S.getExtValue());
3796 assert(Result.Val >= Result.Min && "Expected value in range");
3797 assert(Result.Val <= Result.Max && "Expected value in range");
3798 Lex.Lex();
3799 return false;
3800}
3801
3802template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003803bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3804 switch (Lex.getKind()) {
3805 default:
3806 return TokError("expected 'true' or 'false'");
3807 case lltok::kw_true:
3808 Result.assign(true);
3809 break;
3810 case lltok::kw_false:
3811 Result.assign(false);
3812 break;
3813 }
3814 Lex.Lex();
3815 return false;
3816}
3817
3818template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003819bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003820 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003821 if (!Result.AllowNull)
3822 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003823 Lex.Lex();
3824 Result.assign(nullptr);
3825 return false;
3826 }
3827
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003828 Metadata *MD;
3829 if (ParseMetadata(MD, nullptr))
3830 return true;
3831
3832 Result.assign(MD);
3833 return false;
3834}
3835
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003836template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003837bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003838 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003839 std::string S;
3840 if (ParseStringConstant(S))
3841 return true;
3842
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003843 if (!Result.AllowEmpty && S.empty())
3844 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3845
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003846 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003847 return false;
3848}
3849
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003850template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003851bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3852 SmallVector<Metadata *, 4> MDs;
3853 if (ParseMDNodeVector(MDs))
3854 return true;
3855
3856 Result.assign(std::move(MDs));
3857 return false;
3858}
3859
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003860template <>
3861bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3862 ChecksumKindField &Result) {
3863 if (Lex.getKind() != lltok::ChecksumKind)
3864 return TokError(
3865 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3866
3867 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3868
3869 Result.assign(CSKind);
3870 Lex.Lex();
3871 return false;
3872}
3873
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003874} // end namespace llvm
3875
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003876template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003877bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003878 do {
3879 if (Lex.getKind() != lltok::LabelStr)
3880 return TokError("expected field label here");
3881
3882 if (parseField())
3883 return true;
3884 } while (EatIfPresent(lltok::comma));
3885
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003886 return false;
3887}
3888
3889template <class ParserTy>
3890bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3891 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3892 Lex.Lex();
3893
3894 if (ParseToken(lltok::lparen, "expected '(' here"))
3895 return true;
3896 if (Lex.getKind() != lltok::rparen)
3897 if (ParseMDFieldsImplBody(parseField))
3898 return true;
3899
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003900 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003901 return ParseToken(lltok::rparen, "expected ')' here");
3902}
3903
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003904template <class FieldTy>
3905bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3906 if (Result.Seen)
3907 return TokError("field '" + Name + "' cannot be specified more than once");
3908
3909 LocTy Loc = Lex.getLoc();
3910 Lex.Lex();
3911 return ParseMDField(Loc, Name, Result);
3912}
3913
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003914bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3915 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003916
3917#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003918 if (Lex.getStrVal() == #CLASS) \
3919 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003920#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003921
3922 return TokError("expected metadata type");
3923}
3924
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003925#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3926#define NOP_FIELD(NAME, TYPE, INIT)
3927#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3928 if (!NAME.Seen) \
3929 return Error(ClosingLoc, "missing required field '" #NAME "'");
3930#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003931 if (Lex.getStrVal() == #NAME) \
3932 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003933#define PARSE_MD_FIELDS() \
3934 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3935 do { \
3936 LocTy ClosingLoc; \
3937 if (ParseMDFieldsImpl([&]() -> bool { \
3938 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3939 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3940 }, ClosingLoc)) \
3941 return true; \
3942 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3943 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003944#define GET_OR_DISTINCT(CLASS, ARGS) \
3945 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003946
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003947/// ParseDILocationFields:
3948/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3949bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003950#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003951 OPTIONAL(line, LineField, ); \
3952 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003953 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003954 OPTIONAL(inlinedAt, MDField, );
3955 PARSE_MD_FIELDS();
3956#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003957
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003958 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003959 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003960 return false;
3961}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003962
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003963/// ParseGenericDINode:
3964/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3965bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003966#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003967 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003968 OPTIONAL(header, MDStringField, ); \
3969 OPTIONAL(operands, MDFieldList, );
3970 PARSE_MD_FIELDS();
3971#undef VISIT_MD_FIELDS
3972
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003973 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003974 (Context, tag.Val, header.Val, operands.Val));
3975 return false;
3976}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003977
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003978/// ParseDISubrange:
3979/// ::= !DISubrange(count: 30, lowerBound: 2)
3980bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003981#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003982 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003983 OPTIONAL(lowerBound, MDSignedField, );
3984 PARSE_MD_FIELDS();
3985#undef VISIT_MD_FIELDS
3986
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003987 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003988 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003989}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003990
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003991/// ParseDIEnumerator:
3992/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3993bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003994#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003995 REQUIRED(name, MDStringField, ); \
3996 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003997 PARSE_MD_FIELDS();
3998#undef VISIT_MD_FIELDS
3999
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004000 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004001 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004002}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00004003
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004004/// ParseDIBasicType:
4005/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4006bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004007#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004008 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004009 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004010 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004011 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00004012 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004013 PARSE_MD_FIELDS();
4014#undef VISIT_MD_FIELDS
4015
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004016 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004017 align.Val, encoding.Val));
4018 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004019}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00004020
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004021/// ParseDIDerivedType:
4022/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004023/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004024/// align: 32, offset: 0, flags: 0, extraData: !3,
4025/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004026bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004027#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4028 REQUIRED(tag, DwarfTagField, ); \
4029 OPTIONAL(name, MDStringField, ); \
4030 OPTIONAL(file, MDField, ); \
4031 OPTIONAL(line, LineField, ); \
4032 OPTIONAL(scope, MDField, ); \
4033 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004034 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004035 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004036 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004037 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004038 OPTIONAL(extraData, MDField, ); \
4039 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004040 PARSE_MD_FIELDS();
4041#undef VISIT_MD_FIELDS
4042
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004043 Optional<unsigned> DWARFAddressSpace;
4044 if (dwarfAddressSpace.Val != UINT32_MAX)
4045 DWARFAddressSpace = dwarfAddressSpace.Val;
4046
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004047 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004048 (Context, tag.Val, name.Val, file.Val, line.Val,
4049 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00004050 offset.Val, DWARFAddressSpace, flags.Val,
4051 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004052 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004053}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004054
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004055bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004056#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4057 REQUIRED(tag, DwarfTagField, ); \
4058 OPTIONAL(name, MDStringField, ); \
4059 OPTIONAL(file, MDField, ); \
4060 OPTIONAL(line, LineField, ); \
4061 OPTIONAL(scope, MDField, ); \
4062 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004063 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00004064 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00004065 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004066 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004067 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00004068 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004069 OPTIONAL(vtableHolder, MDField, ); \
4070 OPTIONAL(templateParams, MDField, ); \
4071 OPTIONAL(identifier, MDStringField, );
4072 PARSE_MD_FIELDS();
4073#undef VISIT_MD_FIELDS
4074
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00004075 // If this has an identifier try to build an ODR type.
4076 if (identifier.Val)
4077 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00004078 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4079 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4080 elements.Val, runtimeLang.Val, vtableHolder.Val,
4081 templateParams.Val)) {
4082 Result = CT;
4083 return false;
4084 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00004085
4086 // Create a new node, and save it in the context if it belongs in the type
4087 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004088 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004089 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004090 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4091 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4092 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
4093 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004094}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004095
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004096bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004097#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004098 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004099 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004100 REQUIRED(types, MDField, );
4101 PARSE_MD_FIELDS();
4102#undef VISIT_MD_FIELDS
4103
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004104 Result = GET_OR_DISTINCT(DISubroutineType,
4105 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004106 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004107}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004108
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004109/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004110/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4111/// checksumkind: CSK_MD5,
4112/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004113bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004114#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4115 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004116 REQUIRED(directory, MDStringField, ); \
4117 OPTIONAL(checksumkind, ChecksumKindField, ); \
4118 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004119 PARSE_MD_FIELDS();
4120#undef VISIT_MD_FIELDS
4121
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004122 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4123 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004124 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004125}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004126
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004127/// ParseDICompileUnit:
4128/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004129/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004130/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004131/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004132/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004133bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004134 if (!IsDistinct)
4135 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4136
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4138 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004139 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004140 OPTIONAL(producer, MDStringField, ); \
4141 OPTIONAL(isOptimized, MDBoolField, ); \
4142 OPTIONAL(flags, MDStringField, ); \
4143 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4144 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004145 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004146 OPTIONAL(enums, MDField, ); \
4147 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004148 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004149 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004150 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004151 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004152 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004153 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4154 OPTIONAL(gnuPubnames, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004155 PARSE_MD_FIELDS();
4156#undef VISIT_MD_FIELDS
4157
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004158 Result = DICompileUnit::getDistinct(
4159 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4160 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004161 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Peter Collingbourneb52e2362017-09-12 21:50:41 +00004162 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004163 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004164}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004165
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004166/// ParseDISubprogram:
4167/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004168/// file: !1, line: 7, type: !2, isLocal: false,
4169/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004170/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004171/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004172/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004173/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004174bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004175 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004176#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4177 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004178 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004179 OPTIONAL(linkageName, MDStringField, ); \
4180 OPTIONAL(file, MDField, ); \
4181 OPTIONAL(line, LineField, ); \
4182 OPTIONAL(type, MDField, ); \
4183 OPTIONAL(isLocal, MDBoolField, ); \
4184 OPTIONAL(isDefinition, MDBoolField, (true)); \
4185 OPTIONAL(scopeLine, LineField, ); \
4186 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004187 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004188 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004189 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004190 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004191 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004192 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004193 OPTIONAL(templateParams, MDField, ); \
4194 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004195 OPTIONAL(variables, MDField, ); \
4196 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004197 PARSE_MD_FIELDS();
4198#undef VISIT_MD_FIELDS
4199
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004200 if (isDefinition.Val && !IsDistinct)
4201 return Lex.Error(
4202 Loc,
4203 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4204
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004205 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004206 DISubprogram,
4207 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4208 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4209 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4210 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4211 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004212 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004213}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004214
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004215/// ParseDILexicalBlock:
4216/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4217bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004218#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004219 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004220 OPTIONAL(file, MDField, ); \
4221 OPTIONAL(line, LineField, ); \
4222 OPTIONAL(column, ColumnField, );
4223 PARSE_MD_FIELDS();
4224#undef VISIT_MD_FIELDS
4225
4226 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004227 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004228 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004229}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004230
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004231/// ParseDILexicalBlockFile:
4232/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4233bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004235 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004236 OPTIONAL(file, MDField, ); \
4237 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4238 PARSE_MD_FIELDS();
4239#undef VISIT_MD_FIELDS
4240
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004241 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004242 (Context, scope.Val, file.Val, discriminator.Val));
4243 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004244}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004245
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004246/// ParseDINamespace:
4247/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4248bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004249#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4250 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004251 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004252 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004253 PARSE_MD_FIELDS();
4254#undef VISIT_MD_FIELDS
4255
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004256 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004257 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004258 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004259}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004260
Amjad Abouda9bcf162015-12-10 12:56:35 +00004261/// ParseDIMacro:
4262/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4263bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4264#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4265 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004266 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004267 REQUIRED(name, MDStringField, ); \
4268 OPTIONAL(value, MDStringField, );
4269 PARSE_MD_FIELDS();
4270#undef VISIT_MD_FIELDS
4271
4272 Result = GET_OR_DISTINCT(DIMacro,
4273 (Context, type.Val, line.Val, name.Val, value.Val));
4274 return false;
4275}
4276
4277/// ParseDIMacroFile:
4278/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4279bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4280#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4281 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004282 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004283 REQUIRED(file, MDField, ); \
4284 OPTIONAL(nodes, MDField, );
4285 PARSE_MD_FIELDS();
4286#undef VISIT_MD_FIELDS
4287
4288 Result = GET_OR_DISTINCT(DIMacroFile,
4289 (Context, type.Val, line.Val, file.Val, nodes.Val));
4290 return false;
4291}
4292
Adrian Prantlab1243f2015-06-29 23:03:47 +00004293/// ParseDIModule:
4294/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4295/// includePath: "/usr/include", isysroot: "/")
4296bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4297#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4298 REQUIRED(scope, MDField, ); \
4299 REQUIRED(name, MDStringField, ); \
4300 OPTIONAL(configMacros, MDStringField, ); \
4301 OPTIONAL(includePath, MDStringField, ); \
4302 OPTIONAL(isysroot, MDStringField, );
4303 PARSE_MD_FIELDS();
4304#undef VISIT_MD_FIELDS
4305
4306 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4307 configMacros.Val, includePath.Val, isysroot.Val));
4308 return false;
4309}
4310
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004311/// ParseDITemplateTypeParameter:
4312/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4313bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004315 OPTIONAL(name, MDStringField, ); \
4316 REQUIRED(type, MDField, );
4317 PARSE_MD_FIELDS();
4318#undef VISIT_MD_FIELDS
4319
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004320 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004321 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004322 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004323}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004324
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004325/// ParseDITemplateValueParameter:
4326/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004327/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004328bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004329#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004330 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004331 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004332 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004333 REQUIRED(value, MDField, );
4334 PARSE_MD_FIELDS();
4335#undef VISIT_MD_FIELDS
4336
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004337 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004338 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004339 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004340}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004341
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004342/// ParseDIGlobalVariable:
4343/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004344/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004345/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004346bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004347#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004348 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004349 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004350 OPTIONAL(linkageName, MDStringField, ); \
4351 OPTIONAL(file, MDField, ); \
4352 OPTIONAL(line, LineField, ); \
4353 OPTIONAL(type, MDField, ); \
4354 OPTIONAL(isLocal, MDBoolField, ); \
4355 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004356 OPTIONAL(declaration, MDField, ); \
4357 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004358 PARSE_MD_FIELDS();
4359#undef VISIT_MD_FIELDS
4360
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004361 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004362 (Context, scope.Val, name.Val, linkageName.Val,
4363 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004364 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004365 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004366}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004367
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004368/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004369/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004370/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4371/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004372/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004373/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4374/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004375bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004376#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004377 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004378 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004379 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004380 OPTIONAL(file, MDField, ); \
4381 OPTIONAL(line, LineField, ); \
4382 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004383 OPTIONAL(flags, DIFlagField, ); \
4384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004385 PARSE_MD_FIELDS();
4386#undef VISIT_MD_FIELDS
4387
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004388 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004389 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004390 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004391 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004392}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004393
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004394/// ParseDIExpression:
4395/// ::= !DIExpression(0, 7, -1)
4396bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004397 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4398 Lex.Lex();
4399
4400 if (ParseToken(lltok::lparen, "expected '(' here"))
4401 return true;
4402
4403 SmallVector<uint64_t, 8> Elements;
4404 if (Lex.getKind() != lltok::rparen)
4405 do {
4406 if (Lex.getKind() == lltok::DwarfOp) {
4407 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4408 Lex.Lex();
4409 Elements.push_back(Op);
4410 continue;
4411 }
4412 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4413 }
4414
4415 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4416 return TokError("expected unsigned integer");
4417
4418 auto &U = Lex.getAPSIntVal();
4419 if (U.ugt(UINT64_MAX))
4420 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4421 Elements.push_back(U.getZExtValue());
4422 Lex.Lex();
4423 } while (EatIfPresent(lltok::comma));
4424
4425 if (ParseToken(lltok::rparen, "expected ')' here"))
4426 return true;
4427
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004428 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004429 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004430}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004431
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004432/// ParseDIGlobalVariableExpression:
4433/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4434bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4435 bool IsDistinct) {
4436#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4437 REQUIRED(var, MDField, ); \
Adrian Prantl05782212017-08-30 18:06:51 +00004438 REQUIRED(expr, MDField, );
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004439 PARSE_MD_FIELDS();
4440#undef VISIT_MD_FIELDS
4441
4442 Result =
4443 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4444 return false;
4445}
4446
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004447/// ParseDIObjCProperty:
4448/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004449/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004450bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004451#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004452 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004453 OPTIONAL(file, MDField, ); \
4454 OPTIONAL(line, LineField, ); \
4455 OPTIONAL(setter, MDStringField, ); \
4456 OPTIONAL(getter, MDStringField, ); \
4457 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4458 OPTIONAL(type, MDField, );
4459 PARSE_MD_FIELDS();
4460#undef VISIT_MD_FIELDS
4461
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004462 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004463 (Context, name.Val, file.Val, line.Val, setter.Val,
4464 getter.Val, attributes.Val, type.Val));
4465 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004466}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004467
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004468/// ParseDIImportedEntity:
4469/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004470/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004471bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004472#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4473 REQUIRED(tag, DwarfTagField, ); \
4474 REQUIRED(scope, MDField, ); \
4475 OPTIONAL(entity, MDField, ); \
Adrian Prantld63bfd22017-07-19 00:09:54 +00004476 OPTIONAL(file, MDField, ); \
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004477 OPTIONAL(line, LineField, ); \
4478 OPTIONAL(name, MDStringField, );
4479 PARSE_MD_FIELDS();
4480#undef VISIT_MD_FIELDS
4481
Adrian Prantld63bfd22017-07-19 00:09:54 +00004482 Result = GET_OR_DISTINCT(
4483 DIImportedEntity,
4484 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004485 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004486}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004487
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004488#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004489#undef NOP_FIELD
4490#undef REQUIRE_FIELD
4491#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004492
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004493/// ParseMetadataAsValue
4494/// ::= metadata i32 %local
4495/// ::= metadata i32 @global
4496/// ::= metadata i32 7
4497/// ::= metadata !0
4498/// ::= metadata !{...}
4499/// ::= metadata !"string"
4500bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4501 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004502 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004503 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004504 return true;
4505
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004506 V = MetadataAsValue::get(Context, MD);
4507 return false;
4508}
4509
4510/// ParseValueAsMetadata
4511/// ::= i32 %local
4512/// ::= i32 @global
4513/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004514bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4515 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004516 Type *Ty;
4517 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004518 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004519 return true;
4520 if (Ty->isMetadataTy())
4521 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4522
4523 Value *V;
4524 if (ParseValue(Ty, V, PFS))
4525 return true;
4526
4527 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004528 return false;
4529}
4530
4531/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004532/// ::= i32 %local
4533/// ::= i32 @global
4534/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004535/// ::= !42
4536/// ::= !{...}
4537/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004538/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004539bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004540 if (Lex.getKind() == lltok::MetadataVar) {
4541 MDNode *N;
4542 if (ParseSpecializedMDNode(N))
4543 return true;
4544 MD = N;
4545 return false;
4546 }
4547
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004548 // ValueAsMetadata:
4549 // <type> <value>
4550 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004551 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004552
4553 // '!'.
4554 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4555 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004556
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004557 // MDString:
4558 // ::= '!' STRINGCONSTANT
4559 if (Lex.getKind() == lltok::StringConstant) {
4560 MDString *S;
4561 if (ParseMDString(S))
4562 return true;
4563 MD = S;
4564 return false;
4565 }
4566
Dan Gohman8939ba332010-07-14 18:26:50 +00004567 // MDNode:
4568 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004569 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004570 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004571 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004572 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004573 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004574 return false;
4575}
4576
Victor Hernandez9d75c962010-01-11 22:31:58 +00004577//===----------------------------------------------------------------------===//
4578// Function Parsing.
4579//===----------------------------------------------------------------------===//
4580
Chris Lattner229907c2011-07-18 04:54:35 +00004581bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004582 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004583 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004584 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Chris Lattnerac161bf2009-01-02 07:01:27 +00004586 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004587 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004588 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004589 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004590 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004592 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004593 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004594 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004595 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004596 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004597 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004598 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4599 (ID.UIntVal >> 1) & 1,
4600 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004601 return false;
4602 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 case ValID::t_GlobalName:
4604 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004605 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004606 case ValID::t_GlobalID:
4607 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004608 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004610 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004612 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004613 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004614 return false;
4615 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004616 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004617 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4618 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004619
Dan Gohman518cda42011-12-17 00:04:22 +00004620 // The lexer has no type info, so builds all half, float, and double FP
4621 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004622 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004624 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004625 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004626 &Ignored);
4627 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004628 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004629 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004631 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004632
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004633 if (V->getType() != Ty)
4634 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004635 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 return false;
4638 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004639 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004641 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 return false;
4643 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004644 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004645 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004646 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004647 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004649 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004650 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004651 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004652 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004653 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004655 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004656 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004657 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004658 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004660 case ValID::t_None:
4661 if (!Ty->isTokenTy())
4662 return Error(ID.Loc, "invalid type for none constant");
4663 V = Constant::getNullValue(Ty);
4664 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004666 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004667 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004668
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 V = ID.ConstantVal;
4670 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004671 case ValID::t_ConstantStruct:
4672 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004673 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004674 if (ST->getNumElements() != ID.UIntVal)
4675 return Error(ID.Loc,
4676 "initializer with struct type has wrong # elements");
4677 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4678 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004679
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004680 // Verify that the elements are compatible with the structtype.
4681 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4682 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4683 return Error(ID.Loc, "element " + Twine(i) +
4684 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004685
David Blaikieadbda4b2015-08-03 20:08:41 +00004686 V = ConstantStruct::get(
4687 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004688 } else
4689 return Error(ID.Loc, "constant expression type mismatch");
4690 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004691 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004692 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004693}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004694
Alex Lorenzd2255952015-07-17 22:07:03 +00004695bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4696 C = nullptr;
4697 ValID ID;
4698 auto Loc = Lex.getLoc();
4699 if (ParseValID(ID, /*PFS=*/nullptr))
4700 return true;
4701 switch (ID.Kind) {
4702 case ValID::t_APSInt:
4703 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004704 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004705 case ValID::t_Constant:
4706 case ValID::t_ConstantStruct:
4707 case ValID::t_PackedConstantStruct: {
4708 Value *V;
4709 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4710 return true;
4711 assert(isa<Constant>(V) && "Expected a constant value");
4712 C = cast<Constant>(V);
4713 return false;
4714 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004715 case ValID::t_Null:
4716 C = Constant::getNullValue(Ty);
4717 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004718 default:
4719 return Error(Loc, "expected a constant value");
4720 }
4721}
4722
David Majnemer8a1c45d2015-12-12 05:38:55 +00004723bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004724 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004725 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004726 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727}
4728
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004729bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004730 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004731 return ParseType(Ty) ||
4732 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004733}
4734
Chris Lattner3ed871f2009-10-27 19:13:16 +00004735bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4736 PerFunctionState &PFS) {
4737 Value *V;
4738 Loc = Lex.getLoc();
4739 if (ParseTypeAndValue(V, PFS)) return true;
4740 if (!isa<BasicBlock>(V))
4741 return Error(Loc, "expected a basic block");
4742 BB = cast<BasicBlock>(V);
4743 return false;
4744}
4745
Chris Lattnerac161bf2009-01-02 07:01:27 +00004746/// FunctionHeader
Sean Fertilec70d28b2017-10-26 15:00:26 +00004747/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4748/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4749/// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4750/// OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4752 // Parse the linkage.
4753 LocTy LinkageLoc = Lex.getLoc();
4754 unsigned Linkage;
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004755 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004756 unsigned DLLStorageClass;
Sean Fertilec70d28b2017-10-26 15:00:26 +00004757 bool DSOLocal;
Bill Wendling50d27842012-10-15 20:35:56 +00004758 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004759 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004760 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004761 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 LocTy RetTypeLoc = Lex.getLoc();
Sean Fertilec70d28b2017-10-26 15:00:26 +00004763 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
4764 DSOLocal) ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004765 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004766 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 return true;
4768
4769 // Verify that the linkage is ok.
4770 switch ((GlobalValue::LinkageTypes)Linkage) {
4771 case GlobalValue::ExternalLinkage:
4772 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004773 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004774 if (isDefine)
4775 return Error(LinkageLoc, "invalid linkage for function definition");
4776 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004777 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004779 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004780 case GlobalValue::LinkOnceAnyLinkage:
4781 case GlobalValue::LinkOnceODRLinkage:
4782 case GlobalValue::WeakAnyLinkage:
4783 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004784 if (!isDefine)
4785 return Error(LinkageLoc, "invalid linkage for function declaration");
4786 break;
4787 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004788 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004789 return Error(LinkageLoc, "invalid function linkage type");
4790 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004791
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004792 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4793 return Error(LinkageLoc,
4794 "symbol with local linkage must have default visibility");
4795
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004796 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004798
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004800
4801 std::string FunctionName;
4802 if (Lex.getKind() == lltok::GlobalVar) {
4803 FunctionName = Lex.getStrVal();
4804 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4805 unsigned NameID = Lex.getUIntVal();
4806
4807 if (NameID != NumberedVals.size())
4808 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004809 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004810 } else {
4811 return TokError("expected function name");
4812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattner3822f632009-01-02 08:05:26 +00004814 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004815
Chris Lattner3822f632009-01-02 08:05:26 +00004816 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004818
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004819 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004821 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004822 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004823 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004824 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004825 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004826 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004827 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Craig Topper2617dcc2014-04-15 06:32:26 +00004828 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004829 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004830 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004831 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004832
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004833 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004834 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004835 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004836 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004837 (EatIfPresent(lltok::kw_section) &&
4838 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004839 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004840 ParseOptionalAlignment(Alignment) ||
4841 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004842 ParseStringConstant(GC)) ||
4843 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004844 ParseGlobalTypeAndValue(Prefix)) ||
4845 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004846 ParseGlobalTypeAndValue(Prologue)) ||
4847 (EatIfPresent(lltok::kw_personality) &&
4848 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004849 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004850
Michael Gottesman41748d72013-06-27 00:25:01 +00004851 if (FuncAttrs.contains(Attribute::Builtin))
4852 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004853
Chris Lattnerac161bf2009-01-02 07:01:27 +00004854 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004855 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004856 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004857 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004859
Chris Lattnerac161bf2009-01-02 07:01:27 +00004860 // Okay, if we got here, the function is syntactically valid. Convert types
4861 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004862 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004863 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004864
Chris Lattnerac161bf2009-01-02 07:01:27 +00004865 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004866 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004867 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004868 }
4869
Reid Kleckner7f720332017-04-13 00:58:09 +00004870 AttributeList PAL =
4871 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4872 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004873
Bill Wendling749a43d2012-12-30 13:50:49 +00004874 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004875 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4876
Chris Lattner229907c2011-07-18 04:54:35 +00004877 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004878 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004879 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004880
Craig Topper2617dcc2014-04-15 06:32:26 +00004881 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004882 if (!FunctionName.empty()) {
4883 // If this was a definition of a forward reference, remove the definition
4884 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004885 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004886 if (FRVI != ForwardRefVals.end()) {
4887 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004888 if (!Fn)
4889 return Error(FRVI->second.second, "invalid forward reference to "
4890 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004891 if (Fn->getType() != PFT)
4892 return Error(FRVI->second.second, "invalid forward reference to "
4893 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004894
Chris Lattnerac161bf2009-01-02 07:01:27 +00004895 ForwardRefVals.erase(FRVI);
4896 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004897 // Reject redefinitions.
4898 return Error(NameLoc, "invalid redefinition of function '" +
4899 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004900 } else if (M->getNamedValue(FunctionName)) {
4901 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004903
Dan Gohman399d6ae2009-08-29 23:37:49 +00004904 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 // If this is a definition of a forward referenced function, make sure the
4906 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004907 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004908 if (I != ForwardRefValIDs.end()) {
4909 Fn = cast<Function>(I->second.first);
4910 if (Fn->getType() != PFT)
4911 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004912 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913 ForwardRefValIDs.erase(I);
4914 }
4915 }
4916
Craig Topper2617dcc2014-04-15 06:32:26 +00004917 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004918 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4919 else // Move the forward-reference to the correct spot in the module.
4920 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4921
4922 if (FunctionName.empty())
4923 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004924
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
Sean Fertilec70d28b2017-10-26 15:00:26 +00004926 Fn->setDSOLocal(DSOLocal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004927 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004928 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004929 Fn->setCallingConv(CC);
4930 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004931 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932 Fn->setAlignment(Alignment);
4933 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004934 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004935 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004936 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004937 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004938 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004939 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 // Add all of the arguments we parsed to the function.
4942 Function::arg_iterator ArgIt = Fn->arg_begin();
4943 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4944 // If the argument has a name, insert it into the argument symbol table.
4945 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004946
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947 // Set the name, if it conflicted, it will be auto-renamed.
4948 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004949
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004950 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004951 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4952 ArgList[i].Name + "'");
4953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004954
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004955 if (isDefine)
4956 return false;
4957
Robin Morisset039781e2014-08-29 21:53:01 +00004958 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004959 ValID ID;
4960 if (FunctionName.empty()) {
4961 ID.Kind = ValID::t_GlobalID;
4962 ID.UIntVal = NumberedVals.size() - 1;
4963 } else {
4964 ID.Kind = ValID::t_GlobalName;
4965 ID.StrVal = FunctionName;
4966 }
4967 auto Blocks = ForwardRefBlockAddresses.find(ID);
4968 if (Blocks != ForwardRefBlockAddresses.end())
4969 return Error(Blocks->first.Loc,
4970 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 return false;
4972}
4973
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004974bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4975 ValID ID;
4976 if (FunctionNumber == -1) {
4977 ID.Kind = ValID::t_GlobalName;
4978 ID.StrVal = F.getName();
4979 } else {
4980 ID.Kind = ValID::t_GlobalID;
4981 ID.UIntVal = FunctionNumber;
4982 }
4983
4984 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4985 if (Blocks == P.ForwardRefBlockAddresses.end())
4986 return false;
4987
4988 for (const auto &I : Blocks->second) {
4989 const ValID &BBID = I.first;
4990 GlobalValue *GV = I.second;
4991
4992 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4993 "Expected local id or name");
4994 BasicBlock *BB;
4995 if (BBID.Kind == ValID::t_LocalName)
4996 BB = GetBB(BBID.StrVal, BBID.Loc);
4997 else
4998 BB = GetBB(BBID.UIntVal, BBID.Loc);
4999 if (!BB)
5000 return P.Error(BBID.Loc, "referenced value is not a basic block");
5001
5002 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5003 GV->eraseFromParent();
5004 }
5005
5006 P.ForwardRefBlockAddresses.erase(Blocks);
5007 return false;
5008}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009
5010/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005011/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00005012bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00005013 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 return TokError("expected '{' in function body");
5015 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005016
Chris Lattner3432c622009-10-28 03:39:23 +00005017 int FunctionNumber = -1;
5018 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005019
Chris Lattner3432c622009-10-28 03:39:23 +00005020 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005021
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00005022 // Resolve block addresses and allow basic blocks to be forward-declared
5023 // within this function.
5024 if (PFS.resolveForwardRefBlockAddresses())
5025 return true;
5026 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5027
Chris Lattnerbbddd962010-01-09 19:20:07 +00005028 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005029 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00005030 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005031
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005032 while (Lex.getKind() != lltok::rbrace &&
5033 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005034 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005035
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005036 while (Lex.getKind() != lltok::rbrace)
5037 if (ParseUseListOrder(&PFS))
5038 return true;
5039
Chris Lattnerac161bf2009-01-02 07:01:27 +00005040 // Eat the }.
5041 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005042
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00005044 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005045}
5046
5047/// ParseBasicBlock
5048/// ::= LabelStr? Instruction*
5049bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5050 // If this basic block starts out with a name, remember it.
5051 std::string Name;
5052 LocTy NameLoc = Lex.getLoc();
5053 if (Lex.getKind() == lltok::LabelStr) {
5054 Name = Lex.getStrVal();
5055 Lex.Lex();
5056 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005057
Chris Lattnerac161bf2009-01-02 07:01:27 +00005058 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00005059 if (!BB)
5060 return Error(NameLoc,
5061 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005062
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005064
Chris Lattnerac161bf2009-01-02 07:01:27 +00005065 // Parse the instructions in this block until we get a terminator.
5066 Instruction *Inst;
5067 do {
5068 // This instruction may have three possibilities for a name: a) none
5069 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5070 LocTy NameLoc = Lex.getLoc();
5071 int NameID = -1;
5072 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005073
Chris Lattnerac161bf2009-01-02 07:01:27 +00005074 if (Lex.getKind() == lltok::LocalVarID) {
5075 NameID = Lex.getUIntVal();
5076 Lex.Lex();
5077 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5078 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00005079 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 NameStr = Lex.getStrVal();
5081 Lex.Lex();
5082 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5083 return true;
5084 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005085
Chris Lattner77b89dc2009-12-30 05:23:43 +00005086 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00005087 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00005088 case InstError: return true;
5089 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005090 BB->getInstList().push_back(Inst);
5091
Chris Lattner77b89dc2009-12-30 05:23:43 +00005092 // With a normal result, we check to see if the instruction is followed by
5093 // a comma and metadata.
5094 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005095 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005096 return true;
5097 break;
5098 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005099 BB->getInstList().push_back(Inst);
5100
Chris Lattner77b89dc2009-12-30 05:23:43 +00005101 // If the instruction parser ate an extra comma at the end of it, it
5102 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005103 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005104 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005105 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005106 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005107
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108 // Set the name on the instruction.
5109 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5110 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005111
Chris Lattnerac161bf2009-01-02 07:01:27 +00005112 return false;
5113}
5114
5115//===----------------------------------------------------------------------===//
5116// Instruction Parsing.
5117//===----------------------------------------------------------------------===//
5118
5119/// ParseInstruction - Parse one of the many different instructions.
5120///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005121int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5122 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005123 lltok::Kind Token = Lex.getKind();
5124 if (Token == lltok::Eof)
5125 return TokError("found end of file when expecting more instructions");
5126 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005127 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005128 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005129
Chris Lattnerac161bf2009-01-02 07:01:27 +00005130 switch (Token) {
5131 default: return Error(Loc, "expected instruction opcode");
5132 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005133 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005134 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5135 case lltok::kw_br: return ParseBr(Inst, PFS);
5136 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005137 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005138 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005139 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005140 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5141 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005142 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5143 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005144 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005145 // Binary Operators.
5146 case lltok::kw_add:
5147 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005148 case lltok::kw_mul:
5149 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005150 bool NUW = EatIfPresent(lltok::kw_nuw);
5151 bool NSW = EatIfPresent(lltok::kw_nsw);
5152 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005153
Chris Lattnera676c0f2011-02-07 16:40:21 +00005154 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005155
Chris Lattnera676c0f2011-02-07 16:40:21 +00005156 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5157 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5158 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005159 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005160 case lltok::kw_fadd:
5161 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005162 case lltok::kw_fmul:
5163 case lltok::kw_fdiv:
5164 case lltok::kw_frem: {
5165 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5166 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5167 if (Res != 0)
5168 return Res;
5169 if (FMF.any())
5170 Inst->setFastMathFlags(FMF);
5171 return 0;
5172 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005173
Chris Lattner35315d02011-02-06 21:44:57 +00005174 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005175 case lltok::kw_udiv:
5176 case lltok::kw_lshr:
5177 case lltok::kw_ashr: {
5178 bool Exact = EatIfPresent(lltok::kw_exact);
5179
5180 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5181 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5182 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005183 }
5184
Chris Lattnerac161bf2009-01-02 07:01:27 +00005185 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005186 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005187 case lltok::kw_and:
5188 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005189 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005190 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5191 case lltok::kw_fcmp: {
5192 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5193 int Res = ParseCompare(Inst, PFS, KeywordVal);
5194 if (Res != 0)
5195 return Res;
5196 if (FMF.any())
5197 Inst->setFastMathFlags(FMF);
5198 return 0;
5199 }
5200
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 // Casts.
5202 case lltok::kw_trunc:
5203 case lltok::kw_zext:
5204 case lltok::kw_sext:
5205 case lltok::kw_fptrunc:
5206 case lltok::kw_fpext:
5207 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005208 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 case lltok::kw_uitofp:
5210 case lltok::kw_sitofp:
5211 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005212 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005213 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005214 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 // Other.
5216 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005217 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5219 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5220 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5221 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005222 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005223 // Call.
5224 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5225 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5226 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005227 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005228 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005229 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005230 case lltok::kw_load: return ParseLoad(Inst, PFS);
5231 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005232 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5233 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005234 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005235 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5236 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5237 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5238 }
5239}
5240
5241/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5242bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005243 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005244 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005245 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005246 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5247 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5248 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5249 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5250 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5251 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5252 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5253 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5254 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5255 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5256 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5257 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5258 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5259 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5260 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5261 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5262 }
5263 } else {
5264 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005265 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005266 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5267 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5268 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5269 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5270 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5271 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5272 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5273 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5274 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5275 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5276 }
5277 }
5278 Lex.Lex();
5279 return false;
5280}
5281
5282//===----------------------------------------------------------------------===//
5283// Terminator Instructions.
5284//===----------------------------------------------------------------------===//
5285
5286/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005287/// ::= 'ret' void (',' !dbg, !1)*
5288/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005289bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005290 PerFunctionState &PFS) {
5291 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005292 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005293 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005294
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005295 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005296
Chris Lattnerfdd87902009-10-05 05:54:46 +00005297 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005298 if (!ResType->isVoidTy())
5299 return Error(TypeLoc, "value doesn't match function result type '" +
5300 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005301
Owen Anderson55f1c092009-08-13 21:58:54 +00005302 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005303 return false;
5304 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005305
Chris Lattnerac161bf2009-01-02 07:01:27 +00005306 Value *RV;
5307 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005309 if (ResType != RV->getType())
5310 return Error(TypeLoc, "value doesn't match function result type '" +
5311 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005312
Owen Anderson55f1c092009-08-13 21:58:54 +00005313 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005314 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005315}
5316
Chris Lattnerac161bf2009-01-02 07:01:27 +00005317/// ParseBr
5318/// ::= 'br' TypeAndValue
5319/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5320bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5321 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005322 Value *Op0;
5323 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005324 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005325
Chris Lattnerac161bf2009-01-02 07:01:27 +00005326 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5327 Inst = BranchInst::Create(BB);
5328 return false;
5329 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005330
Owen Anderson55f1c092009-08-13 21:58:54 +00005331 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005332 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005333
Chris Lattnerac161bf2009-01-02 07:01:27 +00005334 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005335 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005337 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005338 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005339
Chris Lattner3ed871f2009-10-27 19:13:16 +00005340 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005341 return false;
5342}
5343
5344/// ParseSwitch
5345/// Instruction
5346/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5347/// JumpTable
5348/// ::= (TypeAndValue ',' TypeAndValue)*
5349bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5350 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005351 Value *Cond;
5352 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5354 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005355 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005356 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5357 return true;
5358
Duncan Sands19d0b472010-02-16 11:11:14 +00005359 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005360 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005361
Chris Lattnerac161bf2009-01-02 07:01:27 +00005362 // Parse the jump table pairs.
5363 SmallPtrSet<Value*, 32> SeenCases;
5364 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5365 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005366 Value *Constant;
5367 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005368
Chris Lattnerac161bf2009-01-02 07:01:27 +00005369 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5370 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005371 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005372 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005373
David Blaikie70573dc2014-11-19 07:49:26 +00005374 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 return Error(CondLoc, "duplicate case value in switch");
5376 if (!isa<ConstantInt>(Constant))
5377 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005378
Chris Lattner3ed871f2009-10-27 19:13:16 +00005379 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005381
Chris Lattnerac161bf2009-01-02 07:01:27 +00005382 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005383
Chris Lattner3ed871f2009-10-27 19:13:16 +00005384 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005385 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5386 SI->addCase(Table[i].first, Table[i].second);
5387 Inst = SI;
5388 return false;
5389}
5390
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005391/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005392/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005393/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5394bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005395 LocTy AddrLoc;
5396 Value *Address;
5397 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005398 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5399 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005400 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005401
Duncan Sands19d0b472010-02-16 11:11:14 +00005402 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005403 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005404
Chris Lattner3ed871f2009-10-27 19:13:16 +00005405 // Parse the destination list.
5406 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005407
Chris Lattner3ed871f2009-10-27 19:13:16 +00005408 if (Lex.getKind() != lltok::rsquare) {
5409 BasicBlock *DestBB;
5410 if (ParseTypeAndBasicBlock(DestBB, PFS))
5411 return true;
5412 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005413
Chris Lattner3ed871f2009-10-27 19:13:16 +00005414 while (EatIfPresent(lltok::comma)) {
5415 if (ParseTypeAndBasicBlock(DestBB, PFS))
5416 return true;
5417 DestList.push_back(DestBB);
5418 }
5419 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005420
Chris Lattner3ed871f2009-10-27 19:13:16 +00005421 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5422 return true;
5423
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005424 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005425 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5426 IBI->addDestination(DestList[i]);
5427 Inst = IBI;
5428 return false;
5429}
5430
Chris Lattnerac161bf2009-01-02 07:01:27 +00005431/// ParseInvoke
5432/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5433/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5434bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5435 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005436 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005437 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005438 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005439 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005440 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005441 LocTy RetTypeLoc;
5442 ValID CalleeID;
5443 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005444 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005445
Chris Lattner3ed871f2009-10-27 19:13:16 +00005446 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005447 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005448 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005449 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005450 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5451 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005452 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005453 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005454 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005455 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005456 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005457 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005458
Chris Lattnerac161bf2009-01-02 07:01:27 +00005459 // If RetType is a non-function pointer type, then this is the short syntax
5460 // for the call, which means that RetType is just the return type. Infer the
5461 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005462 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5463 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005464 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005465 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005466 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5467 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005468
Chris Lattnerac161bf2009-01-02 07:01:27 +00005469 if (!FunctionType::isValidReturnType(RetType))
5470 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005471
Owen Anderson4056ca92009-07-29 22:17:13 +00005472 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005474
David Blaikie41ba2b42015-07-27 23:32:19 +00005475 CalleeID.FTy = Ty;
5476
Chris Lattnerac161bf2009-01-02 07:01:27 +00005477 // Look up the callee.
5478 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005479 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5480 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005481
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005482 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005483 SmallVector<Value *, 8> Args;
5484 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005485
Chris Lattnerac161bf2009-01-02 07:01:27 +00005486 // Loop through FunctionType's arguments and ensure they are specified
5487 // correctly. Also, gather any parameter attributes.
5488 FunctionType::param_iterator I = Ty->param_begin();
5489 FunctionType::param_iterator E = Ty->param_end();
5490 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005491 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005492 if (I != E) {
5493 ExpectedTy = *I++;
5494 } else if (!Ty->isVarArg()) {
5495 return Error(ArgList[i].Loc, "too many arguments specified");
5496 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005497
Chris Lattnerac161bf2009-01-02 07:01:27 +00005498 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5499 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005500 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005501 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005502 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005504
Chris Lattnerac161bf2009-01-02 07:01:27 +00005505 if (I != E)
5506 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005507
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005508 if (FnAttrs.hasAlignmentAttr())
5509 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005510
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005511 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005512 AttributeList PAL =
5513 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5514 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005515
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005516 InvokeInst *II =
5517 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005518 II->setCallingConv(CC);
5519 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005520 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005521 Inst = II;
5522 return false;
5523}
5524
Bill Wendlingf891bf82011-07-31 06:30:59 +00005525/// ParseResume
5526/// ::= 'resume' TypeAndValue
5527bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5528 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005529 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5530 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005531
Bill Wendlingf891bf82011-07-31 06:30:59 +00005532 ResumeInst *RI = ResumeInst::Create(Exn);
5533 Inst = RI;
5534 return false;
5535}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005536
David Majnemer654e1302015-07-31 17:58:14 +00005537bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5538 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005539 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005540 return true;
5541
5542 while (Lex.getKind() != lltok::rsquare) {
5543 // If this isn't the first argument, we need a comma.
5544 if (!Args.empty() &&
5545 ParseToken(lltok::comma, "expected ',' in argument list"))
5546 return true;
5547
5548 // Parse the argument.
5549 LocTy ArgLoc;
5550 Type *ArgTy = nullptr;
5551 if (ParseType(ArgTy, ArgLoc))
5552 return true;
5553
5554 Value *V;
5555 if (ArgTy->isMetadataTy()) {
5556 if (ParseMetadataAsValue(V, PFS))
5557 return true;
5558 } else {
5559 if (ParseValue(ArgTy, V, PFS))
5560 return true;
5561 }
5562 Args.push_back(V);
5563 }
5564
5565 Lex.Lex(); // Lex the ']'.
5566 return false;
5567}
5568
5569/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005570/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005571bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005572 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005573
David Majnemer8a1c45d2015-12-12 05:38:55 +00005574 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5575 return true;
5576
5577 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005578 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005579
5580 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5581 return true;
5582
5583 BasicBlock *UnwindBB = nullptr;
5584 if (Lex.getKind() == lltok::kw_to) {
5585 Lex.Lex();
5586 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5587 return true;
5588 } else {
5589 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5590 return true;
5591 }
5592 }
5593
David Majnemer8a1c45d2015-12-12 05:38:55 +00005594 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005595 return false;
5596}
5597
5598/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005599/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005600bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005601 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005602
David Majnemer8a1c45d2015-12-12 05:38:55 +00005603 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5604 return true;
5605
5606 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005607 return true;
5608
David Majnemer0bc0eef2015-08-15 02:46:08 +00005609 BasicBlock *BB;
5610 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5611 ParseTypeAndBasicBlock(BB, PFS))
5612 return true;
5613
David Majnemer8a1c45d2015-12-12 05:38:55 +00005614 Inst = CatchReturnInst::Create(CatchPad, BB);
5615 return false;
5616}
5617
5618/// ParseCatchSwitch
5619/// ::= 'catchswitch' within Parent
5620bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5621 Value *ParentPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005622
5623 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5624 return true;
5625
5626 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5627 Lex.getKind() != lltok::LocalVarID)
5628 return TokError("expected scope value for catchswitch");
5629
5630 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5631 return true;
5632
5633 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5634 return true;
5635
5636 SmallVector<BasicBlock *, 32> Table;
5637 do {
5638 BasicBlock *DestBB;
5639 if (ParseTypeAndBasicBlock(DestBB, PFS))
5640 return true;
5641 Table.push_back(DestBB);
5642 } while (EatIfPresent(lltok::comma));
5643
5644 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5645 return true;
5646
5647 if (ParseToken(lltok::kw_unwind,
5648 "expected 'unwind' after catchswitch scope"))
5649 return true;
5650
5651 BasicBlock *UnwindBB = nullptr;
5652 if (EatIfPresent(lltok::kw_to)) {
5653 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5654 return true;
5655 } else {
5656 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5657 return true;
5658 }
5659
5660 auto *CatchSwitch =
5661 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5662 for (BasicBlock *DestBB : Table)
5663 CatchSwitch->addHandler(DestBB);
5664 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005665 return false;
5666}
5667
5668/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005669/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005670bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005671 Value *CatchSwitch = nullptr;
5672
5673 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5674 return true;
5675
5676 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5677 return TokError("expected scope value for catchpad");
5678
5679 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5680 return true;
5681
David Majnemer654e1302015-07-31 17:58:14 +00005682 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005683 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005684 return true;
5685
David Majnemer8a1c45d2015-12-12 05:38:55 +00005686 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005687 return false;
5688}
5689
David Majnemer654e1302015-07-31 17:58:14 +00005690/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005691/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005692bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005693 Value *ParentPad = nullptr;
5694
5695 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5696 return true;
5697
5698 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5699 Lex.getKind() != lltok::LocalVarID)
5700 return TokError("expected scope value for cleanuppad");
5701
5702 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5703 return true;
5704
David Majnemer654e1302015-07-31 17:58:14 +00005705 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005706 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005707 return true;
5708
David Majnemer8a1c45d2015-12-12 05:38:55 +00005709 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005710 return false;
5711}
5712
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713//===----------------------------------------------------------------------===//
5714// Binary Operators.
5715//===----------------------------------------------------------------------===//
5716
5717/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005718/// ::= ArithmeticOps TypeAndValue ',' Value
5719///
5720/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5721/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005722bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005723 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005724 LocTy Loc; Value *LHS, *RHS;
5725 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5726 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5727 ParseValue(LHS->getType(), RHS, PFS))
5728 return true;
5729
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005730 bool Valid;
5731 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005732 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005733 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005734 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5735 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005736 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005737 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5738 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005739 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005740
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005741 if (!Valid)
5742 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005743
Chris Lattnerac161bf2009-01-02 07:01:27 +00005744 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5745 return false;
5746}
5747
5748/// ParseLogical
5749/// ::= ArithmeticOps TypeAndValue ',' Value {
5750bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5751 unsigned Opc) {
5752 LocTy Loc; Value *LHS, *RHS;
5753 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5754 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5755 ParseValue(LHS->getType(), RHS, PFS))
5756 return true;
5757
Duncan Sands9dff9be2010-02-15 16:12:20 +00005758 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005759 return Error(Loc,"instruction requires integer or integer vector operands");
5760
5761 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5762 return false;
5763}
5764
Chris Lattnerac161bf2009-01-02 07:01:27 +00005765/// ParseCompare
5766/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5767/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5769 unsigned Opc) {
5770 // Parse the integer/fp comparison predicate.
5771 LocTy Loc;
5772 unsigned Pred;
5773 Value *LHS, *RHS;
5774 if (ParseCmpPredicate(Pred, Opc) ||
5775 ParseTypeAndValue(LHS, Loc, PFS) ||
5776 ParseToken(lltok::comma, "expected ',' after compare value") ||
5777 ParseValue(LHS->getType(), RHS, PFS))
5778 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005779
Chris Lattnerac161bf2009-01-02 07:01:27 +00005780 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005781 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005782 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005783 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005784 } else {
5785 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005786 if (!LHS->getType()->isIntOrIntVectorTy() &&
Craig Topper95d23472017-07-09 07:04:00 +00005787 !LHS->getType()->isPtrOrPtrVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005789 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005790 }
5791 return false;
5792}
5793
5794//===----------------------------------------------------------------------===//
5795// Other Instructions.
5796//===----------------------------------------------------------------------===//
5797
5798
5799/// ParseCast
5800/// ::= CastOpc TypeAndValue 'to' Type
5801bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5802 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005803 LocTy Loc;
5804 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005805 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005806 if (ParseTypeAndValue(Op, Loc, PFS) ||
5807 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5808 ParseType(DestTy))
5809 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005810
Chris Lattner89d856e2009-03-01 00:53:13 +00005811 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5812 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005814 getTypeString(Op->getType()) + "' to '" +
5815 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005816 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005817 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5818 return false;
5819}
5820
5821/// ParseSelect
5822/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5823bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5824 LocTy Loc;
5825 Value *Op0, *Op1, *Op2;
5826 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5827 ParseToken(lltok::comma, "expected ',' after select condition") ||
5828 ParseTypeAndValue(Op1, PFS) ||
5829 ParseToken(lltok::comma, "expected ',' after select value") ||
5830 ParseTypeAndValue(Op2, PFS))
5831 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005832
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5834 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005835
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 Inst = SelectInst::Create(Op0, Op1, Op2);
5837 return false;
5838}
5839
Chris Lattnerb55ab542009-01-05 08:18:44 +00005840/// ParseVA_Arg
5841/// ::= 'va_arg' TypeAndValue ',' Type
5842bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005843 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005844 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005845 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 if (ParseTypeAndValue(Op, PFS) ||
5847 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005848 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005849 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005850
Chris Lattnerb55ab542009-01-05 08:18:44 +00005851 if (!EltTy->isFirstClassType())
5852 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853
5854 Inst = new VAArgInst(Op, EltTy);
5855 return false;
5856}
5857
5858/// ParseExtractElement
5859/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5860bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5861 LocTy Loc;
5862 Value *Op0, *Op1;
5863 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5864 ParseToken(lltok::comma, "expected ',' after extract value") ||
5865 ParseTypeAndValue(Op1, PFS))
5866 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005867
Chris Lattnerac161bf2009-01-02 07:01:27 +00005868 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5869 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005870
Eric Christopherc9742252009-07-25 02:28:41 +00005871 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005872 return false;
5873}
5874
5875/// ParseInsertElement
5876/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5877bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5878 LocTy Loc;
5879 Value *Op0, *Op1, *Op2;
5880 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5881 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5882 ParseTypeAndValue(Op1, PFS) ||
5883 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5884 ParseTypeAndValue(Op2, PFS))
5885 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005886
Chris Lattnerac161bf2009-01-02 07:01:27 +00005887 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005888 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005889
Chris Lattnerac161bf2009-01-02 07:01:27 +00005890 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5891 return false;
5892}
5893
5894/// ParseShuffleVector
5895/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5896bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5897 LocTy Loc;
5898 Value *Op0, *Op1, *Op2;
5899 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5900 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5901 ParseTypeAndValue(Op1, PFS) ||
5902 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5903 ParseTypeAndValue(Op2, PFS))
5904 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005905
Chris Lattnerac161bf2009-01-02 07:01:27 +00005906 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005907 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005908
Chris Lattnerac161bf2009-01-02 07:01:27 +00005909 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5910 return false;
5911}
5912
5913/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005914/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005915int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005916 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005917 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005918
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005919 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005920 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5921 ParseValue(Ty, Op0, PFS) ||
5922 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005923 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005924 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5925 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005926
Chris Lattnerf4f03422009-12-30 05:27:33 +00005927 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005928 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005929
5930 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005931 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005932
Chris Lattner3822f632009-01-02 08:05:26 +00005933 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005934 break;
5935
Chris Lattnerf4f03422009-12-30 05:27:33 +00005936 if (Lex.getKind() == lltok::MetadataVar) {
5937 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005938 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005939 }
Devang Patel8f842d32009-10-16 18:45:49 +00005940
Chris Lattner3822f632009-01-02 08:05:26 +00005941 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005942 ParseValue(Ty, Op0, PFS) ||
5943 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005944 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005945 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5946 return true;
5947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005948
Chris Lattnerac161bf2009-01-02 07:01:27 +00005949 if (!Ty->isFirstClassType())
5950 return Error(TypeLoc, "phi node must have first class type");
5951
Jay Foad52131342011-03-30 11:28:46 +00005952 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005953 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5954 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5955 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005956 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005957}
5958
Bill Wendlingfae14752011-08-12 20:24:12 +00005959/// ParseLandingPad
5960/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5961/// Clause
5962/// ::= 'catch' TypeAndValue
5963/// ::= 'filter'
5964/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5965bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005966 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005967
David Majnemer7fddecc2015-06-17 20:52:32 +00005968 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005969 return true;
5970
David Majnemer7fddecc2015-06-17 20:52:32 +00005971 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005972 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5973
5974 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5975 LandingPadInst::ClauseType CT;
5976 if (EatIfPresent(lltok::kw_catch))
5977 CT = LandingPadInst::Catch;
5978 else if (EatIfPresent(lltok::kw_filter))
5979 CT = LandingPadInst::Filter;
5980 else
5981 return TokError("expected 'catch' or 'filter' clause type");
5982
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005983 Value *V;
5984 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005985 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005986 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005987
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005988 // A 'catch' type expects a non-array constant. A filter clause expects an
5989 // array constant.
5990 if (CT == LandingPadInst::Catch) {
5991 if (isa<ArrayType>(V->getType()))
5992 Error(VLoc, "'catch' clause has an invalid type");
5993 } else {
5994 if (!isa<ArrayType>(V->getType()))
5995 Error(VLoc, "'filter' clause has an invalid type");
5996 }
5997
Owen Andersonf8f259d2015-03-09 07:13:42 +00005998 Constant *CV = dyn_cast<Constant>(V);
5999 if (!CV)
6000 return Error(VLoc, "clause argument must be a constant");
6001 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00006002 }
6003
Owen Andersonf8f259d2015-03-09 07:13:42 +00006004 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00006005 return false;
6006}
6007
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006009/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6010/// OptionalAttrs Type Value ParameterList OptionalAttrs
6011/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6012/// OptionalAttrs Type Value ParameterList OptionalAttrs
6013/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6014/// OptionalAttrs Type Value ParameterList OptionalAttrs
6015/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6016/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00006017bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00006018 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00006019 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00006020 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00006021 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00006022 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00006023 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006024 LocTy RetTypeLoc;
6025 ValID CalleeID;
6026 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006027 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006029
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006030 if (TCK != CallInst::TCK_None &&
6031 ParseToken(lltok::kw_call,
6032 "expected 'tail call', 'musttail call', or 'notail call'"))
6033 return true;
6034
6035 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6036
6037 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00006038 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00006039 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00006040 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6041 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006042 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6043 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006044 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006045
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006046 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6047 return Error(CallLoc, "fast-math-flags specified for call without "
6048 "floating-point scalar or vector return type");
6049
Chris Lattnerac161bf2009-01-02 07:01:27 +00006050 // If RetType is a non-function pointer type, then this is the short syntax
6051 // for the call, which means that RetType is just the return type. Infer the
6052 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00006053 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6054 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006055 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00006056 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00006057 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6058 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006059
Chris Lattnerac161bf2009-01-02 07:01:27 +00006060 if (!FunctionType::isValidReturnType(RetType))
6061 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006062
Owen Anderson4056ca92009-07-29 22:17:13 +00006063 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006064 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006065
David Blaikie41ba2b42015-07-27 23:32:19 +00006066 CalleeID.FTy = Ty;
6067
Chris Lattnerac161bf2009-01-02 07:01:27 +00006068 // Look up the callee.
6069 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00006070 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6071 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006072
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006073 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00006074 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006075
Chris Lattnerac161bf2009-01-02 07:01:27 +00006076 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006077
Chris Lattnerac161bf2009-01-02 07:01:27 +00006078 // Loop through FunctionType's arguments and ensure they are specified
6079 // correctly. Also, gather any parameter attributes.
6080 FunctionType::param_iterator I = Ty->param_begin();
6081 FunctionType::param_iterator E = Ty->param_end();
6082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006083 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006084 if (I != E) {
6085 ExpectedTy = *I++;
6086 } else if (!Ty->isVarArg()) {
6087 return Error(ArgList[i].Loc, "too many arguments specified");
6088 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006089
Chris Lattnerac161bf2009-01-02 07:01:27 +00006090 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6091 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006092 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006093 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006094 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006095 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006096
Chris Lattnerac161bf2009-01-02 07:01:27 +00006097 if (I != E)
6098 return Error(CallLoc, "not enough parameters specified for call");
6099
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006100 if (FnAttrs.hasAlignmentAttr())
6101 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006102
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006103 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006104 AttributeList PAL =
6105 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6106 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006107
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006108 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006109 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006110 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006111 if (FMF.any())
6112 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006114 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006115 Inst = CI;
6116 return false;
6117}
6118
6119//===----------------------------------------------------------------------===//
6120// Memory Instructions.
6121//===----------------------------------------------------------------------===//
6122
6123/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006124/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
Yaxun Liuadde4e42017-10-14 03:23:18 +00006125/// (',' 'align' i32)? (',', 'addrspace(n))?
Chris Lattner78103722011-06-17 03:16:47 +00006126int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006127 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006128 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006129 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006130 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006131 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006132
6133 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006134 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006135
David Majnemera3b0eb22015-02-16 08:38:03 +00006136 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006137
David Majnemera3b0eb22015-02-16 08:38:03 +00006138 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6139 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006140
Chris Lattnerb2f39502009-12-30 05:44:30 +00006141 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006142 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006143 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006144 if (ParseOptionalAlignment(Alignment))
6145 return true;
6146 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6147 return true;
6148 } else if (Lex.getKind() == lltok::kw_addrspace) {
6149 ASLoc = Lex.getLoc();
6150 if (ParseOptionalAddrSpace(AddrSpace))
6151 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006152 } else if (Lex.getKind() == lltok::MetadataVar) {
6153 AteExtraComma = true;
6154 } else {
Yaxun Liuadde4e42017-10-14 03:23:18 +00006155 if (ParseTypeAndValue(Size, SizeLoc, PFS))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006156 return true;
Yaxun Liuadde4e42017-10-14 03:23:18 +00006157 if (EatIfPresent(lltok::comma)) {
6158 if (Lex.getKind() == lltok::kw_align) {
6159 if (ParseOptionalAlignment(Alignment))
6160 return true;
6161 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6162 return true;
6163 } else if (Lex.getKind() == lltok::kw_addrspace) {
6164 ASLoc = Lex.getLoc();
6165 if (ParseOptionalAddrSpace(AddrSpace))
6166 return true;
6167 } else if (Lex.getKind() == lltok::MetadataVar) {
6168 AteExtraComma = true;
6169 }
6170 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006171 }
6172 }
6173
Dan Gohman2140a742010-05-28 01:14:11 +00006174 if (Size && !Size->getType()->isIntegerTy())
6175 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006176
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006177 const DataLayout &DL = M->getDataLayout();
6178 unsigned AS = DL.getAllocaAddrSpace();
6179 if (AS != AddrSpace) {
6180 // TODO: In the future it should be possible to specify addrspace per-alloca.
6181 return Error(ASLoc, "address space must match datalayout");
6182 }
6183
6184 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006185 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006186 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006187 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006188 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006189}
6190
6191/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006192/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006193/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006194/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006195int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006196 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006197 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006198 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006199 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006200 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006201 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006202
6203 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006204 isAtomic = true;
6205 Lex.Lex();
6206 }
6207
Chris Lattnerbc639292011-11-27 06:56:53 +00006208 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006209 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006210 isVolatile = true;
6211 Lex.Lex();
6212 }
6213
David Blaikie15d9a4c2015-04-06 20:59:48 +00006214 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006215 LocTy ExplicitTypeLoc = Lex.getLoc();
6216 if (ParseType(Ty) ||
6217 ParseToken(lltok::comma, "expected comma after load's type") ||
6218 ParseTypeAndValue(Val, Loc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006219 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006220 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6221 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006222
David Blaikie15d9a4c2015-04-06 20:59:48 +00006223 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006224 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006225 if (isAtomic && !Alignment)
6226 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006227 if (Ordering == AtomicOrdering::Release ||
6228 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006229 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006230
David Blaikiea79ac142015-02-27 21:17:42 +00006231 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6232 return Error(ExplicitTypeLoc,
6233 "explicit pointee type doesn't match operand's pointee type");
6234
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006235 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006236 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006237}
6238
6239/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006240
6241/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6242/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006243/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006244int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006245 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006246 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006247 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006248 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006249 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006250 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006251
6252 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006253 isAtomic = true;
6254 Lex.Lex();
6255 }
6256
Chris Lattnerbc639292011-11-27 06:56:53 +00006257 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006258 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006259 isVolatile = true;
6260 Lex.Lex();
6261 }
6262
Chris Lattnerac161bf2009-01-02 07:01:27 +00006263 if (ParseTypeAndValue(Val, Loc, PFS) ||
6264 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006265 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006266 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006267 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006268 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006269
Duncan Sands19d0b472010-02-16 11:11:14 +00006270 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006271 return Error(PtrLoc, "store operand must be a pointer");
6272 if (!Val->getType()->isFirstClassType())
6273 return Error(Loc, "store operand must be a first class value");
6274 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6275 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006276 if (isAtomic && !Alignment)
6277 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006278 if (Ordering == AtomicOrdering::Acquire ||
6279 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006280 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006281
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006282 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006283 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006284}
6285
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006286/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006287/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6288/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006289int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006290 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6291 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006292 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6293 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006294 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006295 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006296 bool isWeak = false;
6297
6298 if (EatIfPresent(lltok::kw_weak))
6299 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006300
6301 if (EatIfPresent(lltok::kw_volatile))
6302 isVolatile = true;
6303
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006304 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6305 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6306 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6307 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6308 ParseTypeAndValue(New, NewLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006309 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006310 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006311 return true;
6312
JF Bastien800f87a2016-04-06 21:19:33 +00006313 if (SuccessOrdering == AtomicOrdering::Unordered ||
6314 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006315 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006316 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6317 return TokError("cmpxchg failure argument shall be no stronger than the "
6318 "success argument");
6319 if (FailureOrdering == AtomicOrdering::Release ||
6320 FailureOrdering == AtomicOrdering::AcquireRelease)
6321 return TokError(
6322 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006323 if (!Ptr->getType()->isPointerTy())
6324 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6325 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6326 return Error(CmpLoc, "compare value and pointer type do not match");
6327 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6328 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006329 if (!New->getType()->isFirstClassType())
6330 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006331 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006332 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006333 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006334 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006335 Inst = CXI;
6336 return AteExtraComma ? InstExtraComma : InstNormal;
6337}
6338
6339/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006340/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6341/// 'singlethread'? AtomicOrdering
6342int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006343 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6344 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006345 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006346 SyncScope::ID SSID = SyncScope::System;
Eli Friedman02e737b2011-08-12 22:50:01 +00006347 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006348 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006349
6350 if (EatIfPresent(lltok::kw_volatile))
6351 isVolatile = true;
6352
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006353 switch (Lex.getKind()) {
6354 default: return TokError("expected binary operation in atomicrmw");
6355 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6356 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6357 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6358 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6359 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6360 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6361 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6362 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6363 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6364 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6365 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6366 }
6367 Lex.Lex(); // Eat the operation.
6368
6369 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6370 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6371 ParseTypeAndValue(Val, ValLoc, PFS) ||
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006372 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006373 return true;
6374
JF Bastien800f87a2016-04-06 21:19:33 +00006375 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006376 return TokError("atomicrmw cannot be unordered");
6377 if (!Ptr->getType()->isPointerTy())
6378 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6379 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6380 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6381 if (!Val->getType()->isIntegerTy())
6382 return Error(ValLoc, "atomicrmw operand must be an integer");
6383 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6384 if (Size < 8 || (Size & (Size - 1)))
6385 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6386 " integer");
6387
6388 AtomicRMWInst *RMWI =
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006389 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006390 RMWI->setVolatile(isVolatile);
6391 Inst = RMWI;
6392 return AteExtraComma ? InstExtraComma : InstNormal;
6393}
6394
Eli Friedmanfee02c62011-07-25 23:16:38 +00006395/// ParseFence
6396/// ::= 'fence' 'singlethread'? AtomicOrdering
6397int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006398 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006399 SyncScope::ID SSID = SyncScope::System;
6400 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
Eli Friedmanfee02c62011-07-25 23:16:38 +00006401 return true;
6402
JF Bastien800f87a2016-04-06 21:19:33 +00006403 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006404 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006405 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006406 return TokError("fence cannot be monotonic");
6407
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00006408 Inst = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00006409 return InstNormal;
6410}
6411
Chris Lattnerac161bf2009-01-02 07:01:27 +00006412/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006413/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006414int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006415 Value *Ptr = nullptr;
6416 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006417 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006418
Dan Gohman16cbbe42009-07-29 15:58:36 +00006419 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006420
David Blaikie79e6c742015-02-27 19:29:02 +00006421 Type *Ty = nullptr;
6422 LocTy ExplicitTypeLoc = Lex.getLoc();
6423 if (ParseType(Ty) ||
6424 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6425 ParseTypeAndValue(Ptr, Loc, PFS))
6426 return true;
6427
Eli Benderskyd9806682013-04-22 17:03:42 +00006428 Type *BaseType = Ptr->getType();
6429 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6430 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006431 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006432
David Blaikie8d757942015-03-09 23:08:44 +00006433 if (Ty != BasePointerType->getElementType())
6434 return Error(ExplicitTypeLoc,
6435 "explicit pointee type doesn't match operand's pointee type");
6436
Chris Lattnerac161bf2009-01-02 07:01:27 +00006437 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006438 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006439 // GEP returns a vector of pointers if at least one of parameters is a vector.
6440 // All vector parameters should have the same vector width.
6441 unsigned GEPWidth = BaseType->isVectorTy() ?
6442 BaseType->getVectorNumElements() : 0;
6443
Chris Lattner3822f632009-01-02 08:05:26 +00006444 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006445 if (Lex.getKind() == lltok::MetadataVar) {
6446 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006447 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006448 }
Chris Lattner3822f632009-01-02 08:05:26 +00006449 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Craig Topper95d23472017-07-09 07:04:00 +00006450 if (!Val->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006451 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006452
Nadav Rotem3924cb02011-12-05 06:29:09 +00006453 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006454 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6455 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006456 return Error(EltLoc,
6457 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006458 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006459 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006460 Indices.push_back(Val);
6461 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006462
Craig Toppere3dcce92015-08-01 22:20:21 +00006463 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006464 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006465 return Error(Loc, "base element of getelementptr must be sized");
6466
David Blaikied33bad32015-04-17 22:32:13 +00006467 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006468 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006469 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006470 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006471 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006472 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006473}
6474
6475/// ParseExtractValue
6476/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006477int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006478 Value *Val; LocTy Loc;
6479 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006480 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006481 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006482 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006483 return true;
6484
Chris Lattner392be582010-02-12 20:49:41 +00006485 if (!Val->getType()->isAggregateType())
6486 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006487
Jay Foad57aa6362011-07-13 10:26:04 +00006488 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006489 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006490 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006491 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006492}
6493
6494/// ParseInsertValue
6495/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006496int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006497 Value *Val0, *Val1; LocTy Loc0, Loc1;
6498 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006499 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006500 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6501 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6502 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006503 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006504 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006505
Chris Lattner392be582010-02-12 20:49:41 +00006506 if (!Val0->getType()->isAggregateType())
6507 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006508
David Majnemer30074532015-02-11 07:43:58 +00006509 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6510 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006511 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006512 if (IndexedType != Val1->getType())
6513 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6514 getTypeString(Val1->getType()) + "' instead of '" +
6515 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006516 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006517 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006518}
Nick Lewycky49f89192009-04-04 07:22:01 +00006519
6520//===----------------------------------------------------------------------===//
6521// Embedded metadata.
6522//===----------------------------------------------------------------------===//
6523
6524/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006525/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006526/// Element
6527/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006528bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006529 if (ParseToken(lltok::lbrace, "expected '{' here"))
6530 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006531
Dan Gohman1e0213a2010-07-13 19:33:27 +00006532 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006533 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006534 return false;
6535
Nick Lewycky49f89192009-04-04 07:22:01 +00006536 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006537 // Null is a special case since it is typeless.
6538 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006539 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006540 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006541 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006542
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006543 Metadata *MD;
6544 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006545 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006546 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006547 } while (EatIfPresent(lltok::comma));
6548
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006549 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006550}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006551
6552//===----------------------------------------------------------------------===//
6553// Use-list order directives.
6554//===----------------------------------------------------------------------===//
6555bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6556 SMLoc Loc) {
6557 if (V->use_empty())
6558 return Error(Loc, "value has no uses");
6559
6560 unsigned NumUses = 0;
6561 SmallDenseMap<const Use *, unsigned, 16> Order;
6562 for (const Use &U : V->uses()) {
6563 if (++NumUses > Indexes.size())
6564 break;
6565 Order[&U] = Indexes[NumUses - 1];
6566 }
6567 if (NumUses < 2)
6568 return Error(Loc, "value only has one use");
6569 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6570 return Error(Loc, "wrong number of indexes, expected " +
6571 Twine(std::distance(V->use_begin(), V->use_end())));
6572
6573 V->sortUseList([&](const Use &L, const Use &R) {
6574 return Order.lookup(&L) < Order.lookup(&R);
6575 });
6576 return false;
6577}
6578
6579/// ParseUseListOrderIndexes
6580/// ::= '{' uint32 (',' uint32)+ '}'
6581bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6582 SMLoc Loc = Lex.getLoc();
6583 if (ParseToken(lltok::lbrace, "expected '{' here"))
6584 return true;
6585 if (Lex.getKind() == lltok::rbrace)
6586 return Lex.Error("expected non-empty list of uselistorder indexes");
6587
6588 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6589 // indexes should be distinct numbers in the range [0, size-1], and should
6590 // not be in order.
6591 unsigned Offset = 0;
6592 unsigned Max = 0;
6593 bool IsOrdered = true;
6594 assert(Indexes.empty() && "Expected empty order vector");
6595 do {
6596 unsigned Index;
6597 if (ParseUInt32(Index))
6598 return true;
6599
6600 // Update consistency checks.
6601 Offset += Index - Indexes.size();
6602 Max = std::max(Max, Index);
6603 IsOrdered &= Index == Indexes.size();
6604
6605 Indexes.push_back(Index);
6606 } while (EatIfPresent(lltok::comma));
6607
6608 if (ParseToken(lltok::rbrace, "expected '}' here"))
6609 return true;
6610
6611 if (Indexes.size() < 2)
6612 return Error(Loc, "expected >= 2 uselistorder indexes");
6613 if (Offset != 0 || Max >= Indexes.size())
6614 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6615 if (IsOrdered)
6616 return Error(Loc, "expected uselistorder indexes to change the order");
6617
6618 return false;
6619}
6620
6621/// ParseUseListOrder
6622/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6623bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6624 SMLoc Loc = Lex.getLoc();
6625 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6626 return true;
6627
6628 Value *V;
6629 SmallVector<unsigned, 16> Indexes;
6630 if (ParseTypeAndValue(V, PFS) ||
6631 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6632 ParseUseListOrderIndexes(Indexes))
6633 return true;
6634
6635 return sortUseListOrder(V, Indexes, Loc);
6636}
6637
6638/// ParseUseListOrderBB
6639/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6640bool LLParser::ParseUseListOrderBB() {
6641 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6642 SMLoc Loc = Lex.getLoc();
6643 Lex.Lex();
6644
6645 ValID Fn, Label;
6646 SmallVector<unsigned, 16> Indexes;
6647 if (ParseValID(Fn) ||
6648 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6649 ParseValID(Label) ||
6650 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6651 ParseUseListOrderIndexes(Indexes))
6652 return true;
6653
6654 // Check the function.
6655 GlobalValue *GV;
6656 if (Fn.Kind == ValID::t_GlobalName)
6657 GV = M->getNamedValue(Fn.StrVal);
6658 else if (Fn.Kind == ValID::t_GlobalID)
6659 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6660 else
6661 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6662 if (!GV)
6663 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6664 auto *F = dyn_cast<Function>(GV);
6665 if (!F)
6666 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6667 if (F->isDeclaration())
6668 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6669
6670 // Check the basic block.
6671 if (Label.Kind == ValID::t_LocalID)
6672 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6673 if (Label.Kind != ValID::t_LocalName)
6674 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006675 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006676 if (!V)
6677 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6678 if (!isa<BasicBlock>(V))
6679 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6680
6681 return sortUseListOrder(V, Indexes, Loc);
6682}