blob: ab315dd2c7f5bb022bfc1d7067718ab416836400 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000019#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000044#include "llvm/Support/Dwarf.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();
134 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136 AS.getFnAttributes());
137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
Reid Klecknerb5180542017-03-21 16:57:19 +0000147 AS = AS.addAttributes(
148 Context, AttributeList::FunctionIndex,
149 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 Fn->setAttributes(AS);
151 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000152 AttributeList AS = CI->getAttributes();
153 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
154 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
Bill Wendlingb32b0412013-02-08 06:32:06 +0000155 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000156 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000157 AS = AS.addAttributes(
158 Context, AttributeList::FunctionIndex,
159 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000160 CI->setAttributes(AS);
161 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000162 AttributeList AS = II->getAttributes();
163 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeList::FunctionIndex);
164 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex,
Bill Wendlingb32b0412013-02-08 06:32:06 +0000165 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000166 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000167 AS = AS.addAttributes(
168 Context, AttributeList::FunctionIndex,
169 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000170 II->setAttributes(AS);
171 } else {
172 llvm_unreachable("invalid object with forward attribute group reference");
173 }
174 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000176 // If there are entries in ForwardRefBlockAddresses at this point, the
177 // function was never defined.
178 if (!ForwardRefBlockAddresses.empty())
179 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
180 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000181
David Majnemer19b51052015-02-11 07:43:56 +0000182 for (const auto &NT : NumberedTypes)
183 if (NT.second.second.isValid())
184 return Error(NT.second.second,
185 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186
187 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
188 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
189 if (I->second.second.isValid())
190 return Error(I->second.second,
191 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000192
David Majnemerdad0a642014-06-27 18:19:56 +0000193 if (!ForwardRefComdats.empty())
194 return Error(ForwardRefComdats.begin()->second,
195 "use of undefined comdat '$" +
196 ForwardRefComdats.begin()->first + "'");
197
Chris Lattnerac161bf2009-01-02 07:01:27 +0000198 if (!ForwardRefVals.empty())
199 return Error(ForwardRefVals.begin()->second.second,
200 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 if (!ForwardRefValIDs.empty())
204 return Error(ForwardRefValIDs.begin()->second.second,
205 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000206 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000207
Devang Pateld2541152009-07-08 19:23:54 +0000208 if (!ForwardRefMDNodes.empty())
209 return Error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000211 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000212
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000213 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000214 for (auto &N : NumberedMetadata) {
215 if (N.second && !N.second->isResolved())
216 N.second->resolveCycles();
217 }
Devang Pateld2541152009-07-08 19:23:54 +0000218
Mehdi Aminie4709272016-09-14 22:29:59 +0000219 for (auto *Inst : InstsWithTBAATag) {
220 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
221 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
222 auto *UpgradedMD = UpgradeTBAANode(*MD);
223 if (MD != UpgradedMD)
224 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000226
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 // Look for intrinsic functions and CallInst that need to be upgraded
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000229 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000230
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000231 // Some types could be renamed during loading if several modules are
232 // loaded in the same LLVMContext (LTO scenario). In this case we should
233 // remangle intrinsics names as well.
234 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
235 Function *F = &*FI++;
236 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
237 F->replaceAllUsesWith(Remangled.getValue());
238 F->eraseFromParent();
239 }
240 }
241
Manman Ren8b4306c2013-12-02 21:29:56 +0000242 UpgradeDebugInfo(*M);
243
Manman Renb5d7ff42016-05-25 23:14:48 +0000244 UpgradeModuleFlags(*M);
245
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) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000486/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000488/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000489/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000491bool LLParser::ParseUnnamedGlobal() {
492 unsigned VarID = NumberedVals.size();
493 std::string Name;
494 LocTy NameLoc = Lex.getLoc();
495
496 // Handle the GlobalID form.
497 if (Lex.getKind() == lltok::GlobalID) {
498 if (Lex.getUIntVal() != VarID)
499 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000500 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000501 Lex.Lex(); // eat GlobalID;
502
503 if (ParseToken(lltok::equal, "expected '=' after name"))
504 return true;
505 }
506
507 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000508 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000509 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000510 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000511 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000512 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000513 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000514
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000515 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000517 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000518
519 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
520 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000521}
522
Chris Lattnerac161bf2009-01-02 07:01:27 +0000523/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000524/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000525/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
526/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000527bool LLParser::ParseNamedGlobal() {
528 assert(Lex.getKind() == lltok::GlobalVar);
529 LocTy NameLoc = Lex.getLoc();
530 std::string Name = Lex.getStrVal();
531 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000532
Chris Lattnerac161bf2009-01-02 07:01:27 +0000533 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000534 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000535 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000536 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000537 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000538 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000539 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000540 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000541
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000542 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000543 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000544 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000545
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000546 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
547 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000548}
549
David Majnemerdad0a642014-06-27 18:19:56 +0000550bool LLParser::parseComdat() {
551 assert(Lex.getKind() == lltok::ComdatVar);
552 std::string Name = Lex.getStrVal();
553 LocTy NameLoc = Lex.getLoc();
554 Lex.Lex();
555
556 if (ParseToken(lltok::equal, "expected '=' here"))
557 return true;
558
559 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
560 return TokError("expected comdat type");
561
562 Comdat::SelectionKind SK;
563 switch (Lex.getKind()) {
564 default:
565 return TokError("unknown selection kind");
566 case lltok::kw_any:
567 SK = Comdat::Any;
568 break;
569 case lltok::kw_exactmatch:
570 SK = Comdat::ExactMatch;
571 break;
572 case lltok::kw_largest:
573 SK = Comdat::Largest;
574 break;
575 case lltok::kw_noduplicates:
576 SK = Comdat::NoDuplicates;
577 break;
578 case lltok::kw_samesize:
579 SK = Comdat::SameSize;
580 break;
581 }
582 Lex.Lex();
583
584 // See if the comdat was forward referenced, if so, use the comdat.
585 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
586 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
587 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
588 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
589
590 Comdat *C;
591 if (I != ComdatSymTab.end())
592 C = &I->second;
593 else
594 C = M->getOrInsertComdat(Name);
595 C->setSelectionKind(SK);
596
597 return false;
598}
599
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600// MDString:
601// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000602bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 std::string Str;
604 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000605 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606 return false;
607}
608
609// MDNode:
610// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000611bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000612 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000613 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000614 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000615 if (ParseUInt32(MID))
616 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000617
Chris Lattner8eff0152010-04-01 05:14:45 +0000618 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000619 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000620 Result = NumberedMetadata[MID];
621 return false;
622 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000623
Chris Lattner8eff0152010-04-01 05:14:45 +0000624 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000625 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000626 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000627
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000628 Result = FwdRef.first.get();
629 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000630 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000631}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000632
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000633/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000634/// !foo = !{ !1, !2 }
635bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000636 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000637 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000638 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000639
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000640 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000641 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000642 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000643 return true;
644
Dan Gohman2637cc12010-07-21 23:38:33 +0000645 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (Lex.getKind() != lltok::rbrace)
647 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000648 if (ParseToken(lltok::exclaim, "Expected '!' here"))
649 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000650
Craig Topper2617dcc2014-04-15 06:32:26 +0000651 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000652 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000653 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000654 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000655
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000656 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000657}
658
Devang Patel39e64d42009-07-01 19:21:12 +0000659/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000661bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000662 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000663 Lex.Lex();
664 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000665
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000667 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000668 ParseToken(lltok::equal, "expected '=' here"))
669 return true;
670
671 // Detect common error, from old metadata syntax.
672 if (Lex.getKind() == lltok::Type)
673 return TokError("unexpected type in metadata definition");
674
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000675 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000676 if (Lex.getKind() == lltok::MetadataVar) {
677 if (ParseSpecializedMDNode(Init, IsDistinct))
678 return true;
679 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
680 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000681 return true;
682
Chris Lattnerfc58af22009-12-30 04:51:58 +0000683 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000684 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000685 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000686 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000687 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000688
Chris Lattnerfc58af22009-12-30 04:51:58 +0000689 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
690 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000691 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000692 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000693 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000694 }
695
Devang Patel39e64d42009-07-01 19:21:12 +0000696 return false;
697}
698
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000699static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
700 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
701 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
702}
703
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000704/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000705/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
706/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000707/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000708///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000709/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000710/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000711///
Eric Christopher536f0a92015-05-28 23:07:39 +0000712/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000713///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000714bool LLParser::parseIndirectSymbol(
715 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
716 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
717 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000718 bool IsAlias;
719 if (Lex.getKind() == lltok::kw_alias)
720 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000721 else if (Lex.getKind() == lltok::kw_ifunc)
722 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000723 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000724 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726
Rafael Espindola78527052013-10-06 15:10:43 +0000727 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
728
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000729 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000730 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000731
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000732 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000733 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000734 "symbol with local linkage must have default visibility");
735
David Blaikie2f408302015-09-11 03:22:04 +0000736 Type *Ty;
737 LocTy ExplicitTypeLoc = Lex.getLoc();
738 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000739 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000740 return true;
741
Rafael Espindola64c1e182014-06-03 02:41:57 +0000742 Constant *Aliasee;
743 LocTy AliaseeLoc = Lex.getLoc();
744 if (Lex.getKind() != lltok::kw_bitcast &&
745 Lex.getKind() != lltok::kw_getelementptr &&
746 Lex.getKind() != lltok::kw_addrspacecast &&
747 Lex.getKind() != lltok::kw_inttoptr) {
748 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000749 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000750 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000751 // The bitcast dest type is not present, it is implied by the dest type.
752 ValID ID;
753 if (ParseValID(ID))
754 return true;
755 if (ID.Kind != ValID::t_Constant)
756 return Error(AliaseeLoc, "invalid aliasee");
757 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
Rafael Espindola64c1e182014-06-03 02:41:57 +0000760 Type *AliaseeType = Aliasee->getType();
761 auto *PTy = dyn_cast<PointerType>(AliaseeType);
762 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000763 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000764 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000766 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000767 return Error(
768 ExplicitTypeLoc,
769 "explicit pointee type doesn't match operand's pointee type");
770
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000771 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
772 return Error(
773 ExplicitTypeLoc,
774 "explicit pointee type should be a function type");
775
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000776 GlobalValue *GVal = nullptr;
777
778 // See if the alias was forward referenced, if so, prepare to replace the
779 // forward reference.
780 if (!Name.empty()) {
781 GVal = M->getNamedValue(Name);
782 if (GVal) {
783 if (!ForwardRefVals.erase(Name))
784 return Error(NameLoc, "redefinition of global '@" + Name + "'");
785 }
786 } else {
787 auto I = ForwardRefValIDs.find(NumberedVals.size());
788 if (I != ForwardRefValIDs.end()) {
789 GVal = I->second.first;
790 ForwardRefValIDs.erase(I);
791 }
792 }
793
Chris Lattnerac161bf2009-01-02 07:01:27 +0000794 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000795 std::unique_ptr<GlobalIndirectSymbol> GA;
796 if (IsAlias)
797 GA.reset(GlobalAlias::create(Ty, AddrSpace,
798 (GlobalValue::LinkageTypes)Linkage, Name,
799 Aliasee, /*Parent*/ nullptr));
800 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000801 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
802 (GlobalValue::LinkageTypes)Linkage, Name,
803 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000804 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000806 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000807 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Rafael Espindola54fc2982015-06-17 17:53:31 +0000809 if (Name.empty())
810 NumberedVals.push_back(GA.get());
811
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000812 if (GVal) {
813 // Verify that types agree.
814 if (GVal->getType() != GA->getType())
815 return Error(
816 ExplicitTypeLoc,
817 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerac161bf2009-01-02 07:01:27 +0000819 // If they agree, just RAUW the old value with the alias and remove the
820 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000821 GVal->replaceAllUsesWith(GA.get());
822 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattnerac161bf2009-01-02 07:01:27 +0000825 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000826 if (IsAlias)
827 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
828 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000829 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000830 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Rafael Espindolaaa273822014-05-09 21:49:17 +0000832 // The module owns this now
833 GA.release();
834
Chris Lattnerac161bf2009-01-02 07:01:27 +0000835 return false;
836}
837
838/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000839/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000840/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000841/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000842/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000843/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000844/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845///
Eric Christopher536f0a92015-05-28 23:07:39 +0000846/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000847/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848///
849bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
850 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000851 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000852 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000853 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000854 if (!isValidVisibilityForLinkage(Visibility, Linkage))
855 return Error(NameLoc,
856 "symbol with local linkage must have default visibility");
857
Chris Lattnerac161bf2009-01-02 07:01:27 +0000858 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000859 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000860 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000862
Craig Topper2617dcc2014-04-15 06:32:26 +0000863 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000864 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000865 ParseOptionalToken(lltok::kw_externally_initialized,
866 IsExternallyInitialized,
867 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 ParseGlobalType(IsConstant) ||
869 ParseType(Ty, TyLoc))
870 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000871
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872 // If the linkage is specified and is external, then no initializer is
873 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000874 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000875 if (!HasLinkage ||
876 !GlobalValue::isValidDeclarationLinkage(
877 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000878 if (ParseGlobalValue(Ty, Init))
879 return true;
880 }
881
David Majnemer49b3d9b2015-02-16 08:41:08 +0000882 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000883 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000884
David Majnemer598bd052014-12-09 05:56:09 +0000885 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000886
887 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000888 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000889 GVal = M->getNamedValue(Name);
890 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000891 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000892 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000893 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000894 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000895 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000896 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000897 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000898 ForwardRefValIDs.erase(I);
899 }
900 }
901
David Majnemer598bd052014-12-09 05:56:09 +0000902 GlobalVariable *GV;
903 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000904 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
905 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000906 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000907 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000908 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000909 return Error(TyLoc,
910 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000911
David Majnemer598bd052014-12-09 05:56:09 +0000912 GV = cast<GlobalVariable>(GVal);
913
Chris Lattnerac161bf2009-01-02 07:01:27 +0000914 // Move the forward-reference to the correct spot in the module.
915 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
916 }
917
918 if (Name.empty())
919 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Chris Lattnerac161bf2009-01-02 07:01:27 +0000921 // Set the parsed properties on the global.
922 if (Init)
923 GV->setInitializer(Init);
924 GV->setConstant(IsConstant);
925 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
926 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000927 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000928 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000929 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000930 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000931
Chris Lattnerac161bf2009-01-02 07:01:27 +0000932 // Parse attributes on the global.
933 while (Lex.getKind() == lltok::comma) {
934 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000935
Chris Lattnerac161bf2009-01-02 07:01:27 +0000936 if (Lex.getKind() == lltok::kw_section) {
937 Lex.Lex();
938 GV->setSection(Lex.getStrVal());
939 if (ParseToken(lltok::StringConstant, "expected global section string"))
940 return true;
941 } else if (Lex.getKind() == lltok::kw_align) {
942 unsigned Alignment;
943 if (ParseOptionalAlignment(Alignment)) return true;
944 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000945 } else if (Lex.getKind() == lltok::MetadataVar) {
946 if (ParseGlobalObjectMetadataAttachment(*GV))
947 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000948 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000949 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000950 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000951 return true;
952 if (C)
953 GV->setComdat(C);
954 else
955 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000956 }
957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000958
Chris Lattnerac161bf2009-01-02 07:01:27 +0000959 return false;
960}
961
Bill Wendling63b88192013-02-06 06:52:58 +0000962/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000963/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000964bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000965 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000966 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000967 Lex.Lex();
968
David Majnemerb39e22b2014-12-09 18:33:57 +0000969 if (Lex.getKind() != lltok::AttrGrpID)
970 return TokError("expected attribute group id");
971
Bill Wendling63b88192013-02-06 06:52:58 +0000972 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000973 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000974 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000975 Lex.Lex();
976
977 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000978 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000979 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000980 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000981 ParseToken(lltok::rbrace, "expected end of attribute group"))
982 return true;
983
Bill Wendlingb32b0412013-02-08 06:32:06 +0000984 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000985 return Error(AttrGrpLoc, "attribute group has no attributes");
986
987 return false;
988}
989
Bill Wendling8b0321d2013-02-08 00:52:31 +0000990/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000991/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000992bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
993 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000994 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000995 bool HaveError = false;
996
997 B.clear();
998
Bill Wendling63b88192013-02-06 06:52:58 +0000999 while (true) {
1000 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001001 if (Token == lltok::kw_builtin)
1002 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001003 switch (Token) {
1004 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001005 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001006 return Error(Lex.getLoc(), "unterminated attribute group");
1007 case lltok::rbrace:
1008 // Finished.
1009 return false;
1010
Bill Wendlingb32b0412013-02-08 06:32:06 +00001011 case lltok::AttrGrpID: {
1012 // Allow a function to reference an attribute group:
1013 //
1014 // define void @foo() #1 { ... }
1015 if (inAttrGrp)
1016 HaveError |=
1017 Error(Lex.getLoc(),
1018 "cannot have an attribute group reference in an attribute group");
1019
1020 unsigned AttrGrpNum = Lex.getUIntVal();
1021 if (inAttrGrp) break;
1022
1023 // Save the reference to the attribute group. We'll fill it in later.
1024 FwdRefAttrGrps.push_back(AttrGrpNum);
1025 break;
1026 }
Bill Wendling63b88192013-02-06 06:52:58 +00001027 // Target-dependent attributes:
1028 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001029 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001030 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001031 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001032 }
1033
1034 // Target-independent attributes:
1035 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001036 // As a hack, we allow function alignment to be initially parsed as an
1037 // attribute on a function declaration/definition or added to an attribute
1038 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001039 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001040 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001041 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001042 if (ParseToken(lltok::equal, "expected '=' here") ||
1043 ParseUInt32(Alignment))
1044 return true;
1045 } else {
1046 if (ParseOptionalAlignment(Alignment))
1047 return true;
1048 }
Bill Wendling63b88192013-02-06 06:52:58 +00001049 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001050 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001051 }
1052 case lltok::kw_alignstack: {
1053 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001054 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001055 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001056 if (ParseToken(lltok::equal, "expected '=' here") ||
1057 ParseUInt32(Alignment))
1058 return true;
1059 } else {
1060 if (ParseOptionalStackAlignment(Alignment))
1061 return true;
1062 }
Bill Wendling63b88192013-02-06 06:52:58 +00001063 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001064 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001065 }
George Burgess IV278199f2016-04-12 01:05:35 +00001066 case lltok::kw_allocsize: {
1067 unsigned ElemSizeArg;
1068 Optional<unsigned> NumElemsArg;
1069 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1070 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1071 return true;
1072 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1073 continue;
1074 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001075 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1076 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1077 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1078 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1079 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001080 case lltok::kw_inaccessiblememonly:
1081 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1082 case lltok::kw_inaccessiblemem_or_argmemonly:
1083 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001084 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1085 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1086 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1087 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1088 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1089 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1090 case lltok::kw_noimplicitfloat:
1091 B.addAttribute(Attribute::NoImplicitFloat); break;
1092 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1093 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1094 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1095 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001096 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001097 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1098 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1099 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1100 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1101 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1102 case lltok::kw_returns_twice:
1103 B.addAttribute(Attribute::ReturnsTwice); break;
1104 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1105 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1106 case lltok::kw_sspstrong:
1107 B.addAttribute(Attribute::StackProtectStrong); break;
1108 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1109 case lltok::kw_sanitize_address:
1110 B.addAttribute(Attribute::SanitizeAddress); break;
1111 case lltok::kw_sanitize_thread:
1112 B.addAttribute(Attribute::SanitizeThread); break;
1113 case lltok::kw_sanitize_memory:
1114 B.addAttribute(Attribute::SanitizeMemory); break;
1115 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001116 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001117
1118 // Error handling.
1119 case lltok::kw_inreg:
1120 case lltok::kw_signext:
1121 case lltok::kw_zeroext:
1122 HaveError |=
1123 Error(Lex.getLoc(),
1124 "invalid use of attribute on a function");
1125 break;
1126 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001127 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001128 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001129 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001130 case lltok::kw_nest:
1131 case lltok::kw_noalias:
1132 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001133 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001134 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001135 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001136 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001137 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001138 HaveError |=
1139 Error(Lex.getLoc(),
1140 "invalid use of parameter-only attribute on a function");
1141 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001142 }
1143
1144 Lex.Lex();
1145 }
1146}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001147
1148//===----------------------------------------------------------------------===//
1149// GlobalValue Reference/Resolution Routines.
1150//===----------------------------------------------------------------------===//
1151
Karl Schimpf77729782015-09-03 18:06:44 +00001152static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1153 const std::string &Name) {
1154 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1155 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1156 else
1157 return new GlobalVariable(*M, PTy->getElementType(), false,
1158 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1159 nullptr, GlobalVariable::NotThreadLocal,
1160 PTy->getAddressSpace());
1161}
1162
Chris Lattnerac161bf2009-01-02 07:01:27 +00001163/// GetGlobalVal - Get a value with the specified name or ID, creating a
1164/// forward reference record if needed. This can return null if the value
1165/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001166GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001168 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001169 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001171 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattnerac161bf2009-01-02 07:01:27 +00001174 // Look this name up in the normal function symbol table.
1175 GlobalValue *Val =
1176 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001177
Chris Lattnerac161bf2009-01-02 07:01:27 +00001178 // If this is a forward reference for the value, see if we already created a
1179 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001180 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001181 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001182 if (I != ForwardRefVals.end())
1183 Val = I->second.first;
1184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001185
Chris Lattnerac161bf2009-01-02 07:01:27 +00001186 // If we have the value in the symbol table or fwd-ref table, return it.
1187 if (Val) {
1188 if (Val->getType() == Ty) return Val;
1189 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001190 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001191 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001193
Chris Lattnerac161bf2009-01-02 07:01:27 +00001194 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001195 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001196 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1197 return FwdVal;
1198}
1199
Chris Lattner229907c2011-07-18 04:54:35 +00001200GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1201 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001202 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001203 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001204 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001206
Craig Topper2617dcc2014-04-15 06:32:26 +00001207 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001208
Chris Lattnerac161bf2009-01-02 07:01:27 +00001209 // If this is a forward reference for the value, see if we already created a
1210 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001211 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001212 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001213 if (I != ForwardRefValIDs.end())
1214 Val = I->second.first;
1215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001216
Chris Lattnerac161bf2009-01-02 07:01:27 +00001217 // If we have the value in the symbol table or fwd-ref table, return it.
1218 if (Val) {
1219 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001220 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001221 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001222 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001226 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001227 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1228 return FwdVal;
1229}
1230
Chris Lattnerac161bf2009-01-02 07:01:27 +00001231//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001232// Comdat Reference/Resolution Routines.
1233//===----------------------------------------------------------------------===//
1234
1235Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1236 // Look this name up in the comdat symbol table.
1237 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1238 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1239 if (I != ComdatSymTab.end())
1240 return &I->second;
1241
1242 // Otherwise, create a new forward reference for this value and remember it.
1243 Comdat *C = M->getOrInsertComdat(Name);
1244 ForwardRefComdats[Name] = Loc;
1245 return C;
1246}
1247
David Majnemerdad0a642014-06-27 18:19:56 +00001248//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001249// Helper Routines.
1250//===----------------------------------------------------------------------===//
1251
1252/// ParseToken - If the current token has the specified kind, eat it and return
1253/// success. Otherwise, emit the specified error and return failure.
1254bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1255 if (Lex.getKind() != T)
1256 return TokError(ErrMsg);
1257 Lex.Lex();
1258 return false;
1259}
1260
Chris Lattner3822f632009-01-02 08:05:26 +00001261/// ParseStringConstant
1262/// ::= StringConstant
1263bool LLParser::ParseStringConstant(std::string &Result) {
1264 if (Lex.getKind() != lltok::StringConstant)
1265 return TokError("expected string constant");
1266 Result = Lex.getStrVal();
1267 Lex.Lex();
1268 return false;
1269}
1270
1271/// ParseUInt32
1272/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001273bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1275 return TokError("expected integer");
1276 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1277 if (Val64 != unsigned(Val64))
1278 return TokError("expected 32-bit integer (too large)");
1279 Val = Val64;
1280 Lex.Lex();
1281 return false;
1282}
1283
Hal Finkelb0407ba2014-07-18 15:51:28 +00001284/// ParseUInt64
1285/// ::= uint64
1286bool LLParser::ParseUInt64(uint64_t &Val) {
1287 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1288 return TokError("expected integer");
1289 Val = Lex.getAPSIntVal().getLimitedValue();
1290 Lex.Lex();
1291 return false;
1292}
1293
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001294/// ParseTLSModel
1295/// := 'localdynamic'
1296/// := 'initialexec'
1297/// := 'localexec'
1298bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1299 switch (Lex.getKind()) {
1300 default:
1301 return TokError("expected localdynamic, initialexec or localexec");
1302 case lltok::kw_localdynamic:
1303 TLM = GlobalVariable::LocalDynamicTLSModel;
1304 break;
1305 case lltok::kw_initialexec:
1306 TLM = GlobalVariable::InitialExecTLSModel;
1307 break;
1308 case lltok::kw_localexec:
1309 TLM = GlobalVariable::LocalExecTLSModel;
1310 break;
1311 }
1312
1313 Lex.Lex();
1314 return false;
1315}
1316
1317/// ParseOptionalThreadLocal
1318/// := /*empty*/
1319/// := 'thread_local'
1320/// := 'thread_local' '(' tlsmodel ')'
1321bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1322 TLM = GlobalVariable::NotThreadLocal;
1323 if (!EatIfPresent(lltok::kw_thread_local))
1324 return false;
1325
1326 TLM = GlobalVariable::GeneralDynamicTLSModel;
1327 if (Lex.getKind() == lltok::lparen) {
1328 Lex.Lex();
1329 return ParseTLSModel(TLM) ||
1330 ParseToken(lltok::rparen, "expected ')' after thread local model");
1331 }
1332 return false;
1333}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001334
1335/// ParseOptionalAddrSpace
1336/// := /*empty*/
1337/// := 'addrspace' '(' uint32 ')'
1338bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1339 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001340 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001341 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001342 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001343 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001344 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001345}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001346
Artur Pilipenko17376c42015-08-03 14:31:49 +00001347/// ParseStringAttribute
1348/// := StringConstant
1349/// := StringConstant '=' StringConstant
1350bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1351 std::string Attr = Lex.getStrVal();
1352 Lex.Lex();
1353 std::string Val;
1354 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1355 return true;
1356 B.addAttribute(Attr, Val);
1357 return false;
1358}
1359
Bill Wendling34c2eb22012-12-04 23:40:58 +00001360/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1361bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1362 bool HaveError = false;
1363
1364 B.clear();
1365
Eugene Zelenko1804a772016-08-25 00:45:04 +00001366 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001367 lltok::Kind Token = Lex.getKind();
1368 switch (Token) {
1369 default: // End of attributes.
1370 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001371 case lltok::StringConstant: {
1372 if (ParseStringAttribute(B))
1373 return true;
1374 continue;
1375 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 case lltok::kw_align: {
1377 unsigned Alignment;
1378 if (ParseOptionalAlignment(Alignment))
1379 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001380 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001381 continue;
1382 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001383 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001384 case lltok::kw_dereferenceable: {
1385 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001386 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001387 return true;
1388 B.addDereferenceableAttr(Bytes);
1389 continue;
1390 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001391 case lltok::kw_dereferenceable_or_null: {
1392 uint64_t Bytes;
1393 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1394 return true;
1395 B.addDereferenceableOrNullAttr(Bytes);
1396 continue;
1397 }
Reid Klecknera534a382013-12-19 02:14:12 +00001398 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001399 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1400 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1401 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1402 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001403 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001404 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1405 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001406 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001407 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1408 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001409 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001410 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001411 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001412 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001413
Stephen Lin7577ed52013-04-20 13:16:13 +00001414 case lltok::kw_alignstack:
1415 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001416 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001417 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001418 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001419 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001420 case lltok::kw_minsize:
1421 case lltok::kw_naked:
1422 case lltok::kw_nobuiltin:
1423 case lltok::kw_noduplicate:
1424 case lltok::kw_noimplicitfloat:
1425 case lltok::kw_noinline:
1426 case lltok::kw_nonlazybind:
1427 case lltok::kw_noredzone:
1428 case lltok::kw_noreturn:
1429 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001430 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001431 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001432 case lltok::kw_returns_twice:
1433 case lltok::kw_sanitize_address:
1434 case lltok::kw_sanitize_memory:
1435 case lltok::kw_sanitize_thread:
1436 case lltok::kw_ssp:
1437 case lltok::kw_sspreq:
1438 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001439 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001440 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001441 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1442 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001443 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001444
Bill Wendling34c2eb22012-12-04 23:40:58 +00001445 Lex.Lex();
1446 }
1447}
1448
1449/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1450bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1451 bool HaveError = false;
1452
1453 B.clear();
1454
Eugene Zelenko1804a772016-08-25 00:45:04 +00001455 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001456 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001457 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001458 default: // End of attributes.
1459 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001460 case lltok::StringConstant: {
1461 if (ParseStringAttribute(B))
1462 return true;
1463 continue;
1464 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001465 case lltok::kw_dereferenceable: {
1466 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001467 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001468 return true;
1469 B.addDereferenceableAttr(Bytes);
1470 continue;
1471 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001472 case lltok::kw_dereferenceable_or_null: {
1473 uint64_t Bytes;
1474 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1475 return true;
1476 B.addDereferenceableOrNullAttr(Bytes);
1477 continue;
1478 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001479 case lltok::kw_align: {
1480 unsigned Alignment;
1481 if (ParseOptionalAlignment(Alignment))
1482 return true;
1483 B.addAlignmentAttr(Alignment);
1484 continue;
1485 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001486 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1487 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001488 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001489 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1490 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001491
Bill Wendling34c2eb22012-12-04 23:40:58 +00001492 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001493 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001494 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001495 case lltok::kw_nest:
1496 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001497 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001498 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001499 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001500 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001501 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001502 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001503
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001504 case lltok::kw_alignstack:
1505 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001506 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001507 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001508 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001509 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001510 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001511 case lltok::kw_minsize:
1512 case lltok::kw_naked:
1513 case lltok::kw_nobuiltin:
1514 case lltok::kw_noduplicate:
1515 case lltok::kw_noimplicitfloat:
1516 case lltok::kw_noinline:
1517 case lltok::kw_nonlazybind:
1518 case lltok::kw_noredzone:
1519 case lltok::kw_noreturn:
1520 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001521 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001522 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001523 case lltok::kw_returns_twice:
1524 case lltok::kw_sanitize_address:
1525 case lltok::kw_sanitize_memory:
1526 case lltok::kw_sanitize_thread:
1527 case lltok::kw_ssp:
1528 case lltok::kw_sspreq:
1529 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001530 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001531 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001532 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001533 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001534
1535 case lltok::kw_readnone:
1536 case lltok::kw_readonly:
1537 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001538 }
1539
Chris Lattnerac161bf2009-01-02 07:01:27 +00001540 Lex.Lex();
1541 }
1542}
1543
Rafael Espindolac6269912016-05-10 17:16:45 +00001544static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1545 HasLinkage = true;
1546 switch (Kind) {
1547 default:
1548 HasLinkage = false;
1549 return GlobalValue::ExternalLinkage;
1550 case lltok::kw_private:
1551 return GlobalValue::PrivateLinkage;
1552 case lltok::kw_internal:
1553 return GlobalValue::InternalLinkage;
1554 case lltok::kw_weak:
1555 return GlobalValue::WeakAnyLinkage;
1556 case lltok::kw_weak_odr:
1557 return GlobalValue::WeakODRLinkage;
1558 case lltok::kw_linkonce:
1559 return GlobalValue::LinkOnceAnyLinkage;
1560 case lltok::kw_linkonce_odr:
1561 return GlobalValue::LinkOnceODRLinkage;
1562 case lltok::kw_available_externally:
1563 return GlobalValue::AvailableExternallyLinkage;
1564 case lltok::kw_appending:
1565 return GlobalValue::AppendingLinkage;
1566 case lltok::kw_common:
1567 return GlobalValue::CommonLinkage;
1568 case lltok::kw_extern_weak:
1569 return GlobalValue::ExternalWeakLinkage;
1570 case lltok::kw_external:
1571 return GlobalValue::ExternalLinkage;
1572 }
1573}
1574
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575/// ParseOptionalLinkage
1576/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001577/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578/// ::= 'internal'
1579/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001580/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001582/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001583/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001585/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001586/// ::= 'extern_weak'
1587/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001588bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1589 unsigned &Visibility,
1590 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001591 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1592 if (HasLinkage)
1593 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001594 ParseOptionalVisibility(Visibility);
1595 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001596 return false;
1597}
1598
1599/// ParseOptionalVisibility
1600/// ::= /*empty*/
1601/// ::= 'default'
1602/// ::= 'hidden'
1603/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001604///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001605void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001606 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001607 default:
1608 Res = GlobalValue::DefaultVisibility;
1609 return;
1610 case lltok::kw_default:
1611 Res = GlobalValue::DefaultVisibility;
1612 break;
1613 case lltok::kw_hidden:
1614 Res = GlobalValue::HiddenVisibility;
1615 break;
1616 case lltok::kw_protected:
1617 Res = GlobalValue::ProtectedVisibility;
1618 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001619 }
1620 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001621}
1622
Nico Rieck7157bb72014-01-14 15:22:47 +00001623/// ParseOptionalDLLStorageClass
1624/// ::= /*empty*/
1625/// ::= 'dllimport'
1626/// ::= 'dllexport'
1627///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001628void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001629 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001630 default:
1631 Res = GlobalValue::DefaultStorageClass;
1632 return;
1633 case lltok::kw_dllimport:
1634 Res = GlobalValue::DLLImportStorageClass;
1635 break;
1636 case lltok::kw_dllexport:
1637 Res = GlobalValue::DLLExportStorageClass;
1638 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001639 }
1640 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001641}
1642
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643/// ParseOptionalCallingConv
1644/// ::= /*empty*/
1645/// ::= 'ccc'
1646/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001647/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001648/// ::= 'coldcc'
1649/// ::= 'x86_stdcallcc'
1650/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001651/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001652/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001653/// ::= 'arm_apcscc'
1654/// ::= 'arm_aapcscc'
1655/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001656/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001657/// ::= 'avr_intrcc'
1658/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001659/// ::= 'ptx_kernel'
1660/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001661/// ::= 'spir_func'
1662/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001663/// ::= 'x86_64_sysvcc'
1664/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001665/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001666/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001667/// ::= 'preserve_mostcc'
1668/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001669/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001670/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001671/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001672/// ::= 'hhvmcc'
1673/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001674/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001675/// ::= 'amdgpu_vs'
1676/// ::= 'amdgpu_tcs'
1677/// ::= 'amdgpu_tes'
1678/// ::= 'amdgpu_gs'
1679/// ::= 'amdgpu_ps'
1680/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001681/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001683///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001684bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685 switch (Lex.getKind()) {
1686 default: CC = CallingConv::C; return false;
1687 case lltok::kw_ccc: CC = CallingConv::C; break;
1688 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1689 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1690 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1691 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001692 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001693 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001694 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001695 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1696 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1697 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001698 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001699 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1700 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001701 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1702 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001703 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1704 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001705 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001706 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1707 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001708 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001709 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001710 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1711 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001712 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001713 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001714 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001715 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1716 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001717 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001718 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1719 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1720 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1721 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001722 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001723 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001724 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001725 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001726 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001728
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729 Lex.Lex();
1730 return false;
1731}
1732
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001733/// ParseMetadataAttachment
1734/// ::= !dbg !42
1735bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1737
1738 std::string Name = Lex.getStrVal();
1739 Kind = M->getMDKindID(Name);
1740 Lex.Lex();
1741
1742 return ParseMDNode(MD);
1743}
1744
Chris Lattner5c427632009-12-30 05:31:19 +00001745/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001746/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001747bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001748 do {
1749 if (Lex.getKind() != lltok::MetadataVar)
1750 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001751
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001752 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001753 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001754 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001755 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001756
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001757 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001758 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001759 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001760
Chris Lattner596760d2009-12-29 21:25:40 +00001761 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001762 } while (EatIfPresent(lltok::comma));
1763 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001764}
1765
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001766/// ParseGlobalObjectMetadataAttachment
1767/// ::= !dbg !57
1768bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1769 unsigned MDK;
1770 MDNode *N;
1771 if (ParseMetadataAttachment(MDK, N))
1772 return true;
1773
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001774 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001775 return false;
1776}
1777
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001778/// ParseOptionalFunctionMetadata
1779/// ::= (!dbg !57)*
1780bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001781 while (Lex.getKind() == lltok::MetadataVar)
1782 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001783 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001784 return false;
1785}
1786
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787/// ParseOptionalAlignment
1788/// ::= /* empty */
1789/// ::= 'align' 4
1790bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1791 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001792 if (!EatIfPresent(lltok::kw_align))
1793 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001794 LocTy AlignLoc = Lex.getLoc();
1795 if (ParseUInt32(Alignment)) return true;
1796 if (!isPowerOf2_32(Alignment))
1797 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001798 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001799 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001800 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801}
1802
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001803/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001804/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001805/// ::= AttrKind '(' 4 ')'
1806///
1807/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1808bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1809 uint64_t &Bytes) {
1810 assert((AttrKind == lltok::kw_dereferenceable ||
1811 AttrKind == lltok::kw_dereferenceable_or_null) &&
1812 "contract!");
1813
Hal Finkelb0407ba2014-07-18 15:51:28 +00001814 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001815 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001816 return false;
1817 LocTy ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::lparen))
1819 return Error(ParenLoc, "expected '('");
1820 LocTy DerefLoc = Lex.getLoc();
1821 if (ParseUInt64(Bytes)) return true;
1822 ParenLoc = Lex.getLoc();
1823 if (!EatIfPresent(lltok::rparen))
1824 return Error(ParenLoc, "expected ')'");
1825 if (!Bytes)
1826 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1827 return false;
1828}
1829
Chris Lattnerb2f39502009-12-30 05:44:30 +00001830/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001831/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001832/// ::= ',' align 4
1833///
1834/// This returns with AteExtraComma set to true if it ate an excess comma at the
1835/// end.
1836bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1837 bool &AteExtraComma) {
1838 AteExtraComma = false;
1839 while (EatIfPresent(lltok::comma)) {
1840 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001841 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001842 AteExtraComma = true;
1843 return false;
1844 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001845
Chris Lattner95b0ff42010-04-23 00:50:50 +00001846 if (Lex.getKind() != lltok::kw_align)
1847 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001848
Chris Lattner95b0ff42010-04-23 00:50:50 +00001849 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001851
Devang Patelea8a4b92009-09-17 23:04:48 +00001852 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001853}
1854
George Burgess IV278199f2016-04-12 01:05:35 +00001855bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1856 Optional<unsigned> &HowManyArg) {
1857 Lex.Lex();
1858
1859 auto StartParen = Lex.getLoc();
1860 if (!EatIfPresent(lltok::lparen))
1861 return Error(StartParen, "expected '('");
1862
1863 if (ParseUInt32(BaseSizeArg))
1864 return true;
1865
1866 if (EatIfPresent(lltok::comma)) {
1867 auto HowManyAt = Lex.getLoc();
1868 unsigned HowMany;
1869 if (ParseUInt32(HowMany))
1870 return true;
1871 if (HowMany == BaseSizeArg)
1872 return Error(HowManyAt,
1873 "'allocsize' indices can't refer to the same parameter");
1874 HowManyArg = HowMany;
1875 } else
1876 HowManyArg = None;
1877
1878 auto EndParen = Lex.getLoc();
1879 if (!EatIfPresent(lltok::rparen))
1880 return Error(EndParen, "expected ')'");
1881 return false;
1882}
1883
Eli Friedmanfee02c62011-07-25 23:16:38 +00001884/// ParseScopeAndOrdering
1885/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1886/// else: ::=
1887///
1888/// This sets Scope and Ordering to the parsed values.
1889bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1890 AtomicOrdering &Ordering) {
1891 if (!isAtomic)
1892 return false;
1893
1894 Scope = CrossThread;
1895 if (EatIfPresent(lltok::kw_singlethread))
1896 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001897
1898 return ParseOrdering(Ordering);
1899}
1900
1901/// ParseOrdering
1902/// ::= AtomicOrdering
1903///
1904/// This sets Ordering to the parsed value.
1905bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001906 switch (Lex.getKind()) {
1907 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001908 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1909 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1910 // Not specified yet:
1911 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1912 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1913 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1914 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1915 case lltok::kw_seq_cst:
1916 Ordering = AtomicOrdering::SequentiallyConsistent;
1917 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001918 }
1919 Lex.Lex();
1920 return false;
1921}
1922
Charles Davisbe5557e2010-02-12 00:31:15 +00001923/// ParseOptionalStackAlignment
1924/// ::= /* empty */
1925/// ::= 'alignstack' '(' 4 ')'
1926bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1927 Alignment = 0;
1928 if (!EatIfPresent(lltok::kw_alignstack))
1929 return false;
1930 LocTy ParenLoc = Lex.getLoc();
1931 if (!EatIfPresent(lltok::lparen))
1932 return Error(ParenLoc, "expected '('");
1933 LocTy AlignLoc = Lex.getLoc();
1934 if (ParseUInt32(Alignment)) return true;
1935 ParenLoc = Lex.getLoc();
1936 if (!EatIfPresent(lltok::rparen))
1937 return Error(ParenLoc, "expected ')'");
1938 if (!isPowerOf2_32(Alignment))
1939 return Error(AlignLoc, "stack alignment is not a power of two");
1940 return false;
1941}
Devang Patelea8a4b92009-09-17 23:04:48 +00001942
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001943/// ParseIndexList - This parses the index list for an insert/extractvalue
1944/// instruction. This sets AteExtraComma in the case where we eat an extra
1945/// comma at the end of the line and find that it is followed by metadata.
1946/// Clients that don't allow metadata can call the version of this function that
1947/// only takes one argument.
1948///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001949/// ParseIndexList
1950/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001951///
1952bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1953 bool &AteExtraComma) {
1954 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001955
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956 if (Lex.getKind() != lltok::comma)
1957 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattner3822f632009-01-02 08:05:26 +00001959 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001960 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001961 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001962 AteExtraComma = true;
1963 return false;
1964 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001965 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001966 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 Indices.push_back(Idx);
1968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 return false;
1971}
1972
1973//===----------------------------------------------------------------------===//
1974// Type Parsing.
1975//===----------------------------------------------------------------------===//
1976
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001977/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001978bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001979 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001980 switch (Lex.getKind()) {
1981 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001982 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001989 // Type ::= StructType
1990 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 return true;
1992 break;
1993 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001994 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 Lex.Lex(); // eat the lsquare.
1996 if (ParseArrayVectorType(Result, false))
1997 return true;
1998 break;
1999 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002001 Lex.Lex();
2002 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002004 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 } else if (ParseArrayVectorType(Result, true))
2007 return true;
2008 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009 case lltok::LocalVar: {
2010 // Type ::= %foo
2011 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002012
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002013 // If the type hasn't been defined yet, create a forward definition and
2014 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002015 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002016 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 Lex.Lex();
2021 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002023
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002024 case lltok::LocalVarID: {
2025 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 // If the type hasn't been defined yet, create a forward definition and
2029 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002030 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002031 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002033 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002035 Lex.Lex();
2036 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002037 }
2038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002039
2040 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002041 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002042 switch (Lex.getKind()) {
2043 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044 default:
2045 if (!AllowVoid && Result->isVoidTy())
2046 return Error(TypeLoc, "void type only allowed for function results");
2047 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002050 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002052 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 if (Result->isVoidTy())
2054 return TokError("pointers to void are invalid - use i8* instead");
2055 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002056 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002057 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 Lex.Lex();
2059 break;
2060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002061 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002063 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002064 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002066 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002068 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002069 unsigned AddrSpace;
2070 if (ParseOptionalAddrSpace(AddrSpace) ||
2071 ParseToken(lltok::star, "expected '*' in address space"))
2072 return true;
2073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 break;
2076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002077
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2079 case lltok::lparen:
2080 if (ParseFunctionType(Result))
2081 return true;
2082 break;
2083 }
2084 }
2085}
2086
2087/// ParseParameterList
2088/// ::= '(' ')'
2089/// ::= '(' Arg (',' Arg)* ')'
2090/// Arg
2091/// ::= Type OptionalAttributes Value OptionalAttributes
2092bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002093 PerFunctionState &PFS, bool IsMustTailCall,
2094 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002095 if (ParseToken(lltok::lparen, "expected '(' in call"))
2096 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002097
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002098 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099 while (Lex.getKind() != lltok::rparen) {
2100 // If this isn't the first argument, we need a comma.
2101 if (!ArgList.empty() &&
2102 ParseToken(lltok::comma, "expected ',' in argument list"))
2103 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002104
Reid Kleckner83498642014-08-26 00:33:28 +00002105 // Parse an ellipsis if this is a musttail call in a variadic function.
2106 if (Lex.getKind() == lltok::dotdotdot) {
2107 const char *Msg = "unexpected ellipsis in argument list for ";
2108 if (!IsMustTailCall)
2109 return TokError(Twine(Msg) + "non-musttail call");
2110 if (!InVarArgsFunc)
2111 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2112 Lex.Lex(); // Lex the '...', it is purely for readability.
2113 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2114 }
2115
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 // Parse the argument.
2117 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002118 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002119 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002121 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002122 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002123
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002124 if (ArgTy->isMetadataTy()) {
2125 if (ParseMetadataAsValue(V, PFS))
2126 return true;
2127 } else {
2128 // Otherwise, handle normal operands.
2129 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2130 return true;
2131 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002132 ArgList.push_back(ParamInfo(
2133 ArgLoc, V, AttributeList::get(V->getContext(), AttrIndex++, ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 }
2135
Reid Kleckner83498642014-08-26 00:33:28 +00002136 if (IsMustTailCall && InVarArgsFunc)
2137 return TokError("expected '...' at end of argument list for musttail call "
2138 "in varargs function");
2139
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 Lex.Lex(); // Lex the ')'.
2141 return false;
2142}
2143
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002144/// ParseOptionalOperandBundles
2145/// ::= /*empty*/
2146/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2147///
2148/// OperandBundle
2149/// ::= bundle-tag '(' ')'
2150/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2151///
2152/// bundle-tag ::= String Constant
2153bool LLParser::ParseOptionalOperandBundles(
2154 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2155 LocTy BeginLoc = Lex.getLoc();
2156 if (!EatIfPresent(lltok::lsquare))
2157 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002159 while (Lex.getKind() != lltok::rsquare) {
2160 // If this isn't the first operand bundle, we need a comma.
2161 if (!BundleList.empty() &&
2162 ParseToken(lltok::comma, "expected ',' in input list"))
2163 return true;
2164
2165 std::string Tag;
2166 if (ParseStringConstant(Tag))
2167 return true;
2168
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002169 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2170 return true;
2171
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002172 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002173 while (Lex.getKind() != lltok::rparen) {
2174 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002175 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002176 ParseToken(lltok::comma, "expected ',' in input list"))
2177 return true;
2178
2179 Type *Ty = nullptr;
2180 Value *Input = nullptr;
2181 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2182 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002183 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002184 }
2185
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002186 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2187
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002188 Lex.Lex(); // Lex the ')'.
2189 }
2190
2191 if (BundleList.empty())
2192 return Error(BeginLoc, "operand bundle set must not be empty");
2193
2194 Lex.Lex(); // Lex the ']'.
2195 return false;
2196}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197
Chris Lattner2ed06b42009-01-05 18:34:07 +00002198/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002199/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200/// ::= '(' ArgTypeListI ')'
2201/// ArgTypeListI
2202/// ::= /*empty*/
2203/// ::= '...'
2204/// ::= ArgTypeList ',' '...'
2205/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002206///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002207bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2208 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 isVarArg = false;
2210 assert(Lex.getKind() == lltok::lparen);
2211 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 if (Lex.getKind() == lltok::rparen) {
2214 // empty
2215 } else if (Lex.getKind() == lltok::dotdotdot) {
2216 isVarArg = true;
2217 Lex.Lex();
2218 } else {
2219 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002220 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002221 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002223
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002224 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002225 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattnerfdd87902009-10-05 05:54:46 +00002227 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002228 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattnerdef19492011-06-17 06:36:20 +00002230 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 Name = Lex.getStrVal();
2232 Lex.Lex();
2233 }
Chris Lattner3822f632009-01-02 08:05:26 +00002234
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002235 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002236 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002237
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002238 unsigned AttrIndex = 1;
Reid Klecknerb5180542017-03-21 16:57:19 +00002239 ArgList.emplace_back(TypeLoc, ArgTy, AttributeList::get(ArgTy->getContext(),
2240 AttrIndex++, Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002241 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002242
Chris Lattner3822f632009-01-02 08:05:26 +00002243 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002245 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002247 break;
2248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 // Otherwise must be an argument type.
2251 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002252 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002253
Chris Lattnerfdd87902009-10-05 05:54:46 +00002254 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002255 return Error(TypeLoc, "argument can not have void type");
2256
Chris Lattnerdef19492011-06-17 06:36:20 +00002257 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 Name = Lex.getStrVal();
2259 Lex.Lex();
2260 } else {
2261 Name = "";
2262 }
Chris Lattner3822f632009-01-02 08:05:26 +00002263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002264 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002265 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002267 ArgList.emplace_back(
2268 TypeLoc, ArgTy,
Reid Klecknerb5180542017-03-21 16:57:19 +00002269 AttributeList::get(ArgTy->getContext(), AttrIndex++, Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002270 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 }
2272 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273
Chris Lattner3822f632009-01-02 08:05:26 +00002274 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002276
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277/// ParseFunctionType
2278/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002279bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002280 assert(Lex.getKind() == lltok::lparen);
2281
Chris Lattnerce473c72009-01-05 08:04:33 +00002282 if (!FunctionType::isValidReturnType(Result))
2283 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002287 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 // Reject names on the arguments lists.
2291 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2292 if (!ArgList[i].Name.empty())
2293 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002294 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002295 return Error(ArgList[i].Loc,
2296 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Jay Foadb804a2b2011-07-12 14:06:48 +00002299 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002303 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 return false;
2305}
2306
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2308/// other structs.
2309bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2310 SmallVector<Type*, 8> Elts;
2311 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002312
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002313 Result = StructType::get(Context, Elts, Packed);
2314 return false;
2315}
2316
2317/// ParseStructDefinition - Parse a struct in a 'type' definition.
2318bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2319 std::pair<Type*, LocTy> &Entry,
2320 Type *&ResultTy) {
2321 // If the type was already defined, diagnose the redefinition.
2322 if (Entry.first && !Entry.second.isValid())
2323 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 // If we have opaque, just return without filling in the definition for the
2326 // struct. This counts as a definition as far as the .ll file goes.
2327 if (EatIfPresent(lltok::kw_opaque)) {
2328 // This type is being defined, so clear the location to indicate this.
2329 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002330
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002331 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002332 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002333 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002334 ResultTy = Entry.first;
2335 return false;
2336 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002337
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338 // If the type starts with '<', then it is either a packed struct or a vector.
2339 bool isPacked = EatIfPresent(lltok::less);
2340
2341 // If we don't have a struct, then we have a random type alias, which we
2342 // accept for compatibility with old files. These types are not allowed to be
2343 // forward referenced and not allowed to be recursive.
2344 if (Lex.getKind() != lltok::lbrace) {
2345 if (Entry.first)
2346 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002347
Craig Topper2617dcc2014-04-15 06:32:26 +00002348 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002349 if (isPacked)
2350 return ParseArrayVectorType(ResultTy, true);
2351 return ParseType(ResultTy);
2352 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002354 // This type is being defined, so clear the location to indicate this.
2355 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002358 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002359 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002360
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002361 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002362
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002363 SmallVector<Type*, 8> Body;
2364 if (ParseStructBody(Body) ||
2365 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2366 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002368 STy->setBody(Body, isPacked);
2369 ResultTy = STy;
2370 return false;
2371}
2372
Chris Lattnerac161bf2009-01-02 07:01:27 +00002373/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002374/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002375/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002376/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002378/// ::= '<' '{' Type (',' Type)* '}' '>'
2379bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002380 assert(Lex.getKind() == lltok::lbrace);
2381 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 // Handle the empty struct.
2384 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002385 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002386
Chris Lattnerf880ca22009-03-09 04:49:14 +00002387 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002388 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002389 if (ParseType(Ty)) return true;
2390 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002391
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002392 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002393 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattner3822f632009-01-02 08:05:26 +00002395 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002396 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002397 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002399 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002400 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002401
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002402 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002405 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406}
2407
2408/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2409/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002410/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002411/// ::= '[' APSINTVAL 'x' Types ']'
2412/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002413bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2415 Lex.getAPSIntVal().getBitWidth() > 64)
2416 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 LocTy SizeLoc = Lex.getLoc();
2419 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002420 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattner3822f632009-01-02 08:05:26 +00002422 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2423 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002424
2425 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002426 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002427 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002428
Chris Lattner3822f632009-01-02 08:05:26 +00002429 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2430 "expected end of sequential type"))
2431 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002432
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002434 if (Size == 0)
2435 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 if ((unsigned)Size != Size)
2437 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002438 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002439 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002440 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002441 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002442 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002443 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002444 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 }
2446 return false;
2447}
2448
2449//===----------------------------------------------------------------------===//
2450// Function Semantic Analysis.
2451//===----------------------------------------------------------------------===//
2452
Chris Lattner3432c622009-10-28 03:39:23 +00002453LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2454 int functionNumber)
2455 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456
2457 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002458 for (Argument &A : F.args())
2459 if (!A.hasName())
2460 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461}
2462
2463LLParser::PerFunctionState::~PerFunctionState() {
2464 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
David Blaikie9ebdc692015-09-21 21:07:50 +00002466 for (const auto &P : ForwardRefVals) {
2467 if (isa<BasicBlock>(P.second.first))
2468 continue;
2469 P.second.first->replaceAllUsesWith(
2470 UndefValue::get(P.second.first->getType()));
2471 delete P.second.first;
2472 }
2473
2474 for (const auto &P : ForwardRefValIDs) {
2475 if (isa<BasicBlock>(P.second.first))
2476 continue;
2477 P.second.first->replaceAllUsesWith(
2478 UndefValue::get(P.second.first->getType()));
2479 delete P.second.first;
2480 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481}
2482
Chris Lattner3432c622009-10-28 03:39:23 +00002483bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002484 if (!ForwardRefVals.empty())
2485 return P.Error(ForwardRefVals.begin()->second.second,
2486 "use of undefined value '%" + ForwardRefVals.begin()->first +
2487 "'");
2488 if (!ForwardRefValIDs.empty())
2489 return P.Error(ForwardRefValIDs.begin()->second.second,
2490 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002491 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002492 return false;
2493}
2494
Chris Lattnerac161bf2009-01-02 07:01:27 +00002495/// GetVal - Get a value with the specified name or ID, creating a
2496/// forward reference record if needed. This can return null if the value
2497/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002498Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002499 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002501 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002502
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 // If this is a forward reference for the value, see if we already created a
2504 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002505 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002506 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 if (I != ForwardRefVals.end())
2508 Val = I->second.first;
2509 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 // If we have the value in the symbol table or fwd-ref table, return it.
2512 if (Val) {
2513 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002514 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 P.Error(Loc, "'%" + Name + "' is not a basic block");
2516 else
2517 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002518 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002519 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002523 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002525 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002527
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 // Otherwise, create a new forward reference for this value and remember it.
2529 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002530 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002531 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002532 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002533 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002535
Chris Lattnerac161bf2009-01-02 07:01:27 +00002536 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2537 return FwdVal;
2538}
2539
David Majnemer8a1c45d2015-12-12 05:38:55 +00002540Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002541 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002542 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002543
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 // If this is a forward reference for the value, see if we already created a
2545 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002546 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002547 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 if (I != ForwardRefValIDs.end())
2549 Val = I->second.first;
2550 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 // If we have the value in the symbol table or fwd-ref table, return it.
2553 if (Val) {
2554 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002555 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002556 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002557 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002558 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002559 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002560 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002562
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002563 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002565 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002567
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 // Otherwise, create a new forward reference for this value and remember it.
2569 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002570 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002571 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002572 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002573 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002574 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575
Chris Lattnerac161bf2009-01-02 07:01:27 +00002576 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2577 return FwdVal;
2578}
2579
2580/// SetInstName - After an instruction is parsed and inserted into its
2581/// basic block, this installs its name.
2582bool LLParser::PerFunctionState::SetInstName(int NameID,
2583 const std::string &NameStr,
2584 LocTy NameLoc, Instruction *Inst) {
2585 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002586 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002587 if (NameID != -1 || !NameStr.empty())
2588 return P.Error(NameLoc, "instructions returning void cannot have a name");
2589 return false;
2590 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002591
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 // If this was a numbered instruction, verify that the instruction is the
2593 // expected value and resolve any forward references.
2594 if (NameStr.empty()) {
2595 // If neither a name nor an ID was specified, just use the next ID.
2596 if (NameID == -1)
2597 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002598
Chris Lattnerac161bf2009-01-02 07:01:27 +00002599 if (unsigned(NameID) != NumberedVals.size())
2600 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002601 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002602
David Blaikie9ebdc692015-09-21 21:07:50 +00002603 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002604 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002605 Value *Sentinel = FI->second.first;
2606 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002608 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002609
2610 Sentinel->replaceAllUsesWith(Inst);
2611 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612 ForwardRefValIDs.erase(FI);
2613 }
2614
2615 NumberedVals.push_back(Inst);
2616 return false;
2617 }
2618
2619 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002620 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002622 Value *Sentinel = FI->second.first;
2623 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002624 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002625 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002626
2627 Sentinel->replaceAllUsesWith(Inst);
2628 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002629 ForwardRefVals.erase(FI);
2630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002631
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 // Set the name on the instruction.
2633 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002635 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 NameStr + "'");
2638 return false;
2639}
2640
2641/// GetBB - Get a basic block with the specified name or ID, creating a
2642/// forward reference record if needed.
2643BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2644 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002645 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2646 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002647}
2648
2649BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002650 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2651 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652}
2653
2654/// DefineBB - Define the specified basic block, which is either named or
2655/// unnamed. If there is an error, this returns null otherwise it returns
2656/// the block being defined.
2657BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2658 LocTy Loc) {
2659 BasicBlock *BB;
2660 if (Name.empty())
2661 BB = GetBB(NumberedVals.size(), Loc);
2662 else
2663 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002664 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002665
Chris Lattnerac161bf2009-01-02 07:01:27 +00002666 // Move the block to the end of the function. Forward ref'd blocks are
2667 // inserted wherever they happen to be referenced.
2668 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 // Remove the block from forward ref sets.
2671 if (Name.empty()) {
2672 ForwardRefValIDs.erase(NumberedVals.size());
2673 NumberedVals.push_back(BB);
2674 } else {
2675 // BB forward references are already in the function symbol table.
2676 ForwardRefVals.erase(Name);
2677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002678
Chris Lattnerac161bf2009-01-02 07:01:27 +00002679 return BB;
2680}
2681
2682//===----------------------------------------------------------------------===//
2683// Constants.
2684//===----------------------------------------------------------------------===//
2685
2686/// ParseValID - Parse an abstract value that doesn't necessarily have a
2687/// type implied. For example, if we parse "4" we don't know what integer type
2688/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002689/// sanity. PFS is used to convert function-local operands of metadata (since
2690/// metadata operands are not just parsed here but also converted to values).
2691/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002692bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002693 ID.Loc = Lex.getLoc();
2694 switch (Lex.getKind()) {
2695 default: return TokError("expected value token");
2696 case lltok::GlobalID: // @42
2697 ID.UIntVal = Lex.getUIntVal();
2698 ID.Kind = ValID::t_GlobalID;
2699 break;
2700 case lltok::GlobalVar: // @foo
2701 ID.StrVal = Lex.getStrVal();
2702 ID.Kind = ValID::t_GlobalName;
2703 break;
2704 case lltok::LocalVarID: // %42
2705 ID.UIntVal = Lex.getUIntVal();
2706 ID.Kind = ValID::t_LocalID;
2707 break;
2708 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002709 ID.StrVal = Lex.getStrVal();
2710 ID.Kind = ValID::t_LocalName;
2711 break;
2712 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002713 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002714 ID.Kind = ValID::t_APSInt;
2715 break;
2716 case lltok::APFloat:
2717 ID.APFloatVal = Lex.getAPFloatVal();
2718 ID.Kind = ValID::t_APFloat;
2719 break;
2720 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002721 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 ID.Kind = ValID::t_Constant;
2723 break;
2724 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002725 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 ID.Kind = ValID::t_Constant;
2727 break;
2728 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2729 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2730 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002731 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732
Chris Lattnerac161bf2009-01-02 07:01:27 +00002733 case lltok::lbrace: {
2734 // ValID ::= '{' ConstVector '}'
2735 Lex.Lex();
2736 SmallVector<Constant*, 16> Elts;
2737 if (ParseGlobalValueVector(Elts) ||
2738 ParseToken(lltok::rbrace, "expected end of struct constant"))
2739 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
David Blaikieadbda4b2015-08-03 20:08:41 +00002741 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002742 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002743 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2744 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002745 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 return false;
2747 }
2748 case lltok::less: {
2749 // ValID ::= '<' ConstVector '>' --> Vector.
2750 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2751 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002752 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754 SmallVector<Constant*, 16> Elts;
2755 LocTy FirstEltLoc = Lex.getLoc();
2756 if (ParseGlobalValueVector(Elts) ||
2757 (isPackedStruct &&
2758 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2759 ParseToken(lltok::greater, "expected end of constant"))
2760 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002761
Chris Lattnerac161bf2009-01-02 07:01:27 +00002762 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002763 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2764 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2765 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002766 ID.UIntVal = Elts.size();
2767 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 return false;
2769 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002770
Chris Lattnerac161bf2009-01-02 07:01:27 +00002771 if (Elts.empty())
2772 return Error(ID.Loc, "constant vector must not be empty");
2773
Duncan Sands9dff9be2010-02-15 16:12:20 +00002774 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002775 !Elts[0]->getType()->isFloatingPointTy() &&
2776 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002778 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002779
Chris Lattnerac161bf2009-01-02 07:01:27 +00002780 // Verify that all the vector elements have the same type.
2781 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2782 if (Elts[i]->getType() != Elts[0]->getType())
2783 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002784 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002785 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786
Chris Lattner69229312011-02-15 00:14:00 +00002787 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 ID.Kind = ValID::t_Constant;
2789 return false;
2790 }
2791 case lltok::lsquare: { // Array Constant
2792 Lex.Lex();
2793 SmallVector<Constant*, 16> Elts;
2794 LocTy FirstEltLoc = Lex.getLoc();
2795 if (ParseGlobalValueVector(Elts) ||
2796 ParseToken(lltok::rsquare, "expected end of array constant"))
2797 return true;
2798
2799 // Handle empty element.
2800 if (Elts.empty()) {
2801 // Use undef instead of an array because it's inconvenient to determine
2802 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002803 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 return false;
2805 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002806
Chris Lattnerac161bf2009-01-02 07:01:27 +00002807 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002809 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002810
Owen Anderson4056ca92009-07-29 22:17:13 +00002811 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
Chris Lattnerac161bf2009-01-02 07:01:27 +00002813 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002814 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002815 if (Elts[i]->getType() != Elts[0]->getType())
2816 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002817 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002818 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002820
Jay Foad83be3612011-06-22 09:24:39 +00002821 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 ID.Kind = ValID::t_Constant;
2823 return false;
2824 }
2825 case lltok::kw_c: // c "foo"
2826 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002827 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2828 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2830 ID.Kind = ValID::t_Constant;
2831 return false;
2832
2833 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002834 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2835 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002836 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 Lex.Lex();
2838 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002839 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002840 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002841 ParseStringConstant(ID.StrVal) ||
2842 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002843 ParseToken(lltok::StringConstant, "expected constraint string"))
2844 return true;
2845 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002846 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002847 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 ID.Kind = ValID::t_InlineAsm;
2849 return false;
2850 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002851
Chris Lattner3432c622009-10-28 03:39:23 +00002852 case lltok::kw_blockaddress: {
2853 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2854 Lex.Lex();
2855
2856 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002857
Chris Lattner3432c622009-10-28 03:39:23 +00002858 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2859 ParseValID(Fn) ||
2860 ParseToken(lltok::comma, "expected comma in block address expression")||
2861 ParseValID(Label) ||
2862 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2863 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002864
Chris Lattner3432c622009-10-28 03:39:23 +00002865 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2866 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002867 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002868 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002869
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002870 // Try to find the function (but skip it if it's forward-referenced).
2871 GlobalValue *GV = nullptr;
2872 if (Fn.Kind == ValID::t_GlobalID) {
2873 if (Fn.UIntVal < NumberedVals.size())
2874 GV = NumberedVals[Fn.UIntVal];
2875 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2876 GV = M->getNamedValue(Fn.StrVal);
2877 }
2878 Function *F = nullptr;
2879 if (GV) {
2880 // Confirm that it's actually a function with a definition.
2881 if (!isa<Function>(GV))
2882 return Error(Fn.Loc, "expected function name in blockaddress");
2883 F = cast<Function>(GV);
2884 if (F->isDeclaration())
2885 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2886 }
2887
2888 if (!F) {
2889 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002890 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002891 ForwardRefBlockAddresses.insert(std::make_pair(
2892 std::move(Fn),
2893 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002894 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2895 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002896 if (!FwdRef)
2897 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2898 GlobalValue::InternalLinkage, nullptr, "");
2899 ID.ConstantVal = FwdRef;
2900 ID.Kind = ValID::t_Constant;
2901 return false;
2902 }
2903
2904 // We found the function; now find the basic block. Don't use PFS, since we
2905 // might be inside a constant expression.
2906 BasicBlock *BB;
2907 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2908 if (Label.Kind == ValID::t_LocalID)
2909 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2910 else
2911 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2912 if (!BB)
2913 return Error(Label.Loc, "referenced value is not a basic block");
2914 } else {
2915 if (Label.Kind == ValID::t_LocalID)
2916 return Error(Label.Loc, "cannot take address of numeric label after "
2917 "the function is defined");
2918 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002919 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002920 if (!BB)
2921 return Error(Label.Loc, "referenced value is not a basic block");
2922 }
2923
2924 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002925 ID.Kind = ValID::t_Constant;
2926 return false;
2927 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002928
Chris Lattnerac161bf2009-01-02 07:01:27 +00002929 case lltok::kw_trunc:
2930 case lltok::kw_zext:
2931 case lltok::kw_sext:
2932 case lltok::kw_fptrunc:
2933 case lltok::kw_fpext:
2934 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002935 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002936 case lltok::kw_uitofp:
2937 case lltok::kw_sitofp:
2938 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002939 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002940 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002941 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002942 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002943 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 Constant *SrcVal;
2945 Lex.Lex();
2946 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2947 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002948 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002949 ParseType(DestTy) ||
2950 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2951 return true;
2952 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2953 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002954 getTypeString(SrcVal->getType()) + "' to '" +
2955 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002956 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002957 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 ID.Kind = ValID::t_Constant;
2959 return false;
2960 }
2961 case lltok::kw_extractvalue: {
2962 Lex.Lex();
2963 Constant *Val;
2964 SmallVector<unsigned, 4> Indices;
2965 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2966 ParseGlobalTypeAndValue(Val) ||
2967 ParseIndexList(Indices) ||
2968 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2969 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002970
Chris Lattner392be582010-02-12 20:49:41 +00002971 if (!Val->getType()->isAggregateType())
2972 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002973 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002974 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002975 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002976 ID.Kind = ValID::t_Constant;
2977 return false;
2978 }
2979 case lltok::kw_insertvalue: {
2980 Lex.Lex();
2981 Constant *Val0, *Val1;
2982 SmallVector<unsigned, 4> Indices;
2983 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2984 ParseGlobalTypeAndValue(Val0) ||
2985 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2986 ParseGlobalTypeAndValue(Val1) ||
2987 ParseIndexList(Indices) ||
2988 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2989 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002990 if (!Val0->getType()->isAggregateType())
2991 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002992 Type *IndexedType =
2993 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2994 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002995 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002996 if (IndexedType != Val1->getType())
2997 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2998 getTypeString(Val1->getType()) +
2999 "' instead of '" + getTypeString(IndexedType) +
3000 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003001 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 ID.Kind = ValID::t_Constant;
3003 return false;
3004 }
3005 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003006 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003007 unsigned PredVal, Opc = Lex.getUIntVal();
3008 Constant *Val0, *Val1;
3009 Lex.Lex();
3010 if (ParseCmpPredicate(PredVal, Opc) ||
3011 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3012 ParseGlobalTypeAndValue(Val0) ||
3013 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3014 ParseGlobalTypeAndValue(Val1) ||
3015 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3016 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003017
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 if (Val0->getType() != Val1->getType())
3019 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003020
Chris Lattnerac161bf2009-01-02 07:01:27 +00003021 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003022
Chris Lattnerac161bf2009-01-02 07:01:27 +00003023 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003024 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003025 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003026 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003027 } else {
3028 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003029 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003030 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003031 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003032 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003033 }
3034 ID.Kind = ValID::t_Constant;
3035 return false;
3036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 // Binary Operators.
3039 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003040 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003042 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003044 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 case lltok::kw_udiv:
3046 case lltok::kw_sdiv:
3047 case lltok::kw_fdiv:
3048 case lltok::kw_urem:
3049 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003050 case lltok::kw_frem:
3051 case lltok::kw_shl:
3052 case lltok::kw_lshr:
3053 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003054 bool NUW = false;
3055 bool NSW = false;
3056 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003057 unsigned Opc = Lex.getUIntVal();
3058 Constant *Val0, *Val1;
3059 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003060 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003061 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3062 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003063 if (EatIfPresent(lltok::kw_nuw))
3064 NUW = true;
3065 if (EatIfPresent(lltok::kw_nsw)) {
3066 NSW = true;
3067 if (EatIfPresent(lltok::kw_nuw))
3068 NUW = true;
3069 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003070 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3071 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003072 if (EatIfPresent(lltok::kw_exact))
3073 Exact = true;
3074 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003075 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3076 ParseGlobalTypeAndValue(Val0) ||
3077 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3078 ParseGlobalTypeAndValue(Val1) ||
3079 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3080 return true;
3081 if (Val0->getType() != Val1->getType())
3082 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003083 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003084 if (NUW)
3085 return Error(ModifierLoc, "nuw only applies to integer operations");
3086 if (NSW)
3087 return Error(ModifierLoc, "nsw only applies to integer operations");
3088 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003089 // Check that the type is valid for the operator.
3090 switch (Opc) {
3091 case Instruction::Add:
3092 case Instruction::Sub:
3093 case Instruction::Mul:
3094 case Instruction::UDiv:
3095 case Instruction::SDiv:
3096 case Instruction::URem:
3097 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003098 case Instruction::Shl:
3099 case Instruction::AShr:
3100 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003101 if (!Val0->getType()->isIntOrIntVectorTy())
3102 return Error(ID.Loc, "constexpr requires integer operands");
3103 break;
3104 case Instruction::FAdd:
3105 case Instruction::FSub:
3106 case Instruction::FMul:
3107 case Instruction::FDiv:
3108 case Instruction::FRem:
3109 if (!Val0->getType()->isFPOrFPVectorTy())
3110 return Error(ID.Loc, "constexpr requires fp operands");
3111 break;
3112 default: llvm_unreachable("Unknown binary operator!");
3113 }
Dan Gohman1b849082009-09-07 23:54:19 +00003114 unsigned Flags = 0;
3115 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3116 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003117 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003118 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003119 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003120 ID.Kind = ValID::t_Constant;
3121 return false;
3122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003123
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003125 case lltok::kw_and:
3126 case lltok::kw_or:
3127 case lltok::kw_xor: {
3128 unsigned Opc = Lex.getUIntVal();
3129 Constant *Val0, *Val1;
3130 Lex.Lex();
3131 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3132 ParseGlobalTypeAndValue(Val0) ||
3133 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3134 ParseGlobalTypeAndValue(Val1) ||
3135 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3136 return true;
3137 if (Val0->getType() != Val1->getType())
3138 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003139 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 return Error(ID.Loc,
3141 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003142 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003143 ID.Kind = ValID::t_Constant;
3144 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003145 }
3146
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 case lltok::kw_getelementptr:
3148 case lltok::kw_shufflevector:
3149 case lltok::kw_insertelement:
3150 case lltok::kw_extractelement:
3151 case lltok::kw_select: {
3152 unsigned Opc = Lex.getUIntVal();
3153 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003154 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003155 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003156 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003157
Dan Gohman1639c392009-07-27 21:53:46 +00003158 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003159 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003160
3161 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3162 return true;
3163
3164 LocTy ExplicitTypeLoc = Lex.getLoc();
3165 if (Opc == Instruction::GetElementPtr) {
3166 if (ParseType(Ty) ||
3167 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3168 return true;
3169 }
3170
Peter Collingbourned93620b2016-11-10 22:34:55 +00003171 Optional<unsigned> InRangeOp;
3172 if (ParseGlobalValueVector(
3173 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003174 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3175 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003176
Chris Lattnerac161bf2009-01-02 07:01:27 +00003177 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003178 if (Elts.size() == 0 ||
3179 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003180 return Error(ID.Loc, "base of getelementptr must be a pointer");
3181
3182 Type *BaseType = Elts[0]->getType();
3183 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003184 if (Ty != BasePointerType->getElementType())
3185 return Error(
3186 ExplicitTypeLoc,
3187 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003188
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003189 unsigned GEPWidth =
3190 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3191
Jay Foaded8db7d2011-07-21 14:31:17 +00003192 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003193 for (Constant *Val : Indices) {
3194 Type *ValTy = Val->getType();
3195 if (!ValTy->getScalarType()->isIntegerTy())
3196 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003197 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003198 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003199 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003200 return Error(
3201 ID.Loc,
3202 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003203 // GEPWidth may have been unknown because the base is a scalar,
3204 // but it is known now.
3205 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003206 }
3207 }
3208
Craig Toppere3dcce92015-08-01 22:20:21 +00003209 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003210 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003211 return Error(ID.Loc, "base element of getelementptr must be sized");
3212
David Blaikie4a2e73b2015-04-02 18:55:32 +00003213 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003214 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003215
3216 if (InRangeOp) {
3217 if (*InRangeOp == 0)
3218 return Error(ID.Loc,
3219 "inrange keyword may not appear on pointer operand");
3220 --*InRangeOp;
3221 }
3222
3223 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3224 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003225 } else if (Opc == Instruction::Select) {
3226 if (Elts.size() != 3)
3227 return Error(ID.Loc, "expected three operands to select");
3228 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3229 Elts[2]))
3230 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003231 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003232 } else if (Opc == Instruction::ShuffleVector) {
3233 if (Elts.size() != 3)
3234 return Error(ID.Loc, "expected three operands to shufflevector");
3235 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3236 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003237 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003238 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003239 } else if (Opc == Instruction::ExtractElement) {
3240 if (Elts.size() != 2)
3241 return Error(ID.Loc, "expected two operands to extractelement");
3242 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3243 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003244 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003245 } else {
3246 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3247 if (Elts.size() != 3)
3248 return Error(ID.Loc, "expected three operands to insertelement");
3249 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3250 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003251 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003252 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003253 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003254
Chris Lattnerac161bf2009-01-02 07:01:27 +00003255 ID.Kind = ValID::t_Constant;
3256 return false;
3257 }
3258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003259
Chris Lattnerac161bf2009-01-02 07:01:27 +00003260 Lex.Lex();
3261 return false;
3262}
3263
3264/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003265bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003266 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003268 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003269 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003270 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003271 if (V && !(C = dyn_cast<Constant>(V)))
3272 return Error(ID.Loc, "global values must be constants");
3273 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003274}
3275
Victor Hernandez9d75c962010-01-11 22:31:58 +00003276bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003277 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003278 return ParseType(Ty) ||
3279 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003280}
3281
Rafael Espindola83a362c2015-01-06 22:55:16 +00003282bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003283 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003284
3285 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003286 if (!EatIfPresent(lltok::kw_comdat))
3287 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003288
3289 if (EatIfPresent(lltok::lparen)) {
3290 if (Lex.getKind() != lltok::ComdatVar)
3291 return TokError("expected comdat variable");
3292 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3293 Lex.Lex();
3294 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3295 return true;
3296 } else {
3297 if (GlobalName.empty())
3298 return TokError("comdat cannot be unnamed");
3299 C = getComdat(GlobalName, KwLoc);
3300 }
3301
David Majnemerdad0a642014-06-27 18:19:56 +00003302 return false;
3303}
3304
Victor Hernandez9d75c962010-01-11 22:31:58 +00003305/// ParseGlobalValueVector
3306/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003307/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3308bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3309 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003310 // Empty list.
3311 if (Lex.getKind() == lltok::rbrace ||
3312 Lex.getKind() == lltok::rsquare ||
3313 Lex.getKind() == lltok::greater ||
3314 Lex.getKind() == lltok::rparen)
3315 return false;
3316
Peter Collingbourned93620b2016-11-10 22:34:55 +00003317 do {
3318 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3319 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003320
Peter Collingbourned93620b2016-11-10 22:34:55 +00003321 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003322 if (ParseGlobalTypeAndValue(C)) return true;
3323 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003324 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003325
3326 return false;
3327}
3328
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003329bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003330 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003331 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003332 return true;
3333
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003334 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003335 return false;
3336}
3337
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003338/// MDNode:
3339/// ::= !{ ... }
3340/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003341/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003342bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003343 if (Lex.getKind() == lltok::MetadataVar)
3344 return ParseSpecializedMDNode(N);
3345
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003346 return ParseToken(lltok::exclaim, "expected '!' here") ||
3347 ParseMDNodeTail(N);
3348}
3349
3350bool LLParser::ParseMDNodeTail(MDNode *&N) {
3351 // !{ ... }
3352 if (Lex.getKind() == lltok::lbrace)
3353 return ParseMDTuple(N);
3354
3355 // !42
3356 return ParseMDNodeID(N);
3357}
3358
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003359namespace {
3360
3361/// Structure to represent an optional metadata field.
3362template <class FieldTy> struct MDFieldImpl {
3363 typedef MDFieldImpl ImplTy;
3364 FieldTy Val;
3365 bool Seen;
3366
3367 void assign(FieldTy Val) {
3368 Seen = true;
3369 this->Val = std::move(Val);
3370 }
3371
3372 explicit MDFieldImpl(FieldTy Default)
3373 : Val(std::move(Default)), Seen(false) {}
3374};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003375
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003376struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3377 uint64_t Max;
3378
3379 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3380 : ImplTy(Default), Max(Max) {}
3381};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003382
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003383struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003384 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003385};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003386
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003387struct ColumnField : public MDUnsignedField {
3388 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3389};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003390
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003391struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003392 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003393 DwarfTagField(dwarf::Tag DefaultTag)
3394 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003395};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003396
Amjad Abouda9bcf162015-12-10 12:56:35 +00003397struct DwarfMacinfoTypeField : public MDUnsignedField {
3398 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3399 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3400 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3401};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003402
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003403struct DwarfAttEncodingField : public MDUnsignedField {
3404 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3405};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003406
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003407struct DwarfVirtualityField : public MDUnsignedField {
3408 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3409};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003410
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003411struct DwarfLangField : public MDUnsignedField {
3412 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3413};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003414
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003415struct DwarfCCField : public MDUnsignedField {
3416 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3417};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003418
Adrian Prantlb939a252016-03-31 23:56:58 +00003419struct EmissionKindField : public MDUnsignedField {
3420 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3421};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003422
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003423struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3424 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003425};
3426
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003427struct MDSignedField : public MDFieldImpl<int64_t> {
3428 int64_t Min;
3429 int64_t Max;
3430
3431 MDSignedField(int64_t Default = 0)
3432 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3433 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3434 : ImplTy(Default), Min(Min), Max(Max) {}
3435};
3436
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003437struct MDBoolField : public MDFieldImpl<bool> {
3438 MDBoolField(bool Default = false) : ImplTy(Default) {}
3439};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003440
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003441struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003442 bool AllowNull;
3443
3444 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003445};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003446
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003447struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3448 MDConstant() : ImplTy(nullptr) {}
3449};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003450
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003451struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003452 bool AllowEmpty;
3453 MDStringField(bool AllowEmpty = true)
3454 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003455};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003456
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003457struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3458 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3459};
3460
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003461struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3462 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3463 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3464};
3465
Eugene Zelenko1804a772016-08-25 00:45:04 +00003466} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003467
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003468namespace llvm {
3469
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003470template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003471bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003472 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003473 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3474 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003475
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003476 auto &U = Lex.getAPSIntVal();
3477 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003478 return TokError("value for '" + Name + "' too large, limit is " +
3479 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003480 Result.assign(U.getZExtValue());
3481 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003482 Lex.Lex();
3483 return false;
3484}
3485
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003486template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003487bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3488 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3489}
3490template <>
3491bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3492 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3493}
3494
3495template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003496bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3497 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003498 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003499
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003500 if (Lex.getKind() != lltok::DwarfTag)
3501 return TokError("expected DWARF tag");
3502
3503 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3504 if (Tag == dwarf::DW_TAG_invalid)
3505 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003506 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003507
3508 Result.assign(Tag);
3509 Lex.Lex();
3510 return false;
3511}
3512
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003513template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003514bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003515 DwarfMacinfoTypeField &Result) {
3516 if (Lex.getKind() == lltok::APSInt)
3517 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3518
3519 if (Lex.getKind() != lltok::DwarfMacinfo)
3520 return TokError("expected DWARF macinfo type");
3521
3522 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3523 if (Macinfo == dwarf::DW_MACINFO_invalid)
3524 return TokError(
3525 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3526 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3527
3528 Result.assign(Macinfo);
3529 Lex.Lex();
3530 return false;
3531}
3532
3533template <>
3534bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003535 DwarfVirtualityField &Result) {
3536 if (Lex.getKind() == lltok::APSInt)
3537 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3538
3539 if (Lex.getKind() != lltok::DwarfVirtuality)
3540 return TokError("expected DWARF virtuality code");
3541
3542 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003543 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003544 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3545 Lex.getStrVal() + "'");
3546 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3547 Result.assign(Virtuality);
3548 Lex.Lex();
3549 return false;
3550}
3551
3552template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003553bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3554 if (Lex.getKind() == lltok::APSInt)
3555 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3556
3557 if (Lex.getKind() != lltok::DwarfLang)
3558 return TokError("expected DWARF language");
3559
3560 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3561 if (!Lang)
3562 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3563 "'");
3564 assert(Lang <= Result.Max && "Expected valid DWARF language");
3565 Result.assign(Lang);
3566 Lex.Lex();
3567 return false;
3568}
3569
3570template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003571bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3572 if (Lex.getKind() == lltok::APSInt)
3573 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3574
3575 if (Lex.getKind() != lltok::DwarfCC)
3576 return TokError("expected DWARF calling convention");
3577
3578 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3579 if (!CC)
3580 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3581 "'");
3582 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3583 Result.assign(CC);
3584 Lex.Lex();
3585 return false;
3586}
3587
3588template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003589bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3590 if (Lex.getKind() == lltok::APSInt)
3591 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3592
3593 if (Lex.getKind() != lltok::EmissionKind)
3594 return TokError("expected emission kind");
3595
3596 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3597 if (!Kind)
3598 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3599 "'");
3600 assert(*Kind <= Result.Max && "Expected valid emission kind");
3601 Result.assign(*Kind);
3602 Lex.Lex();
3603 return false;
3604}
3605
3606template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003607bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003608 DwarfAttEncodingField &Result) {
3609 if (Lex.getKind() == lltok::APSInt)
3610 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3611
3612 if (Lex.getKind() != lltok::DwarfAttEncoding)
3613 return TokError("expected DWARF type attribute encoding");
3614
3615 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3616 if (!Encoding)
3617 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3618 Lex.getStrVal() + "'");
3619 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3620 Result.assign(Encoding);
3621 Lex.Lex();
3622 return false;
3623}
3624
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003625/// DIFlagField
3626/// ::= uint32
3627/// ::= DIFlagVector
3628/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3629template <>
3630bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003631
3632 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003633 auto parseFlag = [&](DINode::DIFlags &Val) {
3634 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3635 uint32_t TempVal = static_cast<uint32_t>(Val);
3636 bool Res = ParseUInt32(TempVal);
3637 Val = static_cast<DINode::DIFlags>(TempVal);
3638 return Res;
3639 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003640
3641 if (Lex.getKind() != lltok::DIFlag)
3642 return TokError("expected debug info flag");
3643
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003644 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003645 if (!Val)
3646 return TokError(Twine("invalid debug info flag flag '") +
3647 Lex.getStrVal() + "'");
3648 Lex.Lex();
3649 return false;
3650 };
3651
3652 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003653 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003654 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003655 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003656 if (parseFlag(Val))
3657 return true;
3658 Combined |= Val;
3659 } while (EatIfPresent(lltok::bar));
3660
3661 Result.assign(Combined);
3662 return false;
3663}
3664
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003665template <>
3666bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003667 MDSignedField &Result) {
3668 if (Lex.getKind() != lltok::APSInt)
3669 return TokError("expected signed integer");
3670
3671 auto &S = Lex.getAPSIntVal();
3672 if (S < Result.Min)
3673 return TokError("value for '" + Name + "' too small, limit is " +
3674 Twine(Result.Min));
3675 if (S > Result.Max)
3676 return TokError("value for '" + Name + "' too large, limit is " +
3677 Twine(Result.Max));
3678 Result.assign(S.getExtValue());
3679 assert(Result.Val >= Result.Min && "Expected value in range");
3680 assert(Result.Val <= Result.Max && "Expected value in range");
3681 Lex.Lex();
3682 return false;
3683}
3684
3685template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003686bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3687 switch (Lex.getKind()) {
3688 default:
3689 return TokError("expected 'true' or 'false'");
3690 case lltok::kw_true:
3691 Result.assign(true);
3692 break;
3693 case lltok::kw_false:
3694 Result.assign(false);
3695 break;
3696 }
3697 Lex.Lex();
3698 return false;
3699}
3700
3701template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003702bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003703 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003704 if (!Result.AllowNull)
3705 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003706 Lex.Lex();
3707 Result.assign(nullptr);
3708 return false;
3709 }
3710
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003711 Metadata *MD;
3712 if (ParseMetadata(MD, nullptr))
3713 return true;
3714
3715 Result.assign(MD);
3716 return false;
3717}
3718
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003719template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003720bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003721 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003722 std::string S;
3723 if (ParseStringConstant(S))
3724 return true;
3725
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003726 if (!Result.AllowEmpty && S.empty())
3727 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3728
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003729 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003730 return false;
3731}
3732
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003733template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003734bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3735 SmallVector<Metadata *, 4> MDs;
3736 if (ParseMDNodeVector(MDs))
3737 return true;
3738
3739 Result.assign(std::move(MDs));
3740 return false;
3741}
3742
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003743template <>
3744bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3745 ChecksumKindField &Result) {
3746 if (Lex.getKind() != lltok::ChecksumKind)
3747 return TokError(
3748 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3749
3750 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3751
3752 Result.assign(CSKind);
3753 Lex.Lex();
3754 return false;
3755}
3756
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003757} // end namespace llvm
3758
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003759template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003760bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003761 do {
3762 if (Lex.getKind() != lltok::LabelStr)
3763 return TokError("expected field label here");
3764
3765 if (parseField())
3766 return true;
3767 } while (EatIfPresent(lltok::comma));
3768
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003769 return false;
3770}
3771
3772template <class ParserTy>
3773bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3774 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3775 Lex.Lex();
3776
3777 if (ParseToken(lltok::lparen, "expected '(' here"))
3778 return true;
3779 if (Lex.getKind() != lltok::rparen)
3780 if (ParseMDFieldsImplBody(parseField))
3781 return true;
3782
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003783 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003784 return ParseToken(lltok::rparen, "expected ')' here");
3785}
3786
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003787template <class FieldTy>
3788bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3789 if (Result.Seen)
3790 return TokError("field '" + Name + "' cannot be specified more than once");
3791
3792 LocTy Loc = Lex.getLoc();
3793 Lex.Lex();
3794 return ParseMDField(Loc, Name, Result);
3795}
3796
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003797bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3798 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003799
3800#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003801 if (Lex.getStrVal() == #CLASS) \
3802 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003803#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003804
3805 return TokError("expected metadata type");
3806}
3807
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003808#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3809#define NOP_FIELD(NAME, TYPE, INIT)
3810#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3811 if (!NAME.Seen) \
3812 return Error(ClosingLoc, "missing required field '" #NAME "'");
3813#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003814 if (Lex.getStrVal() == #NAME) \
3815 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003816#define PARSE_MD_FIELDS() \
3817 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3818 do { \
3819 LocTy ClosingLoc; \
3820 if (ParseMDFieldsImpl([&]() -> bool { \
3821 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3822 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3823 }, ClosingLoc)) \
3824 return true; \
3825 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3826 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003827#define GET_OR_DISTINCT(CLASS, ARGS) \
3828 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003829
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003830/// ParseDILocationFields:
3831/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3832bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003833#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003834 OPTIONAL(line, LineField, ); \
3835 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003836 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003837 OPTIONAL(inlinedAt, MDField, );
3838 PARSE_MD_FIELDS();
3839#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003840
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003841 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003842 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003843 return false;
3844}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003845
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003846/// ParseGenericDINode:
3847/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3848bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003849#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003850 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003851 OPTIONAL(header, MDStringField, ); \
3852 OPTIONAL(operands, MDFieldList, );
3853 PARSE_MD_FIELDS();
3854#undef VISIT_MD_FIELDS
3855
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003856 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003857 (Context, tag.Val, header.Val, operands.Val));
3858 return false;
3859}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003860
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003861/// ParseDISubrange:
3862/// ::= !DISubrange(count: 30, lowerBound: 2)
3863bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003865 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003866 OPTIONAL(lowerBound, MDSignedField, );
3867 PARSE_MD_FIELDS();
3868#undef VISIT_MD_FIELDS
3869
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003870 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003871 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003872}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003873
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003874/// ParseDIEnumerator:
3875/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3876bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003877#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003878 REQUIRED(name, MDStringField, ); \
3879 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003880 PARSE_MD_FIELDS();
3881#undef VISIT_MD_FIELDS
3882
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003883 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003884 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003885}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003886
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003887/// ParseDIBasicType:
3888/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3889bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003890#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003891 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003892 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003893 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003894 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003895 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003896 PARSE_MD_FIELDS();
3897#undef VISIT_MD_FIELDS
3898
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003899 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003900 align.Val, encoding.Val));
3901 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003902}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003903
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003904/// ParseDIDerivedType:
3905/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003906/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003907/// align: 32, offset: 0, flags: 0, extraData: !3,
3908/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003909bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003910#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3911 REQUIRED(tag, DwarfTagField, ); \
3912 OPTIONAL(name, MDStringField, ); \
3913 OPTIONAL(file, MDField, ); \
3914 OPTIONAL(line, LineField, ); \
3915 OPTIONAL(scope, MDField, ); \
3916 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003917 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003918 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003919 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003920 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003921 OPTIONAL(extraData, MDField, ); \
3922 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003923 PARSE_MD_FIELDS();
3924#undef VISIT_MD_FIELDS
3925
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003926 Optional<unsigned> DWARFAddressSpace;
3927 if (dwarfAddressSpace.Val != UINT32_MAX)
3928 DWARFAddressSpace = dwarfAddressSpace.Val;
3929
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003930 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003931 (Context, tag.Val, name.Val, file.Val, line.Val,
3932 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003933 offset.Val, DWARFAddressSpace, flags.Val,
3934 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003935 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003936}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003937
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003938bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003939#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3940 REQUIRED(tag, DwarfTagField, ); \
3941 OPTIONAL(name, MDStringField, ); \
3942 OPTIONAL(file, MDField, ); \
3943 OPTIONAL(line, LineField, ); \
3944 OPTIONAL(scope, MDField, ); \
3945 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003946 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003947 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003948 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003949 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003950 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003951 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003952 OPTIONAL(vtableHolder, MDField, ); \
3953 OPTIONAL(templateParams, MDField, ); \
3954 OPTIONAL(identifier, MDStringField, );
3955 PARSE_MD_FIELDS();
3956#undef VISIT_MD_FIELDS
3957
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003958 // If this has an identifier try to build an ODR type.
3959 if (identifier.Val)
3960 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003961 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3962 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3963 elements.Val, runtimeLang.Val, vtableHolder.Val,
3964 templateParams.Val)) {
3965 Result = CT;
3966 return false;
3967 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003968
3969 // Create a new node, and save it in the context if it belongs in the type
3970 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003971 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003972 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003973 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3974 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3975 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3976 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003977}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003978
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003979bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003980#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003981 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003982 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003983 REQUIRED(types, MDField, );
3984 PARSE_MD_FIELDS();
3985#undef VISIT_MD_FIELDS
3986
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003987 Result = GET_OR_DISTINCT(DISubroutineType,
3988 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003989 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003990}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003991
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003992/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003993/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
3994/// checksumkind: CSK_MD5,
3995/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003996bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3998 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003999 REQUIRED(directory, MDStringField, ); \
4000 OPTIONAL(checksumkind, ChecksumKindField, ); \
4001 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004002 PARSE_MD_FIELDS();
4003#undef VISIT_MD_FIELDS
4004
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004005 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4006 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004007 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004008}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004009
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004010/// ParseDICompileUnit:
4011/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004012/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004013/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004014/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004015/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004016bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004017 if (!IsDistinct)
4018 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4019
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004020#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4021 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004022 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004023 OPTIONAL(producer, MDStringField, ); \
4024 OPTIONAL(isOptimized, MDBoolField, ); \
4025 OPTIONAL(flags, MDStringField, ); \
4026 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4027 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004028 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004029 OPTIONAL(enums, MDField, ); \
4030 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004031 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004032 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004033 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004034 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004035 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4036 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004037 PARSE_MD_FIELDS();
4038#undef VISIT_MD_FIELDS
4039
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004040 Result = DICompileUnit::getDistinct(
4041 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4042 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004043 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004044 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004045 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004046}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004047
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004048/// ParseDISubprogram:
4049/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004050/// file: !1, line: 7, type: !2, isLocal: false,
4051/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004052/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004053/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004054/// isOptimized: false, templateParams: !4, declaration: !5,
4055/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004056bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004057 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004058#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4059 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004060 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004061 OPTIONAL(linkageName, MDStringField, ); \
4062 OPTIONAL(file, MDField, ); \
4063 OPTIONAL(line, LineField, ); \
4064 OPTIONAL(type, MDField, ); \
4065 OPTIONAL(isLocal, MDBoolField, ); \
4066 OPTIONAL(isDefinition, MDBoolField, (true)); \
4067 OPTIONAL(scopeLine, LineField, ); \
4068 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004069 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004070 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004071 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004072 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004073 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004074 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004075 OPTIONAL(templateParams, MDField, ); \
4076 OPTIONAL(declaration, MDField, ); \
4077 OPTIONAL(variables, MDField, );
4078 PARSE_MD_FIELDS();
4079#undef VISIT_MD_FIELDS
4080
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004081 if (isDefinition.Val && !IsDistinct)
4082 return Lex.Error(
4083 Loc,
4084 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4085
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004086 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004087 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4088 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4089 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004090 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4091 isOptimized.Val, unit.Val, templateParams.Val,
4092 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004093 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004094}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004095
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004096/// ParseDILexicalBlock:
4097/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4098bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004099#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004100 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004101 OPTIONAL(file, MDField, ); \
4102 OPTIONAL(line, LineField, ); \
4103 OPTIONAL(column, ColumnField, );
4104 PARSE_MD_FIELDS();
4105#undef VISIT_MD_FIELDS
4106
4107 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004108 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004109 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004110}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004111
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004112/// ParseDILexicalBlockFile:
4113/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4114bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004115#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004116 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004117 OPTIONAL(file, MDField, ); \
4118 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4119 PARSE_MD_FIELDS();
4120#undef VISIT_MD_FIELDS
4121
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004122 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004123 (Context, scope.Val, file.Val, discriminator.Val));
4124 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004125}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004126
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004127/// ParseDINamespace:
4128/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4129bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004130#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4131 REQUIRED(scope, MDField, ); \
4132 OPTIONAL(file, MDField, ); \
4133 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004134 OPTIONAL(line, LineField, ); \
4135 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004136 PARSE_MD_FIELDS();
4137#undef VISIT_MD_FIELDS
4138
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004139 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantldbfda632016-11-03 19:42:02 +00004140 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004141 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004142}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004143
Amjad Abouda9bcf162015-12-10 12:56:35 +00004144/// ParseDIMacro:
4145/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4146bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4147#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4148 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004149 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004150 REQUIRED(name, MDStringField, ); \
4151 OPTIONAL(value, MDStringField, );
4152 PARSE_MD_FIELDS();
4153#undef VISIT_MD_FIELDS
4154
4155 Result = GET_OR_DISTINCT(DIMacro,
4156 (Context, type.Val, line.Val, name.Val, value.Val));
4157 return false;
4158}
4159
4160/// ParseDIMacroFile:
4161/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4162bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4163#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4164 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004165 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004166 REQUIRED(file, MDField, ); \
4167 OPTIONAL(nodes, MDField, );
4168 PARSE_MD_FIELDS();
4169#undef VISIT_MD_FIELDS
4170
4171 Result = GET_OR_DISTINCT(DIMacroFile,
4172 (Context, type.Val, line.Val, file.Val, nodes.Val));
4173 return false;
4174}
4175
Adrian Prantlab1243f2015-06-29 23:03:47 +00004176/// ParseDIModule:
4177/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4178/// includePath: "/usr/include", isysroot: "/")
4179bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4180#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4181 REQUIRED(scope, MDField, ); \
4182 REQUIRED(name, MDStringField, ); \
4183 OPTIONAL(configMacros, MDStringField, ); \
4184 OPTIONAL(includePath, MDStringField, ); \
4185 OPTIONAL(isysroot, MDStringField, );
4186 PARSE_MD_FIELDS();
4187#undef VISIT_MD_FIELDS
4188
4189 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4190 configMacros.Val, includePath.Val, isysroot.Val));
4191 return false;
4192}
4193
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004194/// ParseDITemplateTypeParameter:
4195/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4196bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004197#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004198 OPTIONAL(name, MDStringField, ); \
4199 REQUIRED(type, MDField, );
4200 PARSE_MD_FIELDS();
4201#undef VISIT_MD_FIELDS
4202
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004203 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004204 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004205 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004206}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004207
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004208/// ParseDITemplateValueParameter:
4209/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004210/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004211bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004212#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004213 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004214 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004215 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004216 REQUIRED(value, MDField, );
4217 PARSE_MD_FIELDS();
4218#undef VISIT_MD_FIELDS
4219
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004220 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004221 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004222 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004223}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004224
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004225/// ParseDIGlobalVariable:
4226/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004227/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004228/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004229bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004230#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004231 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004232 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004233 OPTIONAL(linkageName, MDStringField, ); \
4234 OPTIONAL(file, MDField, ); \
4235 OPTIONAL(line, LineField, ); \
4236 OPTIONAL(type, MDField, ); \
4237 OPTIONAL(isLocal, MDBoolField, ); \
4238 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004239 OPTIONAL(declaration, MDField, ); \
4240 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004241 PARSE_MD_FIELDS();
4242#undef VISIT_MD_FIELDS
4243
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004244 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004245 (Context, scope.Val, name.Val, linkageName.Val,
4246 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004247 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004248 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004249}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004250
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004251/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004252/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004253/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4254/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004255/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004256/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4257/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004258bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004259#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004260 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004261 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004262 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004263 OPTIONAL(file, MDField, ); \
4264 OPTIONAL(line, LineField, ); \
4265 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004266 OPTIONAL(flags, DIFlagField, ); \
4267 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004268 PARSE_MD_FIELDS();
4269#undef VISIT_MD_FIELDS
4270
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004271 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004272 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004273 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004274 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004275}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004276
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004277/// ParseDIExpression:
4278/// ::= !DIExpression(0, 7, -1)
4279bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004280 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4281 Lex.Lex();
4282
4283 if (ParseToken(lltok::lparen, "expected '(' here"))
4284 return true;
4285
4286 SmallVector<uint64_t, 8> Elements;
4287 if (Lex.getKind() != lltok::rparen)
4288 do {
4289 if (Lex.getKind() == lltok::DwarfOp) {
4290 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4291 Lex.Lex();
4292 Elements.push_back(Op);
4293 continue;
4294 }
4295 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4296 }
4297
4298 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4299 return TokError("expected unsigned integer");
4300
4301 auto &U = Lex.getAPSIntVal();
4302 if (U.ugt(UINT64_MAX))
4303 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4304 Elements.push_back(U.getZExtValue());
4305 Lex.Lex();
4306 } while (EatIfPresent(lltok::comma));
4307
4308 if (ParseToken(lltok::rparen, "expected ')' here"))
4309 return true;
4310
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004311 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004312 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004313}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004314
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004315/// ParseDIGlobalVariableExpression:
4316/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4317bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4318 bool IsDistinct) {
4319#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4320 REQUIRED(var, MDField, ); \
4321 OPTIONAL(expr, MDField, );
4322 PARSE_MD_FIELDS();
4323#undef VISIT_MD_FIELDS
4324
4325 Result =
4326 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4327 return false;
4328}
4329
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004330/// ParseDIObjCProperty:
4331/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004332/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004333bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004334#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004335 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004336 OPTIONAL(file, MDField, ); \
4337 OPTIONAL(line, LineField, ); \
4338 OPTIONAL(setter, MDStringField, ); \
4339 OPTIONAL(getter, MDStringField, ); \
4340 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4341 OPTIONAL(type, MDField, );
4342 PARSE_MD_FIELDS();
4343#undef VISIT_MD_FIELDS
4344
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004345 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004346 (Context, name.Val, file.Val, line.Val, setter.Val,
4347 getter.Val, attributes.Val, type.Val));
4348 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004349}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004350
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004351/// ParseDIImportedEntity:
4352/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004353/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004354bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004355#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4356 REQUIRED(tag, DwarfTagField, ); \
4357 REQUIRED(scope, MDField, ); \
4358 OPTIONAL(entity, MDField, ); \
4359 OPTIONAL(line, LineField, ); \
4360 OPTIONAL(name, MDStringField, );
4361 PARSE_MD_FIELDS();
4362#undef VISIT_MD_FIELDS
4363
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004364 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004365 entity.Val, line.Val, name.Val));
4366 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004367}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004368
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004369#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004370#undef NOP_FIELD
4371#undef REQUIRE_FIELD
4372#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004373
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004374/// ParseMetadataAsValue
4375/// ::= metadata i32 %local
4376/// ::= metadata i32 @global
4377/// ::= metadata i32 7
4378/// ::= metadata !0
4379/// ::= metadata !{...}
4380/// ::= metadata !"string"
4381bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4382 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004383 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004384 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004385 return true;
4386
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004387 V = MetadataAsValue::get(Context, MD);
4388 return false;
4389}
4390
4391/// ParseValueAsMetadata
4392/// ::= i32 %local
4393/// ::= i32 @global
4394/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004395bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4396 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004397 Type *Ty;
4398 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004399 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004400 return true;
4401 if (Ty->isMetadataTy())
4402 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4403
4404 Value *V;
4405 if (ParseValue(Ty, V, PFS))
4406 return true;
4407
4408 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004409 return false;
4410}
4411
4412/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004413/// ::= i32 %local
4414/// ::= i32 @global
4415/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004416/// ::= !42
4417/// ::= !{...}
4418/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004419/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004420bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004421 if (Lex.getKind() == lltok::MetadataVar) {
4422 MDNode *N;
4423 if (ParseSpecializedMDNode(N))
4424 return true;
4425 MD = N;
4426 return false;
4427 }
4428
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004429 // ValueAsMetadata:
4430 // <type> <value>
4431 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004432 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004433
4434 // '!'.
4435 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4436 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004437
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004438 // MDString:
4439 // ::= '!' STRINGCONSTANT
4440 if (Lex.getKind() == lltok::StringConstant) {
4441 MDString *S;
4442 if (ParseMDString(S))
4443 return true;
4444 MD = S;
4445 return false;
4446 }
4447
Dan Gohman8939ba332010-07-14 18:26:50 +00004448 // MDNode:
4449 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004450 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004451 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004452 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004453 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004454 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004455 return false;
4456}
4457
Victor Hernandez9d75c962010-01-11 22:31:58 +00004458//===----------------------------------------------------------------------===//
4459// Function Parsing.
4460//===----------------------------------------------------------------------===//
4461
Chris Lattner229907c2011-07-18 04:54:35 +00004462bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004463 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004464 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004465 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004466
Chris Lattnerac161bf2009-01-02 07:01:27 +00004467 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004468 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004469 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004470 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004471 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004473 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004474 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004475 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004476 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004477 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004478 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004479 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4480 (ID.UIntVal >> 1) & 1,
4481 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004482 return false;
4483 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 case ValID::t_GlobalName:
4485 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004486 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 case ValID::t_GlobalID:
4488 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004489 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004491 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004493 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004494 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004495 return false;
4496 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004497 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004498 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4499 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004500
Dan Gohman518cda42011-12-17 00:04:22 +00004501 // The lexer has no type info, so builds all half, float, and double FP
4502 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004503 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004504 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004505 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004506 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004507 &Ignored);
4508 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004509 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004510 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004512 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004513
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004514 if (V->getType() != Ty)
4515 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004516 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004517
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 return false;
4519 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004520 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004522 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 return false;
4524 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004525 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004526 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004527 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004528 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004530 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004531 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004532 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004533 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004534 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004535 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004536 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004537 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004539 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004541 case ValID::t_None:
4542 if (!Ty->isTokenTy())
4543 return Error(ID.Loc, "invalid type for none constant");
4544 V = Constant::getNullValue(Ty);
4545 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004546 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004547 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004548 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004549
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 V = ID.ConstantVal;
4551 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004552 case ValID::t_ConstantStruct:
4553 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004554 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004555 if (ST->getNumElements() != ID.UIntVal)
4556 return Error(ID.Loc,
4557 "initializer with struct type has wrong # elements");
4558 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4559 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004560
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004561 // Verify that the elements are compatible with the structtype.
4562 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4563 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4564 return Error(ID.Loc, "element " + Twine(i) +
4565 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004566
David Blaikieadbda4b2015-08-03 20:08:41 +00004567 V = ConstantStruct::get(
4568 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004569 } else
4570 return Error(ID.Loc, "constant expression type mismatch");
4571 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004573 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004574}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004575
Alex Lorenzd2255952015-07-17 22:07:03 +00004576bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4577 C = nullptr;
4578 ValID ID;
4579 auto Loc = Lex.getLoc();
4580 if (ParseValID(ID, /*PFS=*/nullptr))
4581 return true;
4582 switch (ID.Kind) {
4583 case ValID::t_APSInt:
4584 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004585 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004586 case ValID::t_Constant:
4587 case ValID::t_ConstantStruct:
4588 case ValID::t_PackedConstantStruct: {
4589 Value *V;
4590 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4591 return true;
4592 assert(isa<Constant>(V) && "Expected a constant value");
4593 C = cast<Constant>(V);
4594 return false;
4595 }
4596 default:
4597 return Error(Loc, "expected a constant value");
4598 }
4599}
4600
David Majnemer8a1c45d2015-12-12 05:38:55 +00004601bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004602 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004604 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004605}
4606
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004607bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004608 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004609 return ParseType(Ty) ||
4610 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004611}
4612
Chris Lattner3ed871f2009-10-27 19:13:16 +00004613bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4614 PerFunctionState &PFS) {
4615 Value *V;
4616 Loc = Lex.getLoc();
4617 if (ParseTypeAndValue(V, PFS)) return true;
4618 if (!isa<BasicBlock>(V))
4619 return Error(Loc, "expected a basic block");
4620 BB = cast<BasicBlock>(V);
4621 return false;
4622}
4623
Chris Lattnerac161bf2009-01-02 07:01:27 +00004624/// FunctionHeader
4625/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004626/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004627/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4629 // Parse the linkage.
4630 LocTy LinkageLoc = Lex.getLoc();
4631 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004632
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004633 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004634 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004635 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004636 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004637 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004638 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004639 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004640 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4641 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004642 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 return true;
4644
4645 // Verify that the linkage is ok.
4646 switch ((GlobalValue::LinkageTypes)Linkage) {
4647 case GlobalValue::ExternalLinkage:
4648 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004649 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004650 if (isDefine)
4651 return Error(LinkageLoc, "invalid linkage for function definition");
4652 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004653 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004655 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004656 case GlobalValue::LinkOnceAnyLinkage:
4657 case GlobalValue::LinkOnceODRLinkage:
4658 case GlobalValue::WeakAnyLinkage:
4659 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004660 if (!isDefine)
4661 return Error(LinkageLoc, "invalid linkage for function declaration");
4662 break;
4663 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004664 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 return Error(LinkageLoc, "invalid function linkage type");
4666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004667
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004668 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4669 return Error(LinkageLoc,
4670 "symbol with local linkage must have default visibility");
4671
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004672 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004674
Chris Lattnerac161bf2009-01-02 07:01:27 +00004675 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004676
4677 std::string FunctionName;
4678 if (Lex.getKind() == lltok::GlobalVar) {
4679 FunctionName = Lex.getStrVal();
4680 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4681 unsigned NameID = Lex.getUIntVal();
4682
4683 if (NameID != NumberedVals.size())
4684 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004685 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004686 } else {
4687 return TokError("expected function name");
4688 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004689
Chris Lattner3822f632009-01-02 08:05:26 +00004690 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004691
Chris Lattner3822f632009-01-02 08:05:26 +00004692 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004693 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004694
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004695 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004697 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004698 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004699 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004701 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004702 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004703 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004704 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004705 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004706 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004707 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004708 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004709
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004710 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004711 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004712 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004713 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004714 (EatIfPresent(lltok::kw_section) &&
4715 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004716 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004717 ParseOptionalAlignment(Alignment) ||
4718 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004719 ParseStringConstant(GC)) ||
4720 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004721 ParseGlobalTypeAndValue(Prefix)) ||
4722 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004723 ParseGlobalTypeAndValue(Prologue)) ||
4724 (EatIfPresent(lltok::kw_personality) &&
4725 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004726 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727
Michael Gottesman41748d72013-06-27 00:25:01 +00004728 if (FuncAttrs.contains(Attribute::Builtin))
4729 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004730
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004732 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004733 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004734 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004735 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004736
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 // Okay, if we got here, the function is syntactically valid. Convert types
4738 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004739 std::vector<Type*> ParamTypeList;
Reid Klecknerb5180542017-03-21 16:57:19 +00004740 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004741
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004742 if (RetAttrs.hasAttributes())
Reid Klecknerb5180542017-03-21 16:57:19 +00004743 Attrs.push_back(AttributeList::get(RetType->getContext(),
4744 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004745
Chris Lattnerac161bf2009-01-02 07:01:27 +00004746 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004747 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004748 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4749 AttrBuilder B(ArgList[i].Attrs, i + 1);
Reid Klecknerb5180542017-03-21 16:57:19 +00004750 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
Bill Wendlingf5075a42013-01-27 02:24:02 +00004751 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752 }
4753
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004754 if (FuncAttrs.hasAttributes())
Reid Klecknerb5180542017-03-21 16:57:19 +00004755 Attrs.push_back(AttributeList::get(
4756 RetType->getContext(), AttributeList::FunctionIndex, FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757
Reid Klecknerb5180542017-03-21 16:57:19 +00004758 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Bill Wendling749a43d2012-12-30 13:50:49 +00004760 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4762
Chris Lattner229907c2011-07-18 04:54:35 +00004763 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004764 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004765 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004766
Craig Topper2617dcc2014-04-15 06:32:26 +00004767 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004768 if (!FunctionName.empty()) {
4769 // If this was a definition of a forward reference, remove the definition
4770 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004771 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772 if (FRVI != ForwardRefVals.end()) {
4773 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004774 if (!Fn)
4775 return Error(FRVI->second.second, "invalid forward reference to "
4776 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004777 if (Fn->getType() != PFT)
4778 return Error(FRVI->second.second, "invalid forward reference to "
4779 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004780
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 ForwardRefVals.erase(FRVI);
4782 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004783 // Reject redefinitions.
4784 return Error(NameLoc, "invalid redefinition of function '" +
4785 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004786 } else if (M->getNamedValue(FunctionName)) {
4787 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Dan Gohman399d6ae2009-08-29 23:37:49 +00004790 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004791 // If this is a definition of a forward referenced function, make sure the
4792 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004793 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 if (I != ForwardRefValIDs.end()) {
4795 Fn = cast<Function>(I->second.first);
4796 if (Fn->getType() != PFT)
4797 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004798 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004799 ForwardRefValIDs.erase(I);
4800 }
4801 }
4802
Craig Topper2617dcc2014-04-15 06:32:26 +00004803 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4805 else // Move the forward-reference to the correct spot in the module.
4806 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4807
4808 if (FunctionName.empty())
4809 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004810
Chris Lattnerac161bf2009-01-02 07:01:27 +00004811 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4812 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004813 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 Fn->setCallingConv(CC);
4815 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004816 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 Fn->setAlignment(Alignment);
4818 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004819 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004820 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004821 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004822 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004823 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004824 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004825
Chris Lattnerac161bf2009-01-02 07:01:27 +00004826 // Add all of the arguments we parsed to the function.
4827 Function::arg_iterator ArgIt = Fn->arg_begin();
4828 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4829 // If the argument has a name, insert it into the argument symbol table.
4830 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004831
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 // Set the name, if it conflicted, it will be auto-renamed.
4833 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004834
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004835 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004836 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4837 ArgList[i].Name + "'");
4838 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004839
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004840 if (isDefine)
4841 return false;
4842
Robin Morisset039781e2014-08-29 21:53:01 +00004843 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004844 ValID ID;
4845 if (FunctionName.empty()) {
4846 ID.Kind = ValID::t_GlobalID;
4847 ID.UIntVal = NumberedVals.size() - 1;
4848 } else {
4849 ID.Kind = ValID::t_GlobalName;
4850 ID.StrVal = FunctionName;
4851 }
4852 auto Blocks = ForwardRefBlockAddresses.find(ID);
4853 if (Blocks != ForwardRefBlockAddresses.end())
4854 return Error(Blocks->first.Loc,
4855 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004856 return false;
4857}
4858
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004859bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4860 ValID ID;
4861 if (FunctionNumber == -1) {
4862 ID.Kind = ValID::t_GlobalName;
4863 ID.StrVal = F.getName();
4864 } else {
4865 ID.Kind = ValID::t_GlobalID;
4866 ID.UIntVal = FunctionNumber;
4867 }
4868
4869 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4870 if (Blocks == P.ForwardRefBlockAddresses.end())
4871 return false;
4872
4873 for (const auto &I : Blocks->second) {
4874 const ValID &BBID = I.first;
4875 GlobalValue *GV = I.second;
4876
4877 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4878 "Expected local id or name");
4879 BasicBlock *BB;
4880 if (BBID.Kind == ValID::t_LocalName)
4881 BB = GetBB(BBID.StrVal, BBID.Loc);
4882 else
4883 BB = GetBB(BBID.UIntVal, BBID.Loc);
4884 if (!BB)
4885 return P.Error(BBID.Loc, "referenced value is not a basic block");
4886
4887 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4888 GV->eraseFromParent();
4889 }
4890
4891 P.ForwardRefBlockAddresses.erase(Blocks);
4892 return false;
4893}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894
4895/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004896/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004897bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004898 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004899 return TokError("expected '{' in function body");
4900 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004901
Chris Lattner3432c622009-10-28 03:39:23 +00004902 int FunctionNumber = -1;
4903 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004904
Chris Lattner3432c622009-10-28 03:39:23 +00004905 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004906
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004907 // Resolve block addresses and allow basic blocks to be forward-declared
4908 // within this function.
4909 if (PFS.resolveForwardRefBlockAddresses())
4910 return true;
4911 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4912
Chris Lattnerbbddd962010-01-09 19:20:07 +00004913 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004914 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004915 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004916
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004917 while (Lex.getKind() != lltok::rbrace &&
4918 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004920
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004921 while (Lex.getKind() != lltok::rbrace)
4922 if (ParseUseListOrder(&PFS))
4923 return true;
4924
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 // Eat the }.
4926 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004927
Chris Lattnerac161bf2009-01-02 07:01:27 +00004928 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004929 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004930}
4931
4932/// ParseBasicBlock
4933/// ::= LabelStr? Instruction*
4934bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4935 // If this basic block starts out with a name, remember it.
4936 std::string Name;
4937 LocTy NameLoc = Lex.getLoc();
4938 if (Lex.getKind() == lltok::LabelStr) {
4939 Name = Lex.getStrVal();
4940 Lex.Lex();
4941 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004942
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004944 if (!BB)
4945 return Error(NameLoc,
4946 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004947
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004949
Chris Lattnerac161bf2009-01-02 07:01:27 +00004950 // Parse the instructions in this block until we get a terminator.
4951 Instruction *Inst;
4952 do {
4953 // This instruction may have three possibilities for a name: a) none
4954 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4955 LocTy NameLoc = Lex.getLoc();
4956 int NameID = -1;
4957 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004958
Chris Lattnerac161bf2009-01-02 07:01:27 +00004959 if (Lex.getKind() == lltok::LocalVarID) {
4960 NameID = Lex.getUIntVal();
4961 Lex.Lex();
4962 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4963 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004964 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965 NameStr = Lex.getStrVal();
4966 Lex.Lex();
4967 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4968 return true;
4969 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004970
Chris Lattner77b89dc2009-12-30 05:23:43 +00004971 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004972 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004973 case InstError: return true;
4974 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004975 BB->getInstList().push_back(Inst);
4976
Chris Lattner77b89dc2009-12-30 05:23:43 +00004977 // With a normal result, we check to see if the instruction is followed by
4978 // a comma and metadata.
4979 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004980 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004981 return true;
4982 break;
4983 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004984 BB->getInstList().push_back(Inst);
4985
Chris Lattner77b89dc2009-12-30 05:23:43 +00004986 // If the instruction parser ate an extra comma at the end of it, it
4987 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004988 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004989 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004990 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004991 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004992
Chris Lattnerac161bf2009-01-02 07:01:27 +00004993 // Set the name on the instruction.
4994 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4995 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004996
Chris Lattnerac161bf2009-01-02 07:01:27 +00004997 return false;
4998}
4999
5000//===----------------------------------------------------------------------===//
5001// Instruction Parsing.
5002//===----------------------------------------------------------------------===//
5003
5004/// ParseInstruction - Parse one of the many different instructions.
5005///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005006int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5007 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005008 lltok::Kind Token = Lex.getKind();
5009 if (Token == lltok::Eof)
5010 return TokError("found end of file when expecting more instructions");
5011 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005012 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005013 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005014
Chris Lattnerac161bf2009-01-02 07:01:27 +00005015 switch (Token) {
5016 default: return Error(Loc, "expected instruction opcode");
5017 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005018 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005019 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5020 case lltok::kw_br: return ParseBr(Inst, PFS);
5021 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005022 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005023 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005024 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005025 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5026 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005027 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5028 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005029 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005030 // Binary Operators.
5031 case lltok::kw_add:
5032 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005033 case lltok::kw_mul:
5034 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005035 bool NUW = EatIfPresent(lltok::kw_nuw);
5036 bool NSW = EatIfPresent(lltok::kw_nsw);
5037 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005038
Chris Lattnera676c0f2011-02-07 16:40:21 +00005039 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005040
Chris Lattnera676c0f2011-02-07 16:40:21 +00005041 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5042 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5043 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005044 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005045 case lltok::kw_fadd:
5046 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005047 case lltok::kw_fmul:
5048 case lltok::kw_fdiv:
5049 case lltok::kw_frem: {
5050 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5051 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5052 if (Res != 0)
5053 return Res;
5054 if (FMF.any())
5055 Inst->setFastMathFlags(FMF);
5056 return 0;
5057 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005058
Chris Lattner35315d02011-02-06 21:44:57 +00005059 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005060 case lltok::kw_udiv:
5061 case lltok::kw_lshr:
5062 case lltok::kw_ashr: {
5063 bool Exact = EatIfPresent(lltok::kw_exact);
5064
5065 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5066 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5067 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005068 }
5069
Chris Lattnerac161bf2009-01-02 07:01:27 +00005070 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005071 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 case lltok::kw_and:
5073 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005074 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005075 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5076 case lltok::kw_fcmp: {
5077 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5078 int Res = ParseCompare(Inst, PFS, KeywordVal);
5079 if (Res != 0)
5080 return Res;
5081 if (FMF.any())
5082 Inst->setFastMathFlags(FMF);
5083 return 0;
5084 }
5085
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 // Casts.
5087 case lltok::kw_trunc:
5088 case lltok::kw_zext:
5089 case lltok::kw_sext:
5090 case lltok::kw_fptrunc:
5091 case lltok::kw_fpext:
5092 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005093 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005094 case lltok::kw_uitofp:
5095 case lltok::kw_sitofp:
5096 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005097 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005098 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005099 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005100 // Other.
5101 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005102 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5104 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5105 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5106 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005107 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005108 // Call.
5109 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5110 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5111 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005112 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005114 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005115 case lltok::kw_load: return ParseLoad(Inst, PFS);
5116 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005117 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5118 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005119 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005120 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5121 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5122 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5123 }
5124}
5125
5126/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5127bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005128 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005130 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005131 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5132 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5133 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5134 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5135 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5136 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5137 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5138 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5139 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5140 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5141 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5142 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5143 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5144 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5145 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5146 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5147 }
5148 } else {
5149 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005150 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005151 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5152 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5153 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5154 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5155 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5156 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5157 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5158 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5159 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5160 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5161 }
5162 }
5163 Lex.Lex();
5164 return false;
5165}
5166
5167//===----------------------------------------------------------------------===//
5168// Terminator Instructions.
5169//===----------------------------------------------------------------------===//
5170
5171/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005172/// ::= 'ret' void (',' !dbg, !1)*
5173/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005174bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005175 PerFunctionState &PFS) {
5176 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005177 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005178 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005179
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005180 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005181
Chris Lattnerfdd87902009-10-05 05:54:46 +00005182 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005183 if (!ResType->isVoidTy())
5184 return Error(TypeLoc, "value doesn't match function result type '" +
5185 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005186
Owen Anderson55f1c092009-08-13 21:58:54 +00005187 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005188 return false;
5189 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005190
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191 Value *RV;
5192 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005194 if (ResType != RV->getType())
5195 return Error(TypeLoc, "value doesn't match function result type '" +
5196 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005197
Owen Anderson55f1c092009-08-13 21:58:54 +00005198 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005199 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005200}
5201
Chris Lattnerac161bf2009-01-02 07:01:27 +00005202/// ParseBr
5203/// ::= 'br' TypeAndValue
5204/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5205bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5206 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005207 Value *Op0;
5208 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005210
Chris Lattnerac161bf2009-01-02 07:01:27 +00005211 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5212 Inst = BranchInst::Create(BB);
5213 return false;
5214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215
Owen Anderson55f1c092009-08-13 21:58:54 +00005216 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005218
Chris Lattnerac161bf2009-01-02 07:01:27 +00005219 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005220 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005222 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005224
Chris Lattner3ed871f2009-10-27 19:13:16 +00005225 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005226 return false;
5227}
5228
5229/// ParseSwitch
5230/// Instruction
5231/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5232/// JumpTable
5233/// ::= (TypeAndValue ',' TypeAndValue)*
5234bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5235 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005236 Value *Cond;
5237 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5239 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005240 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5242 return true;
5243
Duncan Sands19d0b472010-02-16 11:11:14 +00005244 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005246
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 // Parse the jump table pairs.
5248 SmallPtrSet<Value*, 32> SeenCases;
5249 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5250 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005251 Value *Constant;
5252 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005253
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5255 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005256 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005258
David Blaikie70573dc2014-11-19 07:49:26 +00005259 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 return Error(CondLoc, "duplicate case value in switch");
5261 if (!isa<ConstantInt>(Constant))
5262 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005263
Chris Lattner3ed871f2009-10-27 19:13:16 +00005264 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005266
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005268
Chris Lattner3ed871f2009-10-27 19:13:16 +00005269 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5271 SI->addCase(Table[i].first, Table[i].second);
5272 Inst = SI;
5273 return false;
5274}
5275
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005276/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005277/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005278/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5279bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005280 LocTy AddrLoc;
5281 Value *Address;
5282 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005283 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5284 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005285 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005286
Duncan Sands19d0b472010-02-16 11:11:14 +00005287 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005288 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005289
Chris Lattner3ed871f2009-10-27 19:13:16 +00005290 // Parse the destination list.
5291 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005292
Chris Lattner3ed871f2009-10-27 19:13:16 +00005293 if (Lex.getKind() != lltok::rsquare) {
5294 BasicBlock *DestBB;
5295 if (ParseTypeAndBasicBlock(DestBB, PFS))
5296 return true;
5297 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005298
Chris Lattner3ed871f2009-10-27 19:13:16 +00005299 while (EatIfPresent(lltok::comma)) {
5300 if (ParseTypeAndBasicBlock(DestBB, PFS))
5301 return true;
5302 DestList.push_back(DestBB);
5303 }
5304 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005305
Chris Lattner3ed871f2009-10-27 19:13:16 +00005306 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5307 return true;
5308
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005309 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005310 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5311 IBI->addDestination(DestList[i]);
5312 Inst = IBI;
5313 return false;
5314}
5315
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316/// ParseInvoke
5317/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5318/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5319bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5320 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005321 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005322 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005323 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005324 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005325 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005326 LocTy RetTypeLoc;
5327 ValID CalleeID;
5328 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005329 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005330
Chris Lattner3ed871f2009-10-27 19:13:16 +00005331 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005332 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005333 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005334 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005335 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5336 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005337 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005338 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005339 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005340 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005341 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005342 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005343
Chris Lattnerac161bf2009-01-02 07:01:27 +00005344 // If RetType is a non-function pointer type, then this is the short syntax
5345 // for the call, which means that RetType is just the return type. Infer the
5346 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005347 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5348 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005349 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005350 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5352 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005353
Chris Lattnerac161bf2009-01-02 07:01:27 +00005354 if (!FunctionType::isValidReturnType(RetType))
5355 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005356
Owen Anderson4056ca92009-07-29 22:17:13 +00005357 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005358 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005359
David Blaikie41ba2b42015-07-27 23:32:19 +00005360 CalleeID.FTy = Ty;
5361
Chris Lattnerac161bf2009-01-02 07:01:27 +00005362 // Look up the callee.
5363 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005364 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5365 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005366
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005367 // Set up the Attribute for the function.
Reid Klecknerb5180542017-03-21 16:57:19 +00005368 SmallVector<AttributeList, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005369 if (RetAttrs.hasAttributes())
Reid Klecknerb5180542017-03-21 16:57:19 +00005370 Attrs.push_back(AttributeList::get(RetType->getContext(),
5371 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005372
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 // Loop through FunctionType's arguments and ensure they are specified
5376 // correctly. Also, gather any parameter attributes.
5377 FunctionType::param_iterator I = Ty->param_begin();
5378 FunctionType::param_iterator E = Ty->param_end();
5379 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005380 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 if (I != E) {
5382 ExpectedTy = *I++;
5383 } else if (!Ty->isVarArg()) {
5384 return Error(ArgList[i].Loc, "too many arguments specified");
5385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005386
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5388 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005389 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005390 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005391 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5392 AttrBuilder B(ArgList[i].Attrs, i + 1);
Reid Klecknerb5180542017-03-21 16:57:19 +00005393 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
Bill Wendlingf5075a42013-01-27 02:24:02 +00005394 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005395 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005396
Chris Lattnerac161bf2009-01-02 07:01:27 +00005397 if (I != E)
5398 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005399
David Majnemer8d22abd2015-02-23 00:01:32 +00005400 if (FnAttrs.hasAttributes()) {
5401 if (FnAttrs.hasAlignmentAttr())
5402 return Error(CallLoc, "invoke instructions may not have an alignment");
5403
Reid Klecknerb5180542017-03-21 16:57:19 +00005404 Attrs.push_back(AttributeList::get(RetType->getContext(),
5405 AttributeList::FunctionIndex, FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005406 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005407
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005408 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00005409 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005410
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005411 InvokeInst *II =
5412 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413 II->setCallingConv(CC);
5414 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005415 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005416 Inst = II;
5417 return false;
5418}
5419
Bill Wendlingf891bf82011-07-31 06:30:59 +00005420/// ParseResume
5421/// ::= 'resume' TypeAndValue
5422bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5423 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005424 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5425 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005426
Bill Wendlingf891bf82011-07-31 06:30:59 +00005427 ResumeInst *RI = ResumeInst::Create(Exn);
5428 Inst = RI;
5429 return false;
5430}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005431
David Majnemer654e1302015-07-31 17:58:14 +00005432bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5433 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005434 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005435 return true;
5436
5437 while (Lex.getKind() != lltok::rsquare) {
5438 // If this isn't the first argument, we need a comma.
5439 if (!Args.empty() &&
5440 ParseToken(lltok::comma, "expected ',' in argument list"))
5441 return true;
5442
5443 // Parse the argument.
5444 LocTy ArgLoc;
5445 Type *ArgTy = nullptr;
5446 if (ParseType(ArgTy, ArgLoc))
5447 return true;
5448
5449 Value *V;
5450 if (ArgTy->isMetadataTy()) {
5451 if (ParseMetadataAsValue(V, PFS))
5452 return true;
5453 } else {
5454 if (ParseValue(ArgTy, V, PFS))
5455 return true;
5456 }
5457 Args.push_back(V);
5458 }
5459
5460 Lex.Lex(); // Lex the ']'.
5461 return false;
5462}
5463
5464/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005465/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005466bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005467 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005468
David Majnemer8a1c45d2015-12-12 05:38:55 +00005469 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5470 return true;
5471
5472 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005473 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005474
5475 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5476 return true;
5477
5478 BasicBlock *UnwindBB = nullptr;
5479 if (Lex.getKind() == lltok::kw_to) {
5480 Lex.Lex();
5481 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5482 return true;
5483 } else {
5484 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5485 return true;
5486 }
5487 }
5488
David Majnemer8a1c45d2015-12-12 05:38:55 +00005489 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005490 return false;
5491}
5492
5493/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005494/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005495bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005496 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005497
David Majnemer8a1c45d2015-12-12 05:38:55 +00005498 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5499 return true;
5500
5501 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005502 return true;
5503
David Majnemer0bc0eef2015-08-15 02:46:08 +00005504 BasicBlock *BB;
5505 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5506 ParseTypeAndBasicBlock(BB, PFS))
5507 return true;
5508
David Majnemer8a1c45d2015-12-12 05:38:55 +00005509 Inst = CatchReturnInst::Create(CatchPad, BB);
5510 return false;
5511}
5512
5513/// ParseCatchSwitch
5514/// ::= 'catchswitch' within Parent
5515bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5516 Value *ParentPad;
5517 LocTy BBLoc;
5518
5519 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5520 return true;
5521
5522 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5523 Lex.getKind() != lltok::LocalVarID)
5524 return TokError("expected scope value for catchswitch");
5525
5526 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5527 return true;
5528
5529 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5530 return true;
5531
5532 SmallVector<BasicBlock *, 32> Table;
5533 do {
5534 BasicBlock *DestBB;
5535 if (ParseTypeAndBasicBlock(DestBB, PFS))
5536 return true;
5537 Table.push_back(DestBB);
5538 } while (EatIfPresent(lltok::comma));
5539
5540 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5541 return true;
5542
5543 if (ParseToken(lltok::kw_unwind,
5544 "expected 'unwind' after catchswitch scope"))
5545 return true;
5546
5547 BasicBlock *UnwindBB = nullptr;
5548 if (EatIfPresent(lltok::kw_to)) {
5549 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5550 return true;
5551 } else {
5552 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5553 return true;
5554 }
5555
5556 auto *CatchSwitch =
5557 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5558 for (BasicBlock *DestBB : Table)
5559 CatchSwitch->addHandler(DestBB);
5560 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005561 return false;
5562}
5563
5564/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005565/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005566bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005567 Value *CatchSwitch = nullptr;
5568
5569 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5570 return true;
5571
5572 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5573 return TokError("expected scope value for catchpad");
5574
5575 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5576 return true;
5577
David Majnemer654e1302015-07-31 17:58:14 +00005578 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005579 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005580 return true;
5581
David Majnemer8a1c45d2015-12-12 05:38:55 +00005582 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005583 return false;
5584}
5585
David Majnemer654e1302015-07-31 17:58:14 +00005586/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005587/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005588bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005589 Value *ParentPad = nullptr;
5590
5591 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5592 return true;
5593
5594 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5595 Lex.getKind() != lltok::LocalVarID)
5596 return TokError("expected scope value for cleanuppad");
5597
5598 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5599 return true;
5600
David Majnemer654e1302015-07-31 17:58:14 +00005601 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005602 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005603 return true;
5604
David Majnemer8a1c45d2015-12-12 05:38:55 +00005605 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005606 return false;
5607}
5608
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609//===----------------------------------------------------------------------===//
5610// Binary Operators.
5611//===----------------------------------------------------------------------===//
5612
5613/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005614/// ::= ArithmeticOps TypeAndValue ',' Value
5615///
5616/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5617/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005618bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005619 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005620 LocTy Loc; Value *LHS, *RHS;
5621 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5622 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5623 ParseValue(LHS->getType(), RHS, PFS))
5624 return true;
5625
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005626 bool Valid;
5627 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005628 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005629 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005630 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5631 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005632 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005633 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5634 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005636
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005637 if (!Valid)
5638 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005639
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5641 return false;
5642}
5643
5644/// ParseLogical
5645/// ::= ArithmeticOps TypeAndValue ',' Value {
5646bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5647 unsigned Opc) {
5648 LocTy Loc; Value *LHS, *RHS;
5649 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5650 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5651 ParseValue(LHS->getType(), RHS, PFS))
5652 return true;
5653
Duncan Sands9dff9be2010-02-15 16:12:20 +00005654 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005655 return Error(Loc,"instruction requires integer or integer vector operands");
5656
5657 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5658 return false;
5659}
5660
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661/// ParseCompare
5662/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5663/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5665 unsigned Opc) {
5666 // Parse the integer/fp comparison predicate.
5667 LocTy Loc;
5668 unsigned Pred;
5669 Value *LHS, *RHS;
5670 if (ParseCmpPredicate(Pred, Opc) ||
5671 ParseTypeAndValue(LHS, Loc, PFS) ||
5672 ParseToken(lltok::comma, "expected ',' after compare value") ||
5673 ParseValue(LHS->getType(), RHS, PFS))
5674 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005677 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005679 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005680 } else {
5681 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005682 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005683 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005685 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005686 }
5687 return false;
5688}
5689
5690//===----------------------------------------------------------------------===//
5691// Other Instructions.
5692//===----------------------------------------------------------------------===//
5693
5694
5695/// ParseCast
5696/// ::= CastOpc TypeAndValue 'to' Type
5697bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5698 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005699 LocTy Loc;
5700 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005701 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005702 if (ParseTypeAndValue(Op, Loc, PFS) ||
5703 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5704 ParseType(DestTy))
5705 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005706
Chris Lattner89d856e2009-03-01 00:53:13 +00005707 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5708 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005709 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005710 getTypeString(Op->getType()) + "' to '" +
5711 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005712 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005713 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5714 return false;
5715}
5716
5717/// ParseSelect
5718/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5719bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5720 LocTy Loc;
5721 Value *Op0, *Op1, *Op2;
5722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5723 ParseToken(lltok::comma, "expected ',' after select condition") ||
5724 ParseTypeAndValue(Op1, PFS) ||
5725 ParseToken(lltok::comma, "expected ',' after select value") ||
5726 ParseTypeAndValue(Op2, PFS))
5727 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005728
Chris Lattnerac161bf2009-01-02 07:01:27 +00005729 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5730 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005731
Chris Lattnerac161bf2009-01-02 07:01:27 +00005732 Inst = SelectInst::Create(Op0, Op1, Op2);
5733 return false;
5734}
5735
Chris Lattnerb55ab542009-01-05 08:18:44 +00005736/// ParseVA_Arg
5737/// ::= 'va_arg' TypeAndValue ',' Type
5738bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005739 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005740 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005741 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005742 if (ParseTypeAndValue(Op, PFS) ||
5743 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005744 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005746
Chris Lattnerb55ab542009-01-05 08:18:44 +00005747 if (!EltTy->isFirstClassType())
5748 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005749
5750 Inst = new VAArgInst(Op, EltTy);
5751 return false;
5752}
5753
5754/// ParseExtractElement
5755/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5756bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5757 LocTy Loc;
5758 Value *Op0, *Op1;
5759 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5760 ParseToken(lltok::comma, "expected ',' after extract value") ||
5761 ParseTypeAndValue(Op1, PFS))
5762 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005763
Chris Lattnerac161bf2009-01-02 07:01:27 +00005764 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5765 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005766
Eric Christopherc9742252009-07-25 02:28:41 +00005767 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005768 return false;
5769}
5770
5771/// ParseInsertElement
5772/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5773bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5774 LocTy Loc;
5775 Value *Op0, *Op1, *Op2;
5776 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5777 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5778 ParseTypeAndValue(Op1, PFS) ||
5779 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5780 ParseTypeAndValue(Op2, PFS))
5781 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005782
Chris Lattnerac161bf2009-01-02 07:01:27 +00005783 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005784 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005785
Chris Lattnerac161bf2009-01-02 07:01:27 +00005786 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5787 return false;
5788}
5789
5790/// ParseShuffleVector
5791/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5792bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5793 LocTy Loc;
5794 Value *Op0, *Op1, *Op2;
5795 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5796 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5797 ParseTypeAndValue(Op1, PFS) ||
5798 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5799 ParseTypeAndValue(Op2, PFS))
5800 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005801
Chris Lattnerac161bf2009-01-02 07:01:27 +00005802 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005803 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005804
Chris Lattnerac161bf2009-01-02 07:01:27 +00005805 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5806 return false;
5807}
5808
5809/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005810/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005811int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005812 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005814
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005815 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5817 ParseValue(Ty, Op0, PFS) ||
5818 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005819 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005820 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5821 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005822
Chris Lattnerf4f03422009-12-30 05:27:33 +00005823 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005824 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005825
5826 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005827 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005828
Chris Lattner3822f632009-01-02 08:05:26 +00005829 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830 break;
5831
Chris Lattnerf4f03422009-12-30 05:27:33 +00005832 if (Lex.getKind() == lltok::MetadataVar) {
5833 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005834 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005835 }
Devang Patel8f842d32009-10-16 18:45:49 +00005836
Chris Lattner3822f632009-01-02 08:05:26 +00005837 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005838 ParseValue(Ty, Op0, PFS) ||
5839 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005840 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5842 return true;
5843 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005844
Chris Lattnerac161bf2009-01-02 07:01:27 +00005845 if (!Ty->isFirstClassType())
5846 return Error(TypeLoc, "phi node must have first class type");
5847
Jay Foad52131342011-03-30 11:28:46 +00005848 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005849 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5850 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5851 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005852 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853}
5854
Bill Wendlingfae14752011-08-12 20:24:12 +00005855/// ParseLandingPad
5856/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5857/// Clause
5858/// ::= 'catch' TypeAndValue
5859/// ::= 'filter'
5860/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5861bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005862 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005863
David Majnemer7fddecc2015-06-17 20:52:32 +00005864 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005865 return true;
5866
David Majnemer7fddecc2015-06-17 20:52:32 +00005867 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005868 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5869
5870 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5871 LandingPadInst::ClauseType CT;
5872 if (EatIfPresent(lltok::kw_catch))
5873 CT = LandingPadInst::Catch;
5874 else if (EatIfPresent(lltok::kw_filter))
5875 CT = LandingPadInst::Filter;
5876 else
5877 return TokError("expected 'catch' or 'filter' clause type");
5878
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005879 Value *V;
5880 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005881 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005882 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005883
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005884 // A 'catch' type expects a non-array constant. A filter clause expects an
5885 // array constant.
5886 if (CT == LandingPadInst::Catch) {
5887 if (isa<ArrayType>(V->getType()))
5888 Error(VLoc, "'catch' clause has an invalid type");
5889 } else {
5890 if (!isa<ArrayType>(V->getType()))
5891 Error(VLoc, "'filter' clause has an invalid type");
5892 }
5893
Owen Andersonf8f259d2015-03-09 07:13:42 +00005894 Constant *CV = dyn_cast<Constant>(V);
5895 if (!CV)
5896 return Error(VLoc, "clause argument must be a constant");
5897 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005898 }
5899
Owen Andersonf8f259d2015-03-09 07:13:42 +00005900 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005901 return false;
5902}
5903
Chris Lattnerac161bf2009-01-02 07:01:27 +00005904/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005905/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5906/// OptionalAttrs Type Value ParameterList OptionalAttrs
5907/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5908/// OptionalAttrs Type Value ParameterList OptionalAttrs
5909/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5910/// OptionalAttrs Type Value ParameterList OptionalAttrs
5911/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5912/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005913bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005914 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005915 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005916 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005917 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005918 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005919 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005920 LocTy RetTypeLoc;
5921 ValID CalleeID;
5922 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005923 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005924 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005925
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005926 if (TCK != CallInst::TCK_None &&
5927 ParseToken(lltok::kw_call,
5928 "expected 'tail call', 'musttail call', or 'notail call'"))
5929 return true;
5930
5931 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5932
5933 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005934 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005935 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005936 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5937 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005938 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5939 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005940 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005941
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005942 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5943 return Error(CallLoc, "fast-math-flags specified for call without "
5944 "floating-point scalar or vector return type");
5945
Chris Lattnerac161bf2009-01-02 07:01:27 +00005946 // If RetType is a non-function pointer type, then this is the short syntax
5947 // for the call, which means that RetType is just the return type. Infer the
5948 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005949 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5950 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005951 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005952 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005953 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5954 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005955
Chris Lattnerac161bf2009-01-02 07:01:27 +00005956 if (!FunctionType::isValidReturnType(RetType))
5957 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005958
Owen Anderson4056ca92009-07-29 22:17:13 +00005959 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005961
David Blaikie41ba2b42015-07-27 23:32:19 +00005962 CalleeID.FTy = Ty;
5963
Chris Lattnerac161bf2009-01-02 07:01:27 +00005964 // Look up the callee.
5965 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005966 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5967 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005968
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005969 // Set up the Attribute for the function.
Reid Klecknerb5180542017-03-21 16:57:19 +00005970 SmallVector<AttributeList, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005971 if (RetAttrs.hasAttributes())
Reid Klecknerb5180542017-03-21 16:57:19 +00005972 Attrs.push_back(AttributeList::get(RetType->getContext(),
5973 AttributeList::ReturnIndex, RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005974
Chris Lattnerac161bf2009-01-02 07:01:27 +00005975 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 // Loop through FunctionType's arguments and ensure they are specified
5978 // correctly. Also, gather any parameter attributes.
5979 FunctionType::param_iterator I = Ty->param_begin();
5980 FunctionType::param_iterator E = Ty->param_end();
5981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005982 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005983 if (I != E) {
5984 ExpectedTy = *I++;
5985 } else if (!Ty->isVarArg()) {
5986 return Error(ArgList[i].Loc, "too many arguments specified");
5987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005988
Chris Lattnerac161bf2009-01-02 07:01:27 +00005989 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5990 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005991 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005993 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5994 AttrBuilder B(ArgList[i].Attrs, i + 1);
Reid Klecknerb5180542017-03-21 16:57:19 +00005995 Attrs.push_back(AttributeList::get(RetType->getContext(), i + 1, B));
Bill Wendlingf5075a42013-01-27 02:24:02 +00005996 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005997 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005998
Chris Lattnerac161bf2009-01-02 07:01:27 +00005999 if (I != E)
6000 return Error(CallLoc, "not enough parameters specified for call");
6001
David Majnemer8d22abd2015-02-23 00:01:32 +00006002 if (FnAttrs.hasAttributes()) {
6003 if (FnAttrs.hasAlignmentAttr())
6004 return Error(CallLoc, "call instructions may not have an alignment");
6005
Reid Klecknerb5180542017-03-21 16:57:19 +00006006 Attrs.push_back(AttributeList::get(RetType->getContext(),
6007 AttributeList::FunctionIndex, FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00006008 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006009
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006010 // Finish off the Attribute and check them
Reid Klecknerb5180542017-03-21 16:57:19 +00006011 AttributeList PAL = AttributeList::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006012
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006013 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006014 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006016 if (FMF.any())
6017 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006018 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006019 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006020 Inst = CI;
6021 return false;
6022}
6023
6024//===----------------------------------------------------------------------===//
6025// Memory Instructions.
6026//===----------------------------------------------------------------------===//
6027
6028/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006029/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6030/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006031int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006032 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00006033 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006034 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006035 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006036
6037 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006038 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006039
David Majnemera3b0eb22015-02-16 08:38:03 +00006040 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006041
David Majnemera3b0eb22015-02-16 08:38:03 +00006042 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6043 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006044
Chris Lattnerb2f39502009-12-30 05:44:30 +00006045 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006046 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006047 if (Lex.getKind() == lltok::kw_align) {
6048 if (ParseOptionalAlignment(Alignment)) return true;
6049 } else if (Lex.getKind() == lltok::MetadataVar) {
6050 AteExtraComma = true;
6051 } else {
6052 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6053 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6054 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006055 }
6056 }
6057
Dan Gohman2140a742010-05-28 01:14:11 +00006058 if (Size && !Size->getType()->isIntegerTy())
6059 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006060
Reid Kleckner436c42e2014-01-17 23:58:17 +00006061 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6062 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006063 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006064 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006065 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066}
6067
6068/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006069/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006070/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006071/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006072int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006073 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006074 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006075 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006076 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006077 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006078 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006079
6080 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006081 isAtomic = true;
6082 Lex.Lex();
6083 }
6084
Chris Lattnerbc639292011-11-27 06:56:53 +00006085 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006086 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006087 isVolatile = true;
6088 Lex.Lex();
6089 }
6090
David Blaikie15d9a4c2015-04-06 20:59:48 +00006091 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006092 LocTy ExplicitTypeLoc = Lex.getLoc();
6093 if (ParseType(Ty) ||
6094 ParseToken(lltok::comma, "expected comma after load's type") ||
6095 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006096 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006097 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6098 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006099
David Blaikie15d9a4c2015-04-06 20:59:48 +00006100 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006101 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006102 if (isAtomic && !Alignment)
6103 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006104 if (Ordering == AtomicOrdering::Release ||
6105 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006106 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006107
David Blaikiea79ac142015-02-27 21:17:42 +00006108 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6109 return Error(ExplicitTypeLoc,
6110 "explicit pointee type doesn't match operand's pointee type");
6111
David Blaikie15d9a4c2015-04-06 20:59:48 +00006112 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006113 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006114}
6115
6116/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006117
6118/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6119/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006120/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006121int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006122 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006123 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006124 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006125 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006126 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006127 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006128
6129 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006130 isAtomic = true;
6131 Lex.Lex();
6132 }
6133
Chris Lattnerbc639292011-11-27 06:56:53 +00006134 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006135 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006136 isVolatile = true;
6137 Lex.Lex();
6138 }
6139
Chris Lattnerac161bf2009-01-02 07:01:27 +00006140 if (ParseTypeAndValue(Val, Loc, PFS) ||
6141 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006142 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006143 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006144 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006145 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006146
Duncan Sands19d0b472010-02-16 11:11:14 +00006147 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006148 return Error(PtrLoc, "store operand must be a pointer");
6149 if (!Val->getType()->isFirstClassType())
6150 return Error(Loc, "store operand must be a first class value");
6151 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6152 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006153 if (isAtomic && !Alignment)
6154 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006155 if (Ordering == AtomicOrdering::Acquire ||
6156 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006157 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006158
Eli Friedman59b66882011-08-09 23:02:53 +00006159 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006160 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006161}
6162
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006163/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006164/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6165/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006166int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006167 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6168 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006169 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6170 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006171 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006172 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006173 bool isWeak = false;
6174
6175 if (EatIfPresent(lltok::kw_weak))
6176 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006177
6178 if (EatIfPresent(lltok::kw_volatile))
6179 isVolatile = true;
6180
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006181 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6182 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6183 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6184 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6185 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006186 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6187 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006188 return true;
6189
JF Bastien800f87a2016-04-06 21:19:33 +00006190 if (SuccessOrdering == AtomicOrdering::Unordered ||
6191 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006192 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006193 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6194 return TokError("cmpxchg failure argument shall be no stronger than the "
6195 "success argument");
6196 if (FailureOrdering == AtomicOrdering::Release ||
6197 FailureOrdering == AtomicOrdering::AcquireRelease)
6198 return TokError(
6199 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006200 if (!Ptr->getType()->isPointerTy())
6201 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6202 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6203 return Error(CmpLoc, "compare value and pointer type do not match");
6204 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6205 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006206 if (!New->getType()->isFirstClassType())
6207 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006208 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6209 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006210 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006211 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006212 Inst = CXI;
6213 return AteExtraComma ? InstExtraComma : InstNormal;
6214}
6215
6216/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006217/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6218/// 'singlethread'? AtomicOrdering
6219int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006220 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6221 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006222 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006223 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006224 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006225 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006226
6227 if (EatIfPresent(lltok::kw_volatile))
6228 isVolatile = true;
6229
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006230 switch (Lex.getKind()) {
6231 default: return TokError("expected binary operation in atomicrmw");
6232 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6233 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6234 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6235 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6236 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6237 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6238 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6239 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6240 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6241 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6242 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6243 }
6244 Lex.Lex(); // Eat the operation.
6245
6246 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6247 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6248 ParseTypeAndValue(Val, ValLoc, PFS) ||
6249 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6250 return true;
6251
JF Bastien800f87a2016-04-06 21:19:33 +00006252 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006253 return TokError("atomicrmw cannot be unordered");
6254 if (!Ptr->getType()->isPointerTy())
6255 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6256 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6257 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6258 if (!Val->getType()->isIntegerTy())
6259 return Error(ValLoc, "atomicrmw operand must be an integer");
6260 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6261 if (Size < 8 || (Size & (Size - 1)))
6262 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6263 " integer");
6264
6265 AtomicRMWInst *RMWI =
6266 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6267 RMWI->setVolatile(isVolatile);
6268 Inst = RMWI;
6269 return AteExtraComma ? InstExtraComma : InstNormal;
6270}
6271
Eli Friedmanfee02c62011-07-25 23:16:38 +00006272/// ParseFence
6273/// ::= 'fence' 'singlethread'? AtomicOrdering
6274int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006275 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006276 SynchronizationScope Scope = CrossThread;
6277 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6278 return true;
6279
JF Bastien800f87a2016-04-06 21:19:33 +00006280 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006281 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006282 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006283 return TokError("fence cannot be monotonic");
6284
6285 Inst = new FenceInst(Context, Ordering, Scope);
6286 return InstNormal;
6287}
6288
Chris Lattnerac161bf2009-01-02 07:01:27 +00006289/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006290/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006291int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006292 Value *Ptr = nullptr;
6293 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006294 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006295
Dan Gohman16cbbe42009-07-29 15:58:36 +00006296 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006297
David Blaikie79e6c742015-02-27 19:29:02 +00006298 Type *Ty = nullptr;
6299 LocTy ExplicitTypeLoc = Lex.getLoc();
6300 if (ParseType(Ty) ||
6301 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6302 ParseTypeAndValue(Ptr, Loc, PFS))
6303 return true;
6304
Eli Benderskyd9806682013-04-22 17:03:42 +00006305 Type *BaseType = Ptr->getType();
6306 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6307 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006308 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006309
David Blaikie8d757942015-03-09 23:08:44 +00006310 if (Ty != BasePointerType->getElementType())
6311 return Error(ExplicitTypeLoc,
6312 "explicit pointee type doesn't match operand's pointee type");
6313
Chris Lattnerac161bf2009-01-02 07:01:27 +00006314 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006315 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006316 // GEP returns a vector of pointers if at least one of parameters is a vector.
6317 // All vector parameters should have the same vector width.
6318 unsigned GEPWidth = BaseType->isVectorTy() ?
6319 BaseType->getVectorNumElements() : 0;
6320
Chris Lattner3822f632009-01-02 08:05:26 +00006321 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006322 if (Lex.getKind() == lltok::MetadataVar) {
6323 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006324 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006325 }
Chris Lattner3822f632009-01-02 08:05:26 +00006326 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006327 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006328 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006329
Nadav Rotem3924cb02011-12-05 06:29:09 +00006330 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006331 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6332 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006333 return Error(EltLoc,
6334 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006335 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006336 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006337 Indices.push_back(Val);
6338 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006339
Craig Toppere3dcce92015-08-01 22:20:21 +00006340 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006341 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006342 return Error(Loc, "base element of getelementptr must be sized");
6343
David Blaikied33bad32015-04-17 22:32:13 +00006344 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006345 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006346 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006347 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006348 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006349 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006350}
6351
6352/// ParseExtractValue
6353/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006354int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006355 Value *Val; LocTy Loc;
6356 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006357 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006358 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006359 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006360 return true;
6361
Chris Lattner392be582010-02-12 20:49:41 +00006362 if (!Val->getType()->isAggregateType())
6363 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006364
Jay Foad57aa6362011-07-13 10:26:04 +00006365 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006366 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006367 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006368 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006369}
6370
6371/// ParseInsertValue
6372/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006373int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006374 Value *Val0, *Val1; LocTy Loc0, Loc1;
6375 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006376 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006377 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6378 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6379 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006380 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006381 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006382
Chris Lattner392be582010-02-12 20:49:41 +00006383 if (!Val0->getType()->isAggregateType())
6384 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006385
David Majnemer30074532015-02-11 07:43:58 +00006386 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6387 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006388 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006389 if (IndexedType != Val1->getType())
6390 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6391 getTypeString(Val1->getType()) + "' instead of '" +
6392 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006393 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006394 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006395}
Nick Lewycky49f89192009-04-04 07:22:01 +00006396
6397//===----------------------------------------------------------------------===//
6398// Embedded metadata.
6399//===----------------------------------------------------------------------===//
6400
6401/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006402/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006403/// Element
6404/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006405bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006406 if (ParseToken(lltok::lbrace, "expected '{' here"))
6407 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006408
Dan Gohman1e0213a2010-07-13 19:33:27 +00006409 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006410 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006411 return false;
6412
Nick Lewycky49f89192009-04-04 07:22:01 +00006413 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006414 // Null is a special case since it is typeless.
6415 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006416 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006417 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006418 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006419
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006420 Metadata *MD;
6421 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006422 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006423 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006424 } while (EatIfPresent(lltok::comma));
6425
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006426 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006427}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006428
6429//===----------------------------------------------------------------------===//
6430// Use-list order directives.
6431//===----------------------------------------------------------------------===//
6432bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6433 SMLoc Loc) {
6434 if (V->use_empty())
6435 return Error(Loc, "value has no uses");
6436
6437 unsigned NumUses = 0;
6438 SmallDenseMap<const Use *, unsigned, 16> Order;
6439 for (const Use &U : V->uses()) {
6440 if (++NumUses > Indexes.size())
6441 break;
6442 Order[&U] = Indexes[NumUses - 1];
6443 }
6444 if (NumUses < 2)
6445 return Error(Loc, "value only has one use");
6446 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6447 return Error(Loc, "wrong number of indexes, expected " +
6448 Twine(std::distance(V->use_begin(), V->use_end())));
6449
6450 V->sortUseList([&](const Use &L, const Use &R) {
6451 return Order.lookup(&L) < Order.lookup(&R);
6452 });
6453 return false;
6454}
6455
6456/// ParseUseListOrderIndexes
6457/// ::= '{' uint32 (',' uint32)+ '}'
6458bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6459 SMLoc Loc = Lex.getLoc();
6460 if (ParseToken(lltok::lbrace, "expected '{' here"))
6461 return true;
6462 if (Lex.getKind() == lltok::rbrace)
6463 return Lex.Error("expected non-empty list of uselistorder indexes");
6464
6465 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6466 // indexes should be distinct numbers in the range [0, size-1], and should
6467 // not be in order.
6468 unsigned Offset = 0;
6469 unsigned Max = 0;
6470 bool IsOrdered = true;
6471 assert(Indexes.empty() && "Expected empty order vector");
6472 do {
6473 unsigned Index;
6474 if (ParseUInt32(Index))
6475 return true;
6476
6477 // Update consistency checks.
6478 Offset += Index - Indexes.size();
6479 Max = std::max(Max, Index);
6480 IsOrdered &= Index == Indexes.size();
6481
6482 Indexes.push_back(Index);
6483 } while (EatIfPresent(lltok::comma));
6484
6485 if (ParseToken(lltok::rbrace, "expected '}' here"))
6486 return true;
6487
6488 if (Indexes.size() < 2)
6489 return Error(Loc, "expected >= 2 uselistorder indexes");
6490 if (Offset != 0 || Max >= Indexes.size())
6491 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6492 if (IsOrdered)
6493 return Error(Loc, "expected uselistorder indexes to change the order");
6494
6495 return false;
6496}
6497
6498/// ParseUseListOrder
6499/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6500bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6501 SMLoc Loc = Lex.getLoc();
6502 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6503 return true;
6504
6505 Value *V;
6506 SmallVector<unsigned, 16> Indexes;
6507 if (ParseTypeAndValue(V, PFS) ||
6508 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6509 ParseUseListOrderIndexes(Indexes))
6510 return true;
6511
6512 return sortUseListOrder(V, Indexes, Loc);
6513}
6514
6515/// ParseUseListOrderBB
6516/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6517bool LLParser::ParseUseListOrderBB() {
6518 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6519 SMLoc Loc = Lex.getLoc();
6520 Lex.Lex();
6521
6522 ValID Fn, Label;
6523 SmallVector<unsigned, 16> Indexes;
6524 if (ParseValID(Fn) ||
6525 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6526 ParseValID(Label) ||
6527 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6528 ParseUseListOrderIndexes(Indexes))
6529 return true;
6530
6531 // Check the function.
6532 GlobalValue *GV;
6533 if (Fn.Kind == ValID::t_GlobalName)
6534 GV = M->getNamedValue(Fn.StrVal);
6535 else if (Fn.Kind == ValID::t_GlobalID)
6536 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6537 else
6538 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6539 if (!GV)
6540 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6541 auto *F = dyn_cast<Function>(GV);
6542 if (!F)
6543 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6544 if (F->isDeclaration())
6545 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6546
6547 // Check the basic block.
6548 if (Label.Kind == ValID::t_LocalID)
6549 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6550 if (Label.Kind != ValID::t_LocalName)
6551 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006552 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006553 if (!V)
6554 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6555 if (!isa<BasicBlock>(V))
6556 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6557
6558 return sortUseListOrder(V, Indexes, Loc);
6559}