blob: 58ea9296afda486752b211c43cc6cbf43f4c71f6 [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();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000136
137 FnAttrs.merge(B);
138
139 // If the alignment was parsed as an attribute, move to the alignment
140 // field.
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
144 }
145
Reid Klecknerb5180542017-03-21 16:57:19 +0000146 AS = AS.addAttributes(
147 Context, AttributeList::FunctionIndex,
148 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000151 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000154 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000155 AS = AS.addAttributes(
156 Context, AttributeList::FunctionIndex,
157 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000158 CI->setAttributes(AS);
159 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000160 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000161 AttrBuilder FnAttrs(AS.getFnAttributes());
162 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000163 FnAttrs.merge(B);
Reid Klecknerb5180542017-03-21 16:57:19 +0000164 AS = AS.addAttributes(
165 Context, AttributeList::FunctionIndex,
166 AttributeList::get(Context, AttributeList::FunctionIndex, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000167 II->setAttributes(AS);
168 } else {
169 llvm_unreachable("invalid object with forward attribute group reference");
170 }
171 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000172
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000173 // If there are entries in ForwardRefBlockAddresses at this point, the
174 // function was never defined.
175 if (!ForwardRefBlockAddresses.empty())
176 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
177 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000178
David Majnemer19b51052015-02-11 07:43:56 +0000179 for (const auto &NT : NumberedTypes)
180 if (NT.second.second.isValid())
181 return Error(NT.second.second,
182 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000183
184 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
185 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
186 if (I->second.second.isValid())
187 return Error(I->second.second,
188 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000189
David Majnemerdad0a642014-06-27 18:19:56 +0000190 if (!ForwardRefComdats.empty())
191 return Error(ForwardRefComdats.begin()->second,
192 "use of undefined comdat '$" +
193 ForwardRefComdats.begin()->first + "'");
194
Chris Lattnerac161bf2009-01-02 07:01:27 +0000195 if (!ForwardRefVals.empty())
196 return Error(ForwardRefVals.begin()->second.second,
197 "use of undefined value '@" + ForwardRefVals.begin()->first +
198 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000199
Chris Lattnerac161bf2009-01-02 07:01:27 +0000200 if (!ForwardRefValIDs.empty())
201 return Error(ForwardRefValIDs.begin()->second.second,
202 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000203 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000204
Devang Pateld2541152009-07-08 19:23:54 +0000205 if (!ForwardRefMDNodes.empty())
206 return Error(ForwardRefMDNodes.begin()->second.second,
207 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000208 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000209
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000210 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000211 for (auto &N : NumberedMetadata) {
212 if (N.second && !N.second->isResolved())
213 N.second->resolveCycles();
214 }
Devang Pateld2541152009-07-08 19:23:54 +0000215
Mehdi Aminie4709272016-09-14 22:29:59 +0000216 for (auto *Inst : InstsWithTBAATag) {
217 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
218 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
219 auto *UpgradedMD = UpgradeTBAANode(*MD);
220 if (MD != UpgradedMD)
221 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
222 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000223
Chris Lattnerac161bf2009-01-02 07:01:27 +0000224 // Look for intrinsic functions and CallInst that need to be upgraded
225 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000226 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000227
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000228 // Some types could be renamed during loading if several modules are
229 // loaded in the same LLVMContext (LTO scenario). In this case we should
230 // remangle intrinsics names as well.
231 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
232 Function *F = &*FI++;
233 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
234 F->replaceAllUsesWith(Remangled.getValue());
235 F->eraseFromParent();
236 }
237 }
238
Manman Ren8b4306c2013-12-02 21:29:56 +0000239 UpgradeDebugInfo(*M);
240
Manman Renb5d7ff42016-05-25 23:14:48 +0000241 UpgradeModuleFlags(*M);
242
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000243 if (!Slots)
244 return false;
245 // Initialize the slot mapping.
246 // Because by this point we've parsed and validated everything, we can "steal"
247 // the mapping from LLParser as it doesn't need it anymore.
248 Slots->GlobalValues = std::move(NumberedVals);
249 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000250 for (const auto &I : NamedTypes)
251 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
252 for (const auto &I : NumberedTypes)
253 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000254
Chris Lattnerac161bf2009-01-02 07:01:27 +0000255 return false;
256}
257
258//===----------------------------------------------------------------------===//
259// Top-Level Entities
260//===----------------------------------------------------------------------===//
261
262bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000263 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000264 switch (Lex.getKind()) {
265 default: return TokError("expected top-level entity");
266 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000267 case lltok::kw_declare: if (ParseDeclare()) return true; break;
268 case lltok::kw_define: if (ParseDefine()) return true; break;
269 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
270 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000271 case lltok::kw_source_filename:
272 if (ParseSourceFileName())
273 return true;
274 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000275 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000276 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000277 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000278 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000279 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000280 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000281 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000282 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000283 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000284 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
285 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000286 if (ParseUseListOrderBB())
287 return true;
288 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000289 }
290 }
291}
292
Chris Lattnerac161bf2009-01-02 07:01:27 +0000293/// toplevelentity
294/// ::= 'module' 'asm' STRINGCONSTANT
295bool LLParser::ParseModuleAsm() {
296 assert(Lex.getKind() == lltok::kw_module);
297 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000298
299 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000300 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
301 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000302
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000303 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000304 return false;
305}
306
307/// toplevelentity
308/// ::= 'target' 'triple' '=' STRINGCONSTANT
309/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
310bool LLParser::ParseTargetDefinition() {
311 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000312 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000313 switch (Lex.Lex()) {
314 default: return TokError("unknown target property");
315 case lltok::kw_triple:
316 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000317 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
318 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000320 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000321 return false;
322 case lltok::kw_datalayout:
323 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000324 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
325 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000326 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000327 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328 return false;
329 }
330}
331
Bill Wendling706d3d62012-11-28 08:41:48 +0000332/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000333/// ::= 'source_filename' '=' STRINGCONSTANT
334bool LLParser::ParseSourceFileName() {
335 assert(Lex.getKind() == lltok::kw_source_filename);
336 std::string Str;
337 Lex.Lex();
338 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
339 ParseStringConstant(Str))
340 return true;
341 M->setSourceFileName(Str);
342 return false;
343}
344
345/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000346/// ::= 'deplibs' '=' '[' ']'
347/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
348/// FIXME: Remove in 4.0. Currently parse, but ignore.
349bool LLParser::ParseDepLibs() {
350 assert(Lex.getKind() == lltok::kw_deplibs);
351 Lex.Lex();
352 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
353 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
354 return true;
355
356 if (EatIfPresent(lltok::rsquare))
357 return false;
358
359 do {
360 std::string Str;
361 if (ParseStringConstant(Str)) return true;
362 } while (EatIfPresent(lltok::comma));
363
364 return ParseToken(lltok::rsquare, "expected ']' at end of list");
365}
366
Dan Gohman466876b2009-08-12 23:32:33 +0000367/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000368/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000369bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000370 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000371 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000372 Lex.Lex(); // eat LocalVarID;
373
374 if (ParseToken(lltok::equal, "expected '=' after name") ||
375 ParseToken(lltok::kw_type, "expected 'type' after '='"))
376 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377
Craig Topper2617dcc2014-04-15 06:32:26 +0000378 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379 if (ParseStructDefinition(TypeLoc, "",
380 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000381
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000382 if (!isa<StructType>(Result)) {
383 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
384 if (Entry.first)
385 return Error(TypeLoc, "non-struct types may not be recursive");
386 Entry.first = Result;
387 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000389
Chris Lattnerac161bf2009-01-02 07:01:27 +0000390 return false;
391}
392
393/// toplevelentity
394/// ::= LocalVar '=' 'type' type
395bool LLParser::ParseNamedType() {
396 std::string Name = Lex.getStrVal();
397 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000398 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattner3822f632009-01-02 08:05:26 +0000400 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000401 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000402 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000403
Craig Topper2617dcc2014-04-15 06:32:26 +0000404 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 if (ParseStructDefinition(NameLoc, Name,
406 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000407
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000408 if (!isa<StructType>(Result)) {
409 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
410 if (Entry.first)
411 return Error(NameLoc, "non-struct types may not be recursive");
412 Entry.first = Result;
413 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000414 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000415
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000417}
418
Chris Lattnerac161bf2009-01-02 07:01:27 +0000419/// toplevelentity
420/// ::= 'declare' FunctionHeader
421bool LLParser::ParseDeclare() {
422 assert(Lex.getKind() == lltok::kw_declare);
423 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000424
Peter Collingbourne21521892016-06-21 23:42:48 +0000425 std::vector<std::pair<unsigned, MDNode *>> MDs;
426 while (Lex.getKind() == lltok::MetadataVar) {
427 unsigned MDK;
428 MDNode *N;
429 if (ParseMetadataAttachment(MDK, N))
430 return true;
431 MDs.push_back({MDK, N});
432 }
433
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000435 if (ParseFunctionHeader(F, false))
436 return true;
437 for (auto &MD : MDs)
438 F->addMetadata(MD.first, *MD.second);
439 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440}
441
442/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000443/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444bool LLParser::ParseDefine() {
445 assert(Lex.getKind() == lltok::kw_define);
446 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000447
Chris Lattnerac161bf2009-01-02 07:01:27 +0000448 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000449 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000450 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000451 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000452}
453
Chris Lattner3822f632009-01-02 08:05:26 +0000454/// ParseGlobalType
455/// ::= 'constant'
456/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457bool LLParser::ParseGlobalType(bool &IsConstant) {
458 if (Lex.getKind() == lltok::kw_constant)
459 IsConstant = true;
460 else if (Lex.getKind() == lltok::kw_global)
461 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000462 else {
463 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000464 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000465 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000466 Lex.Lex();
467 return false;
468}
469
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000470bool LLParser::ParseOptionalUnnamedAddr(
471 GlobalVariable::UnnamedAddr &UnnamedAddr) {
472 if (EatIfPresent(lltok::kw_unnamed_addr))
473 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
474 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
475 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
476 else
477 UnnamedAddr = GlobalValue::UnnamedAddr::None;
478 return false;
479}
480
Dan Gohman466876b2009-08-12 23:32:33 +0000481/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000482/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000483/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
484/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000485/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000486/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000488bool LLParser::ParseUnnamedGlobal() {
489 unsigned VarID = NumberedVals.size();
490 std::string Name;
491 LocTy NameLoc = Lex.getLoc();
492
493 // Handle the GlobalID form.
494 if (Lex.getKind() == lltok::GlobalID) {
495 if (Lex.getUIntVal() != VarID)
496 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000497 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000498 Lex.Lex(); // eat GlobalID;
499
500 if (ParseToken(lltok::equal, "expected '=' after name"))
501 return true;
502 }
503
504 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000505 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000506 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000507 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000508 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000509 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000510 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000511
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000512 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000513 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000514 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000515
516 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
517 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000518}
519
Chris Lattnerac161bf2009-01-02 07:01:27 +0000520/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000521/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000522/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
523/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000524bool LLParser::ParseNamedGlobal() {
525 assert(Lex.getKind() == lltok::GlobalVar);
526 LocTy NameLoc = Lex.getLoc();
527 std::string Name = Lex.getStrVal();
528 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000529
Chris Lattnerac161bf2009-01-02 07:01:27 +0000530 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000531 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000532 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000533 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000534 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000535 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000536 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000537 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000538
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000539 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000540 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000541 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000542
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000543 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
544 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000545}
546
David Majnemerdad0a642014-06-27 18:19:56 +0000547bool LLParser::parseComdat() {
548 assert(Lex.getKind() == lltok::ComdatVar);
549 std::string Name = Lex.getStrVal();
550 LocTy NameLoc = Lex.getLoc();
551 Lex.Lex();
552
553 if (ParseToken(lltok::equal, "expected '=' here"))
554 return true;
555
556 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
557 return TokError("expected comdat type");
558
559 Comdat::SelectionKind SK;
560 switch (Lex.getKind()) {
561 default:
562 return TokError("unknown selection kind");
563 case lltok::kw_any:
564 SK = Comdat::Any;
565 break;
566 case lltok::kw_exactmatch:
567 SK = Comdat::ExactMatch;
568 break;
569 case lltok::kw_largest:
570 SK = Comdat::Largest;
571 break;
572 case lltok::kw_noduplicates:
573 SK = Comdat::NoDuplicates;
574 break;
575 case lltok::kw_samesize:
576 SK = Comdat::SameSize;
577 break;
578 }
579 Lex.Lex();
580
581 // See if the comdat was forward referenced, if so, use the comdat.
582 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
583 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
584 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
585 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
586
587 Comdat *C;
588 if (I != ComdatSymTab.end())
589 C = &I->second;
590 else
591 C = M->getOrInsertComdat(Name);
592 C->setSelectionKind(SK);
593
594 return false;
595}
596
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597// MDString:
598// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000599bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600 std::string Str;
601 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000602 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603 return false;
604}
605
606// MDNode:
607// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000608bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000609 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000610 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000611 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000612 if (ParseUInt32(MID))
613 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000614
Chris Lattner8eff0152010-04-01 05:14:45 +0000615 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000616 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000617 Result = NumberedMetadata[MID];
618 return false;
619 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000620
Chris Lattner8eff0152010-04-01 05:14:45 +0000621 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000622 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000623 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000624
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000625 Result = FwdRef.first.get();
626 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000627 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000628}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000629
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000630/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000631/// !foo = !{ !1, !2 }
632bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000633 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000634 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000635 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000636
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000637 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000638 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000639 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000640 return true;
641
Dan Gohman2637cc12010-07-21 23:38:33 +0000642 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000643 if (Lex.getKind() != lltok::rbrace)
644 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000645 if (ParseToken(lltok::exclaim, "Expected '!' here"))
646 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000647
Craig Topper2617dcc2014-04-15 06:32:26 +0000648 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000649 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000650 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000651 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000652
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000653 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000654}
655
Devang Patel39e64d42009-07-01 19:21:12 +0000656/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000657/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000658bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000659 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000660 Lex.Lex();
661 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000662
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000663 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000664 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000665 ParseToken(lltok::equal, "expected '=' here"))
666 return true;
667
668 // Detect common error, from old metadata syntax.
669 if (Lex.getKind() == lltok::Type)
670 return TokError("unexpected type in metadata definition");
671
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000672 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000673 if (Lex.getKind() == lltok::MetadataVar) {
674 if (ParseSpecializedMDNode(Init, IsDistinct))
675 return true;
676 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
677 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000678 return true;
679
Chris Lattnerfc58af22009-12-30 04:51:58 +0000680 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000681 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000682 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000683 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000684 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000685
Chris Lattnerfc58af22009-12-30 04:51:58 +0000686 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
687 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000688 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000689 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000690 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000691 }
692
Devang Patel39e64d42009-07-01 19:21:12 +0000693 return false;
694}
695
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000696static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
697 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
698 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
699}
700
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000701/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000702/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
703/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000704/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000705///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000706/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000707/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000708///
Eric Christopher536f0a92015-05-28 23:07:39 +0000709/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000710///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000711bool LLParser::parseIndirectSymbol(
712 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
713 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
714 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000715 bool IsAlias;
716 if (Lex.getKind() == lltok::kw_alias)
717 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000718 else if (Lex.getKind() == lltok::kw_ifunc)
719 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000720 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000721 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000722 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723
Rafael Espindola78527052013-10-06 15:10:43 +0000724 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
725
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000726 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000727 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000728
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000729 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000730 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000731 "symbol with local linkage must have default visibility");
732
David Blaikie2f408302015-09-11 03:22:04 +0000733 Type *Ty;
734 LocTy ExplicitTypeLoc = Lex.getLoc();
735 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000736 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000737 return true;
738
Rafael Espindola64c1e182014-06-03 02:41:57 +0000739 Constant *Aliasee;
740 LocTy AliaseeLoc = Lex.getLoc();
741 if (Lex.getKind() != lltok::kw_bitcast &&
742 Lex.getKind() != lltok::kw_getelementptr &&
743 Lex.getKind() != lltok::kw_addrspacecast &&
744 Lex.getKind() != lltok::kw_inttoptr) {
745 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000746 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000748 // The bitcast dest type is not present, it is implied by the dest type.
749 ValID ID;
750 if (ParseValID(ID))
751 return true;
752 if (ID.Kind != ValID::t_Constant)
753 return Error(AliaseeLoc, "invalid aliasee");
754 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000755 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000756
Rafael Espindola64c1e182014-06-03 02:41:57 +0000757 Type *AliaseeType = Aliasee->getType();
758 auto *PTy = dyn_cast<PointerType>(AliaseeType);
759 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000760 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000761 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000762
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000763 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000764 return Error(
765 ExplicitTypeLoc,
766 "explicit pointee type doesn't match operand's pointee type");
767
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000768 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
769 return Error(
770 ExplicitTypeLoc,
771 "explicit pointee type should be a function type");
772
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000773 GlobalValue *GVal = nullptr;
774
775 // See if the alias was forward referenced, if so, prepare to replace the
776 // forward reference.
777 if (!Name.empty()) {
778 GVal = M->getNamedValue(Name);
779 if (GVal) {
780 if (!ForwardRefVals.erase(Name))
781 return Error(NameLoc, "redefinition of global '@" + Name + "'");
782 }
783 } else {
784 auto I = ForwardRefValIDs.find(NumberedVals.size());
785 if (I != ForwardRefValIDs.end()) {
786 GVal = I->second.first;
787 ForwardRefValIDs.erase(I);
788 }
789 }
790
Chris Lattnerac161bf2009-01-02 07:01:27 +0000791 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000792 std::unique_ptr<GlobalIndirectSymbol> GA;
793 if (IsAlias)
794 GA.reset(GlobalAlias::create(Ty, AddrSpace,
795 (GlobalValue::LinkageTypes)Linkage, Name,
796 Aliasee, /*Parent*/ nullptr));
797 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000798 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
799 (GlobalValue::LinkageTypes)Linkage, Name,
800 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000801 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000802 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000803 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000804 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000805
Rafael Espindola54fc2982015-06-17 17:53:31 +0000806 if (Name.empty())
807 NumberedVals.push_back(GA.get());
808
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000809 if (GVal) {
810 // Verify that types agree.
811 if (GVal->getType() != GA->getType())
812 return Error(
813 ExplicitTypeLoc,
814 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Chris Lattnerac161bf2009-01-02 07:01:27 +0000816 // If they agree, just RAUW the old value with the alias and remove the
817 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000818 GVal->replaceAllUsesWith(GA.get());
819 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000821
Chris Lattnerac161bf2009-01-02 07:01:27 +0000822 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000823 if (IsAlias)
824 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
825 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000826 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000827 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000828
Rafael Espindolaaa273822014-05-09 21:49:17 +0000829 // The module owns this now
830 GA.release();
831
Chris Lattnerac161bf2009-01-02 07:01:27 +0000832 return false;
833}
834
835/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000836/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000837/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000838/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000839/// ::= 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
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842///
Eric Christopher536f0a92015-05-28 23:07:39 +0000843/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000844/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845///
846bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
847 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000848 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000849 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000850 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000851 if (!isValidVisibilityForLinkage(Visibility, Linkage))
852 return Error(NameLoc,
853 "symbol with local linkage must have default visibility");
854
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000856 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000857 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000858 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000859
Craig Topper2617dcc2014-04-15 06:32:26 +0000860 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000861 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000862 ParseOptionalToken(lltok::kw_externally_initialized,
863 IsExternallyInitialized,
864 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000865 ParseGlobalType(IsConstant) ||
866 ParseType(Ty, TyLoc))
867 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000868
Chris Lattnerac161bf2009-01-02 07:01:27 +0000869 // If the linkage is specified and is external, then no initializer is
870 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000871 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000872 if (!HasLinkage ||
873 !GlobalValue::isValidDeclarationLinkage(
874 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000875 if (ParseGlobalValue(Ty, Init))
876 return true;
877 }
878
David Majnemer49b3d9b2015-02-16 08:41:08 +0000879 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000880 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000881
David Majnemer598bd052014-12-09 05:56:09 +0000882 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883
884 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000885 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000886 GVal = M->getNamedValue(Name);
887 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000888 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000889 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000890 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000891 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000892 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000893 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000894 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000895 ForwardRefValIDs.erase(I);
896 }
897 }
898
David Majnemer598bd052014-12-09 05:56:09 +0000899 GlobalVariable *GV;
900 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000901 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
902 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000903 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000904 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000905 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000906 return Error(TyLoc,
907 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000908
David Majnemer598bd052014-12-09 05:56:09 +0000909 GV = cast<GlobalVariable>(GVal);
910
Chris Lattnerac161bf2009-01-02 07:01:27 +0000911 // Move the forward-reference to the correct spot in the module.
912 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
913 }
914
915 if (Name.empty())
916 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000917
Chris Lattnerac161bf2009-01-02 07:01:27 +0000918 // Set the parsed properties on the global.
919 if (Init)
920 GV->setInitializer(Init);
921 GV->setConstant(IsConstant);
922 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
923 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000924 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000925 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000926 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000927 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000928
Chris Lattnerac161bf2009-01-02 07:01:27 +0000929 // Parse attributes on the global.
930 while (Lex.getKind() == lltok::comma) {
931 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000932
Chris Lattnerac161bf2009-01-02 07:01:27 +0000933 if (Lex.getKind() == lltok::kw_section) {
934 Lex.Lex();
935 GV->setSection(Lex.getStrVal());
936 if (ParseToken(lltok::StringConstant, "expected global section string"))
937 return true;
938 } else if (Lex.getKind() == lltok::kw_align) {
939 unsigned Alignment;
940 if (ParseOptionalAlignment(Alignment)) return true;
941 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000942 } else if (Lex.getKind() == lltok::MetadataVar) {
943 if (ParseGlobalObjectMetadataAttachment(*GV))
944 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000945 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000946 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000947 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000948 return true;
949 if (C)
950 GV->setComdat(C);
951 else
952 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000953 }
954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000955
Chris Lattnerac161bf2009-01-02 07:01:27 +0000956 return false;
957}
958
Bill Wendling63b88192013-02-06 06:52:58 +0000959/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000960/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000961bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000962 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000963 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000964 Lex.Lex();
965
David Majnemerb39e22b2014-12-09 18:33:57 +0000966 if (Lex.getKind() != lltok::AttrGrpID)
967 return TokError("expected attribute group id");
968
Bill Wendling63b88192013-02-06 06:52:58 +0000969 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000970 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000971 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000972 Lex.Lex();
973
974 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000975 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000976 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000977 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000978 ParseToken(lltok::rbrace, "expected end of attribute group"))
979 return true;
980
Bill Wendlingb32b0412013-02-08 06:32:06 +0000981 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000982 return Error(AttrGrpLoc, "attribute group has no attributes");
983
984 return false;
985}
986
Bill Wendling8b0321d2013-02-08 00:52:31 +0000987/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000988/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000989bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
990 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000991 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000992 bool HaveError = false;
993
994 B.clear();
995
Bill Wendling63b88192013-02-06 06:52:58 +0000996 while (true) {
997 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000998 if (Token == lltok::kw_builtin)
999 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001000 switch (Token) {
1001 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001002 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001003 return Error(Lex.getLoc(), "unterminated attribute group");
1004 case lltok::rbrace:
1005 // Finished.
1006 return false;
1007
Bill Wendlingb32b0412013-02-08 06:32:06 +00001008 case lltok::AttrGrpID: {
1009 // Allow a function to reference an attribute group:
1010 //
1011 // define void @foo() #1 { ... }
1012 if (inAttrGrp)
1013 HaveError |=
1014 Error(Lex.getLoc(),
1015 "cannot have an attribute group reference in an attribute group");
1016
1017 unsigned AttrGrpNum = Lex.getUIntVal();
1018 if (inAttrGrp) break;
1019
1020 // Save the reference to the attribute group. We'll fill it in later.
1021 FwdRefAttrGrps.push_back(AttrGrpNum);
1022 break;
1023 }
Bill Wendling63b88192013-02-06 06:52:58 +00001024 // Target-dependent attributes:
1025 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001026 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001027 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001028 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001029 }
1030
1031 // Target-independent attributes:
1032 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001033 // As a hack, we allow function alignment to be initially parsed as an
1034 // attribute on a function declaration/definition or added to an attribute
1035 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001036 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001037 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001038 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001039 if (ParseToken(lltok::equal, "expected '=' here") ||
1040 ParseUInt32(Alignment))
1041 return true;
1042 } else {
1043 if (ParseOptionalAlignment(Alignment))
1044 return true;
1045 }
Bill Wendling63b88192013-02-06 06:52:58 +00001046 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001047 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001048 }
1049 case lltok::kw_alignstack: {
1050 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001051 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001052 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001053 if (ParseToken(lltok::equal, "expected '=' here") ||
1054 ParseUInt32(Alignment))
1055 return true;
1056 } else {
1057 if (ParseOptionalStackAlignment(Alignment))
1058 return true;
1059 }
Bill Wendling63b88192013-02-06 06:52:58 +00001060 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001061 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001062 }
George Burgess IV278199f2016-04-12 01:05:35 +00001063 case lltok::kw_allocsize: {
1064 unsigned ElemSizeArg;
1065 Optional<unsigned> NumElemsArg;
1066 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1067 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1068 return true;
1069 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1070 continue;
1071 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001072 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1073 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1074 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1075 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1076 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001077 case lltok::kw_inaccessiblememonly:
1078 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1079 case lltok::kw_inaccessiblemem_or_argmemonly:
1080 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001081 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1082 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1083 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1084 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1085 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1086 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1087 case lltok::kw_noimplicitfloat:
1088 B.addAttribute(Attribute::NoImplicitFloat); break;
1089 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1090 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1091 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1092 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001093 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001094 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1095 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1096 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1097 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1098 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1099 case lltok::kw_returns_twice:
1100 B.addAttribute(Attribute::ReturnsTwice); break;
1101 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1102 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1103 case lltok::kw_sspstrong:
1104 B.addAttribute(Attribute::StackProtectStrong); break;
1105 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1106 case lltok::kw_sanitize_address:
1107 B.addAttribute(Attribute::SanitizeAddress); break;
1108 case lltok::kw_sanitize_thread:
1109 B.addAttribute(Attribute::SanitizeThread); break;
1110 case lltok::kw_sanitize_memory:
1111 B.addAttribute(Attribute::SanitizeMemory); break;
1112 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001113 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001114
1115 // Error handling.
1116 case lltok::kw_inreg:
1117 case lltok::kw_signext:
1118 case lltok::kw_zeroext:
1119 HaveError |=
1120 Error(Lex.getLoc(),
1121 "invalid use of attribute on a function");
1122 break;
1123 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001124 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001125 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001126 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001127 case lltok::kw_nest:
1128 case lltok::kw_noalias:
1129 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001130 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001131 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001132 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001133 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001134 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001135 HaveError |=
1136 Error(Lex.getLoc(),
1137 "invalid use of parameter-only attribute on a function");
1138 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001139 }
1140
1141 Lex.Lex();
1142 }
1143}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001144
1145//===----------------------------------------------------------------------===//
1146// GlobalValue Reference/Resolution Routines.
1147//===----------------------------------------------------------------------===//
1148
Karl Schimpf77729782015-09-03 18:06:44 +00001149static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1150 const std::string &Name) {
1151 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1152 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1153 else
1154 return new GlobalVariable(*M, PTy->getElementType(), false,
1155 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1156 nullptr, GlobalVariable::NotThreadLocal,
1157 PTy->getAddressSpace());
1158}
1159
Chris Lattnerac161bf2009-01-02 07:01:27 +00001160/// GetGlobalVal - Get a value with the specified name or ID, creating a
1161/// forward reference record if needed. This can return null if the value
1162/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001163GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001164 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001165 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001166 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001168 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001170
Chris Lattnerac161bf2009-01-02 07:01:27 +00001171 // Look this name up in the normal function symbol table.
1172 GlobalValue *Val =
1173 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001174
Chris Lattnerac161bf2009-01-02 07:01:27 +00001175 // If this is a forward reference for the value, see if we already created a
1176 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001177 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001178 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001179 if (I != ForwardRefVals.end())
1180 Val = I->second.first;
1181 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183 // If we have the value in the symbol table or fwd-ref table, return it.
1184 if (Val) {
1185 if (Val->getType() == Ty) return Val;
1186 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001187 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001188 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001190
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001192 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001193 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1194 return FwdVal;
1195}
1196
Chris Lattner229907c2011-07-18 04:54:35 +00001197GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1198 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001199 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001201 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001203
Craig Topper2617dcc2014-04-15 06:32:26 +00001204 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001205
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206 // If this is a forward reference for the value, see if we already created a
1207 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001208 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001209 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 if (I != ForwardRefValIDs.end())
1211 Val = I->second.first;
1212 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001213
Chris Lattnerac161bf2009-01-02 07:01:27 +00001214 // If we have the value in the symbol table or fwd-ref table, return it.
1215 if (Val) {
1216 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001217 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001218 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001219 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001221
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001223 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1225 return FwdVal;
1226}
1227
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001229// Comdat Reference/Resolution Routines.
1230//===----------------------------------------------------------------------===//
1231
1232Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1233 // Look this name up in the comdat symbol table.
1234 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1235 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1236 if (I != ComdatSymTab.end())
1237 return &I->second;
1238
1239 // Otherwise, create a new forward reference for this value and remember it.
1240 Comdat *C = M->getOrInsertComdat(Name);
1241 ForwardRefComdats[Name] = Loc;
1242 return C;
1243}
1244
David Majnemerdad0a642014-06-27 18:19:56 +00001245//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001246// Helper Routines.
1247//===----------------------------------------------------------------------===//
1248
1249/// ParseToken - If the current token has the specified kind, eat it and return
1250/// success. Otherwise, emit the specified error and return failure.
1251bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1252 if (Lex.getKind() != T)
1253 return TokError(ErrMsg);
1254 Lex.Lex();
1255 return false;
1256}
1257
Chris Lattner3822f632009-01-02 08:05:26 +00001258/// ParseStringConstant
1259/// ::= StringConstant
1260bool LLParser::ParseStringConstant(std::string &Result) {
1261 if (Lex.getKind() != lltok::StringConstant)
1262 return TokError("expected string constant");
1263 Result = Lex.getStrVal();
1264 Lex.Lex();
1265 return false;
1266}
1267
1268/// ParseUInt32
1269/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001270bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001271 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1272 return TokError("expected integer");
1273 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1274 if (Val64 != unsigned(Val64))
1275 return TokError("expected 32-bit integer (too large)");
1276 Val = Val64;
1277 Lex.Lex();
1278 return false;
1279}
1280
Hal Finkelb0407ba2014-07-18 15:51:28 +00001281/// ParseUInt64
1282/// ::= uint64
1283bool LLParser::ParseUInt64(uint64_t &Val) {
1284 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1285 return TokError("expected integer");
1286 Val = Lex.getAPSIntVal().getLimitedValue();
1287 Lex.Lex();
1288 return false;
1289}
1290
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001291/// ParseTLSModel
1292/// := 'localdynamic'
1293/// := 'initialexec'
1294/// := 'localexec'
1295bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1296 switch (Lex.getKind()) {
1297 default:
1298 return TokError("expected localdynamic, initialexec or localexec");
1299 case lltok::kw_localdynamic:
1300 TLM = GlobalVariable::LocalDynamicTLSModel;
1301 break;
1302 case lltok::kw_initialexec:
1303 TLM = GlobalVariable::InitialExecTLSModel;
1304 break;
1305 case lltok::kw_localexec:
1306 TLM = GlobalVariable::LocalExecTLSModel;
1307 break;
1308 }
1309
1310 Lex.Lex();
1311 return false;
1312}
1313
1314/// ParseOptionalThreadLocal
1315/// := /*empty*/
1316/// := 'thread_local'
1317/// := 'thread_local' '(' tlsmodel ')'
1318bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1319 TLM = GlobalVariable::NotThreadLocal;
1320 if (!EatIfPresent(lltok::kw_thread_local))
1321 return false;
1322
1323 TLM = GlobalVariable::GeneralDynamicTLSModel;
1324 if (Lex.getKind() == lltok::lparen) {
1325 Lex.Lex();
1326 return ParseTLSModel(TLM) ||
1327 ParseToken(lltok::rparen, "expected ')' after thread local model");
1328 }
1329 return false;
1330}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001331
1332/// ParseOptionalAddrSpace
1333/// := /*empty*/
1334/// := 'addrspace' '(' uint32 ')'
1335bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1336 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001337 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001338 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001339 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001340 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001341 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001342}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001343
Artur Pilipenko17376c42015-08-03 14:31:49 +00001344/// ParseStringAttribute
1345/// := StringConstant
1346/// := StringConstant '=' StringConstant
1347bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1348 std::string Attr = Lex.getStrVal();
1349 Lex.Lex();
1350 std::string Val;
1351 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1352 return true;
1353 B.addAttribute(Attr, Val);
1354 return false;
1355}
1356
Bill Wendling34c2eb22012-12-04 23:40:58 +00001357/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1358bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1359 bool HaveError = false;
1360
1361 B.clear();
1362
Eugene Zelenko1804a772016-08-25 00:45:04 +00001363 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001364 lltok::Kind Token = Lex.getKind();
1365 switch (Token) {
1366 default: // End of attributes.
1367 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001368 case lltok::StringConstant: {
1369 if (ParseStringAttribute(B))
1370 return true;
1371 continue;
1372 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001373 case lltok::kw_align: {
1374 unsigned Alignment;
1375 if (ParseOptionalAlignment(Alignment))
1376 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001377 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001378 continue;
1379 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001380 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001381 case lltok::kw_dereferenceable: {
1382 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001383 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001384 return true;
1385 B.addDereferenceableAttr(Bytes);
1386 continue;
1387 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001388 case lltok::kw_dereferenceable_or_null: {
1389 uint64_t Bytes;
1390 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1391 return true;
1392 B.addDereferenceableOrNullAttr(Bytes);
1393 continue;
1394 }
Reid Klecknera534a382013-12-19 02:14:12 +00001395 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001396 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1397 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1398 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1399 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001400 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001401 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1402 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001403 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001404 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1405 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001406 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001407 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001408 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001409 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001410
Stephen Lin7577ed52013-04-20 13:16:13 +00001411 case lltok::kw_alignstack:
1412 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001413 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001414 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001415 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001416 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001417 case lltok::kw_minsize:
1418 case lltok::kw_naked:
1419 case lltok::kw_nobuiltin:
1420 case lltok::kw_noduplicate:
1421 case lltok::kw_noimplicitfloat:
1422 case lltok::kw_noinline:
1423 case lltok::kw_nonlazybind:
1424 case lltok::kw_noredzone:
1425 case lltok::kw_noreturn:
1426 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001427 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001428 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001429 case lltok::kw_returns_twice:
1430 case lltok::kw_sanitize_address:
1431 case lltok::kw_sanitize_memory:
1432 case lltok::kw_sanitize_thread:
1433 case lltok::kw_ssp:
1434 case lltok::kw_sspreq:
1435 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001436 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001437 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001438 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1439 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001440 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001441
Bill Wendling34c2eb22012-12-04 23:40:58 +00001442 Lex.Lex();
1443 }
1444}
1445
1446/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1447bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1448 bool HaveError = false;
1449
1450 B.clear();
1451
Eugene Zelenko1804a772016-08-25 00:45:04 +00001452 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001453 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001454 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001455 default: // End of attributes.
1456 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001457 case lltok::StringConstant: {
1458 if (ParseStringAttribute(B))
1459 return true;
1460 continue;
1461 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001462 case lltok::kw_dereferenceable: {
1463 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001464 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001465 return true;
1466 B.addDereferenceableAttr(Bytes);
1467 continue;
1468 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001469 case lltok::kw_dereferenceable_or_null: {
1470 uint64_t Bytes;
1471 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1472 return true;
1473 B.addDereferenceableOrNullAttr(Bytes);
1474 continue;
1475 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001476 case lltok::kw_align: {
1477 unsigned Alignment;
1478 if (ParseOptionalAlignment(Alignment))
1479 return true;
1480 B.addAlignmentAttr(Alignment);
1481 continue;
1482 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001483 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1484 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001485 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001486 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1487 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001488
Bill Wendling34c2eb22012-12-04 23:40:58 +00001489 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001490 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001491 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001492 case lltok::kw_nest:
1493 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001494 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001495 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001496 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001497 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001498 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001499 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001500
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001501 case lltok::kw_alignstack:
1502 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001503 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001504 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001505 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001506 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001507 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001508 case lltok::kw_minsize:
1509 case lltok::kw_naked:
1510 case lltok::kw_nobuiltin:
1511 case lltok::kw_noduplicate:
1512 case lltok::kw_noimplicitfloat:
1513 case lltok::kw_noinline:
1514 case lltok::kw_nonlazybind:
1515 case lltok::kw_noredzone:
1516 case lltok::kw_noreturn:
1517 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001518 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001519 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001520 case lltok::kw_returns_twice:
1521 case lltok::kw_sanitize_address:
1522 case lltok::kw_sanitize_memory:
1523 case lltok::kw_sanitize_thread:
1524 case lltok::kw_ssp:
1525 case lltok::kw_sspreq:
1526 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001527 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001528 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001529 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001530 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001531
1532 case lltok::kw_readnone:
1533 case lltok::kw_readonly:
1534 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001535 }
1536
Chris Lattnerac161bf2009-01-02 07:01:27 +00001537 Lex.Lex();
1538 }
1539}
1540
Rafael Espindolac6269912016-05-10 17:16:45 +00001541static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1542 HasLinkage = true;
1543 switch (Kind) {
1544 default:
1545 HasLinkage = false;
1546 return GlobalValue::ExternalLinkage;
1547 case lltok::kw_private:
1548 return GlobalValue::PrivateLinkage;
1549 case lltok::kw_internal:
1550 return GlobalValue::InternalLinkage;
1551 case lltok::kw_weak:
1552 return GlobalValue::WeakAnyLinkage;
1553 case lltok::kw_weak_odr:
1554 return GlobalValue::WeakODRLinkage;
1555 case lltok::kw_linkonce:
1556 return GlobalValue::LinkOnceAnyLinkage;
1557 case lltok::kw_linkonce_odr:
1558 return GlobalValue::LinkOnceODRLinkage;
1559 case lltok::kw_available_externally:
1560 return GlobalValue::AvailableExternallyLinkage;
1561 case lltok::kw_appending:
1562 return GlobalValue::AppendingLinkage;
1563 case lltok::kw_common:
1564 return GlobalValue::CommonLinkage;
1565 case lltok::kw_extern_weak:
1566 return GlobalValue::ExternalWeakLinkage;
1567 case lltok::kw_external:
1568 return GlobalValue::ExternalLinkage;
1569 }
1570}
1571
Chris Lattnerac161bf2009-01-02 07:01:27 +00001572/// ParseOptionalLinkage
1573/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001574/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575/// ::= 'internal'
1576/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001577/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001579/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001580/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001582/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001583/// ::= 'extern_weak'
1584/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001585bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1586 unsigned &Visibility,
1587 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001588 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1589 if (HasLinkage)
1590 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001591 ParseOptionalVisibility(Visibility);
1592 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001593 return false;
1594}
1595
1596/// ParseOptionalVisibility
1597/// ::= /*empty*/
1598/// ::= 'default'
1599/// ::= 'hidden'
1600/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001601///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001602void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001603 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001604 default:
1605 Res = GlobalValue::DefaultVisibility;
1606 return;
1607 case lltok::kw_default:
1608 Res = GlobalValue::DefaultVisibility;
1609 break;
1610 case lltok::kw_hidden:
1611 Res = GlobalValue::HiddenVisibility;
1612 break;
1613 case lltok::kw_protected:
1614 Res = GlobalValue::ProtectedVisibility;
1615 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001616 }
1617 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618}
1619
Nico Rieck7157bb72014-01-14 15:22:47 +00001620/// ParseOptionalDLLStorageClass
1621/// ::= /*empty*/
1622/// ::= 'dllimport'
1623/// ::= 'dllexport'
1624///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001625void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001626 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001627 default:
1628 Res = GlobalValue::DefaultStorageClass;
1629 return;
1630 case lltok::kw_dllimport:
1631 Res = GlobalValue::DLLImportStorageClass;
1632 break;
1633 case lltok::kw_dllexport:
1634 Res = GlobalValue::DLLExportStorageClass;
1635 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001636 }
1637 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001638}
1639
Chris Lattnerac161bf2009-01-02 07:01:27 +00001640/// ParseOptionalCallingConv
1641/// ::= /*empty*/
1642/// ::= 'ccc'
1643/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001644/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001645/// ::= 'coldcc'
1646/// ::= 'x86_stdcallcc'
1647/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001648/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001649/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001650/// ::= 'arm_apcscc'
1651/// ::= 'arm_aapcscc'
1652/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001653/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001654/// ::= 'avr_intrcc'
1655/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001656/// ::= 'ptx_kernel'
1657/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001658/// ::= 'spir_func'
1659/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001660/// ::= 'x86_64_sysvcc'
1661/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001662/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001663/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001664/// ::= 'preserve_mostcc'
1665/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001666/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001667/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001668/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001669/// ::= 'hhvmcc'
1670/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001671/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001672/// ::= 'amdgpu_vs'
1673/// ::= 'amdgpu_tcs'
1674/// ::= 'amdgpu_tes'
1675/// ::= 'amdgpu_gs'
1676/// ::= 'amdgpu_ps'
1677/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001678/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001679/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001680///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001681bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682 switch (Lex.getKind()) {
1683 default: CC = CallingConv::C; return false;
1684 case lltok::kw_ccc: CC = CallingConv::C; break;
1685 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1686 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1687 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1688 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001689 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001690 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001691 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001692 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1693 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1694 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001695 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001696 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1697 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001698 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1699 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001700 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1701 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001702 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001703 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1704 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001705 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001706 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001707 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1708 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001709 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001710 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001711 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001712 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1713 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001714 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001715 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1716 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1717 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1718 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001719 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001720 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001721 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001722 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001723 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001725
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 Lex.Lex();
1727 return false;
1728}
1729
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001730/// ParseMetadataAttachment
1731/// ::= !dbg !42
1732bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1733 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1734
1735 std::string Name = Lex.getStrVal();
1736 Kind = M->getMDKindID(Name);
1737 Lex.Lex();
1738
1739 return ParseMDNode(MD);
1740}
1741
Chris Lattner5c427632009-12-30 05:31:19 +00001742/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001743/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001744bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001745 do {
1746 if (Lex.getKind() != lltok::MetadataVar)
1747 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001748
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001749 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001750 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001751 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001752 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001753
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001754 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001755 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001756 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001757
Chris Lattner596760d2009-12-29 21:25:40 +00001758 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001759 } while (EatIfPresent(lltok::comma));
1760 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001761}
1762
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001763/// ParseGlobalObjectMetadataAttachment
1764/// ::= !dbg !57
1765bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1766 unsigned MDK;
1767 MDNode *N;
1768 if (ParseMetadataAttachment(MDK, N))
1769 return true;
1770
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001771 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001772 return false;
1773}
1774
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001775/// ParseOptionalFunctionMetadata
1776/// ::= (!dbg !57)*
1777bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001778 while (Lex.getKind() == lltok::MetadataVar)
1779 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001780 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001781 return false;
1782}
1783
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784/// ParseOptionalAlignment
1785/// ::= /* empty */
1786/// ::= 'align' 4
1787bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1788 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001789 if (!EatIfPresent(lltok::kw_align))
1790 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001791 LocTy AlignLoc = Lex.getLoc();
1792 if (ParseUInt32(Alignment)) return true;
1793 if (!isPowerOf2_32(Alignment))
1794 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001795 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001796 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001797 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001798}
1799
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001800/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001801/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001802/// ::= AttrKind '(' 4 ')'
1803///
1804/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1805bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1806 uint64_t &Bytes) {
1807 assert((AttrKind == lltok::kw_dereferenceable ||
1808 AttrKind == lltok::kw_dereferenceable_or_null) &&
1809 "contract!");
1810
Hal Finkelb0407ba2014-07-18 15:51:28 +00001811 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001812 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001813 return false;
1814 LocTy ParenLoc = Lex.getLoc();
1815 if (!EatIfPresent(lltok::lparen))
1816 return Error(ParenLoc, "expected '('");
1817 LocTy DerefLoc = Lex.getLoc();
1818 if (ParseUInt64(Bytes)) return true;
1819 ParenLoc = Lex.getLoc();
1820 if (!EatIfPresent(lltok::rparen))
1821 return Error(ParenLoc, "expected ')'");
1822 if (!Bytes)
1823 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1824 return false;
1825}
1826
Chris Lattnerb2f39502009-12-30 05:44:30 +00001827/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001828/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001829/// ::= ',' align 4
1830///
1831/// This returns with AteExtraComma set to true if it ate an excess comma at the
1832/// end.
1833bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1834 bool &AteExtraComma) {
1835 AteExtraComma = false;
1836 while (EatIfPresent(lltok::comma)) {
1837 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001838 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001839 AteExtraComma = true;
1840 return false;
1841 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001842
Chris Lattner95b0ff42010-04-23 00:50:50 +00001843 if (Lex.getKind() != lltok::kw_align)
1844 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001845
Chris Lattner95b0ff42010-04-23 00:50:50 +00001846 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001847 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001848
Devang Patelea8a4b92009-09-17 23:04:48 +00001849 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001850}
1851
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001852/// ParseOptionalCommaAddrSpace
1853/// ::=
1854/// ::= ',' addrspace(1)
1855///
1856/// This returns with AteExtraComma set to true if it ate an excess comma at the
1857/// end.
1858bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1859 LocTy &Loc,
1860 bool &AteExtraComma) {
1861 AteExtraComma = false;
1862 while (EatIfPresent(lltok::comma)) {
1863 // Metadata at the end is an early exit.
1864 if (Lex.getKind() == lltok::MetadataVar) {
1865 AteExtraComma = true;
1866 return false;
1867 }
1868
1869 Loc = Lex.getLoc();
1870 if (Lex.getKind() != lltok::kw_addrspace)
1871 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1872
1873 if (ParseOptionalAddrSpace(AddrSpace))
1874 return true;
1875 }
1876
1877 return false;
1878}
1879
George Burgess IV278199f2016-04-12 01:05:35 +00001880bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1881 Optional<unsigned> &HowManyArg) {
1882 Lex.Lex();
1883
1884 auto StartParen = Lex.getLoc();
1885 if (!EatIfPresent(lltok::lparen))
1886 return Error(StartParen, "expected '('");
1887
1888 if (ParseUInt32(BaseSizeArg))
1889 return true;
1890
1891 if (EatIfPresent(lltok::comma)) {
1892 auto HowManyAt = Lex.getLoc();
1893 unsigned HowMany;
1894 if (ParseUInt32(HowMany))
1895 return true;
1896 if (HowMany == BaseSizeArg)
1897 return Error(HowManyAt,
1898 "'allocsize' indices can't refer to the same parameter");
1899 HowManyArg = HowMany;
1900 } else
1901 HowManyArg = None;
1902
1903 auto EndParen = Lex.getLoc();
1904 if (!EatIfPresent(lltok::rparen))
1905 return Error(EndParen, "expected ')'");
1906 return false;
1907}
1908
Eli Friedmanfee02c62011-07-25 23:16:38 +00001909/// ParseScopeAndOrdering
1910/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1911/// else: ::=
1912///
1913/// This sets Scope and Ordering to the parsed values.
1914bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1915 AtomicOrdering &Ordering) {
1916 if (!isAtomic)
1917 return false;
1918
1919 Scope = CrossThread;
1920 if (EatIfPresent(lltok::kw_singlethread))
1921 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001922
1923 return ParseOrdering(Ordering);
1924}
1925
1926/// ParseOrdering
1927/// ::= AtomicOrdering
1928///
1929/// This sets Ordering to the parsed value.
1930bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001931 switch (Lex.getKind()) {
1932 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001933 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1934 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1935 // Not specified yet:
1936 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1937 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1938 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1939 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1940 case lltok::kw_seq_cst:
1941 Ordering = AtomicOrdering::SequentiallyConsistent;
1942 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001943 }
1944 Lex.Lex();
1945 return false;
1946}
1947
Charles Davisbe5557e2010-02-12 00:31:15 +00001948/// ParseOptionalStackAlignment
1949/// ::= /* empty */
1950/// ::= 'alignstack' '(' 4 ')'
1951bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1952 Alignment = 0;
1953 if (!EatIfPresent(lltok::kw_alignstack))
1954 return false;
1955 LocTy ParenLoc = Lex.getLoc();
1956 if (!EatIfPresent(lltok::lparen))
1957 return Error(ParenLoc, "expected '('");
1958 LocTy AlignLoc = Lex.getLoc();
1959 if (ParseUInt32(Alignment)) return true;
1960 ParenLoc = Lex.getLoc();
1961 if (!EatIfPresent(lltok::rparen))
1962 return Error(ParenLoc, "expected ')'");
1963 if (!isPowerOf2_32(Alignment))
1964 return Error(AlignLoc, "stack alignment is not a power of two");
1965 return false;
1966}
Devang Patelea8a4b92009-09-17 23:04:48 +00001967
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001968/// ParseIndexList - This parses the index list for an insert/extractvalue
1969/// instruction. This sets AteExtraComma in the case where we eat an extra
1970/// comma at the end of the line and find that it is followed by metadata.
1971/// Clients that don't allow metadata can call the version of this function that
1972/// only takes one argument.
1973///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001974/// ParseIndexList
1975/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001976///
1977bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1978 bool &AteExtraComma) {
1979 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001980
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 if (Lex.getKind() != lltok::comma)
1982 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001983
Chris Lattner3822f632009-01-02 08:05:26 +00001984 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001985 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001986 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001987 AteExtraComma = true;
1988 return false;
1989 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001990 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001991 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001992 Indices.push_back(Idx);
1993 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001994
Chris Lattnerac161bf2009-01-02 07:01:27 +00001995 return false;
1996}
1997
1998//===----------------------------------------------------------------------===//
1999// Type Parsing.
2000//===----------------------------------------------------------------------===//
2001
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002003bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002004 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 switch (Lex.getKind()) {
2006 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002007 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002009 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002011 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002012 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002013 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 // Type ::= StructType
2015 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016 return true;
2017 break;
2018 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020 Lex.Lex(); // eat the lsquare.
2021 if (ParseArrayVectorType(Result, false))
2022 return true;
2023 break;
2024 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002026 Lex.Lex();
2027 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002028 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002029 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002030 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002031 } else if (ParseArrayVectorType(Result, true))
2032 return true;
2033 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002034 case lltok::LocalVar: {
2035 // Type ::= %foo
2036 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038 // If the type hasn't been defined yet, create a forward definition and
2039 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002040 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002041 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002043 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002045 Lex.Lex();
2046 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 case lltok::LocalVarID: {
2050 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053 // If the type hasn't been defined yet, create a forward definition and
2054 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002055 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002056 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002057 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002059 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002060 Lex.Lex();
2061 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 }
2063 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002064
2065 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002066 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 switch (Lex.getKind()) {
2068 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 default:
2070 if (!AllowVoid && Result->isVoidTy())
2071 return Error(TypeLoc, "void type only allowed for function results");
2072 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002077 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078 if (Result->isVoidTy())
2079 return TokError("pointers to void are invalid - use i8* instead");
2080 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002081 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002082 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002083 Lex.Lex();
2084 break;
2085
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002089 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002090 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002091 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002092 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002093 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094 unsigned AddrSpace;
2095 if (ParseOptionalAddrSpace(AddrSpace) ||
2096 ParseToken(lltok::star, "expected '*' in address space"))
2097 return true;
2098
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 break;
2101 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002102
Chris Lattnerac161bf2009-01-02 07:01:27 +00002103 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2104 case lltok::lparen:
2105 if (ParseFunctionType(Result))
2106 return true;
2107 break;
2108 }
2109 }
2110}
2111
2112/// ParseParameterList
2113/// ::= '(' ')'
2114/// ::= '(' Arg (',' Arg)* ')'
2115/// Arg
2116/// ::= Type OptionalAttributes Value OptionalAttributes
2117bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002118 PerFunctionState &PFS, bool IsMustTailCall,
2119 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 if (ParseToken(lltok::lparen, "expected '(' in call"))
2121 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 while (Lex.getKind() != lltok::rparen) {
2124 // If this isn't the first argument, we need a comma.
2125 if (!ArgList.empty() &&
2126 ParseToken(lltok::comma, "expected ',' in argument list"))
2127 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002128
Reid Kleckner83498642014-08-26 00:33:28 +00002129 // Parse an ellipsis if this is a musttail call in a variadic function.
2130 if (Lex.getKind() == lltok::dotdotdot) {
2131 const char *Msg = "unexpected ellipsis in argument list for ";
2132 if (!IsMustTailCall)
2133 return TokError(Twine(Msg) + "non-musttail call");
2134 if (!InVarArgsFunc)
2135 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2136 Lex.Lex(); // Lex the '...', it is purely for readability.
2137 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2138 }
2139
Chris Lattnerac161bf2009-01-02 07:01:27 +00002140 // Parse the argument.
2141 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002142 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002143 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002145 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002147
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002148 if (ArgTy->isMetadataTy()) {
2149 if (ParseMetadataAsValue(V, PFS))
2150 return true;
2151 } else {
2152 // Otherwise, handle normal operands.
2153 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2154 return true;
2155 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002156 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002157 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 }
2159
Reid Kleckner83498642014-08-26 00:33:28 +00002160 if (IsMustTailCall && InVarArgsFunc)
2161 return TokError("expected '...' at end of argument list for musttail call "
2162 "in varargs function");
2163
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 Lex.Lex(); // Lex the ')'.
2165 return false;
2166}
2167
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002168/// ParseOptionalOperandBundles
2169/// ::= /*empty*/
2170/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2171///
2172/// OperandBundle
2173/// ::= bundle-tag '(' ')'
2174/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2175///
2176/// bundle-tag ::= String Constant
2177bool LLParser::ParseOptionalOperandBundles(
2178 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2179 LocTy BeginLoc = Lex.getLoc();
2180 if (!EatIfPresent(lltok::lsquare))
2181 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002183 while (Lex.getKind() != lltok::rsquare) {
2184 // If this isn't the first operand bundle, we need a comma.
2185 if (!BundleList.empty() &&
2186 ParseToken(lltok::comma, "expected ',' in input list"))
2187 return true;
2188
2189 std::string Tag;
2190 if (ParseStringConstant(Tag))
2191 return true;
2192
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002193 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2194 return true;
2195
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002196 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002197 while (Lex.getKind() != lltok::rparen) {
2198 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002199 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002200 ParseToken(lltok::comma, "expected ',' in input list"))
2201 return true;
2202
2203 Type *Ty = nullptr;
2204 Value *Input = nullptr;
2205 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2206 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002207 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002208 }
2209
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002210 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2211
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002212 Lex.Lex(); // Lex the ')'.
2213 }
2214
2215 if (BundleList.empty())
2216 return Error(BeginLoc, "operand bundle set must not be empty");
2217
2218 Lex.Lex(); // Lex the ']'.
2219 return false;
2220}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221
Chris Lattner2ed06b42009-01-05 18:34:07 +00002222/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002223/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002224/// ::= '(' ArgTypeListI ')'
2225/// ArgTypeListI
2226/// ::= /*empty*/
2227/// ::= '...'
2228/// ::= ArgTypeList ',' '...'
2229/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002230///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002231bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2232 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 isVarArg = false;
2234 assert(Lex.getKind() == lltok::lparen);
2235 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Chris Lattnerac161bf2009-01-02 07:01:27 +00002237 if (Lex.getKind() == lltok::rparen) {
2238 // empty
2239 } else if (Lex.getKind() == lltok::dotdotdot) {
2240 isVarArg = true;
2241 Lex.Lex();
2242 } else {
2243 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002244 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002245 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002248 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002249 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002250
Chris Lattnerfdd87902009-10-05 05:54:46 +00002251 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002252 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Chris Lattnerdef19492011-06-17 06:36:20 +00002254 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 Name = Lex.getStrVal();
2256 Lex.Lex();
2257 }
Chris Lattner3822f632009-01-02 08:05:26 +00002258
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002259 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002260 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002262 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002263 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002264 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Chris Lattner3822f632009-01-02 08:05:26 +00002266 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002268 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002270 break;
2271 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002272
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 // Otherwise must be an argument type.
2274 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002275 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002276
Chris Lattnerfdd87902009-10-05 05:54:46 +00002277 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002278 return Error(TypeLoc, "argument can not have void type");
2279
Chris Lattnerdef19492011-06-17 06:36:20 +00002280 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 Name = Lex.getStrVal();
2282 Lex.Lex();
2283 } else {
2284 Name = "";
2285 }
Chris Lattner3822f632009-01-02 08:05:26 +00002286
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002287 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002288 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002290 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002291 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002292 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 }
2294 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002295
Chris Lattner3822f632009-01-02 08:05:26 +00002296 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattnerac161bf2009-01-02 07:01:27 +00002299/// ParseFunctionType
2300/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002301bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002302 assert(Lex.getKind() == lltok::lparen);
2303
Chris Lattnerce473c72009-01-05 08:04:33 +00002304 if (!FunctionType::isValidReturnType(Result))
2305 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002309 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002311
Chris Lattnerac161bf2009-01-02 07:01:27 +00002312 // Reject names on the arguments lists.
2313 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2314 if (!ArgList[i].Name.empty())
2315 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002316 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002317 return Error(ArgList[i].Loc,
2318 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002319 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002320
Jay Foadb804a2b2011-07-12 14:06:48 +00002321 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002322 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002323 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326 return false;
2327}
2328
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2330/// other structs.
2331bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2332 SmallVector<Type*, 8> Elts;
2333 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 Result = StructType::get(Context, Elts, Packed);
2336 return false;
2337}
2338
2339/// ParseStructDefinition - Parse a struct in a 'type' definition.
2340bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2341 std::pair<Type*, LocTy> &Entry,
2342 Type *&ResultTy) {
2343 // If the type was already defined, diagnose the redefinition.
2344 if (Entry.first && !Entry.second.isValid())
2345 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002347 // If we have opaque, just return without filling in the definition for the
2348 // struct. This counts as a definition as far as the .ll file goes.
2349 if (EatIfPresent(lltok::kw_opaque)) {
2350 // This type is being defined, so clear the location to indicate this.
2351 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002353 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002354 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002355 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002356 ResultTy = Entry.first;
2357 return false;
2358 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002359
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002360 // If the type starts with '<', then it is either a packed struct or a vector.
2361 bool isPacked = EatIfPresent(lltok::less);
2362
2363 // If we don't have a struct, then we have a random type alias, which we
2364 // accept for compatibility with old files. These types are not allowed to be
2365 // forward referenced and not allowed to be recursive.
2366 if (Lex.getKind() != lltok::lbrace) {
2367 if (Entry.first)
2368 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002369
Craig Topper2617dcc2014-04-15 06:32:26 +00002370 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002371 if (isPacked)
2372 return ParseArrayVectorType(ResultTy, true);
2373 return ParseType(ResultTy);
2374 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002375
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002376 // This type is being defined, so clear the location to indicate this.
2377 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002379 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002380 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002381 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 SmallVector<Type*, 8> Body;
2386 if (ParseStructBody(Body) ||
2387 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2388 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002389
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002390 STy->setBody(Body, isPacked);
2391 ResultTy = STy;
2392 return false;
2393}
2394
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002398/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002399/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002400/// ::= '<' '{' Type (',' Type)* '}' '>'
2401bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002402 assert(Lex.getKind() == lltok::lbrace);
2403 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002405 // Handle the empty struct.
2406 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002408
Chris Lattnerf880ca22009-03-09 04:49:14 +00002409 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002410 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002411 if (ParseType(Ty)) return true;
2412 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002413
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002414 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002415 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002416
Chris Lattner3822f632009-01-02 08:05:26 +00002417 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002418 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002419 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002421 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002422 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002423
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002424 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002425 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002426
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002427 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428}
2429
2430/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2431/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002432/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433/// ::= '[' APSINTVAL 'x' Types ']'
2434/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002435bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2437 Lex.getAPSIntVal().getBitWidth() > 64)
2438 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002439
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 LocTy SizeLoc = Lex.getLoc();
2441 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002442 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002443
Chris Lattner3822f632009-01-02 08:05:26 +00002444 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2445 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446
2447 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002448 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002449 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002450
Chris Lattner3822f632009-01-02 08:05:26 +00002451 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2452 "expected end of sequential type"))
2453 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002454
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002456 if (Size == 0)
2457 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 if ((unsigned)Size != Size)
2459 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002460 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002461 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002462 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002463 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002464 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002466 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 }
2468 return false;
2469}
2470
2471//===----------------------------------------------------------------------===//
2472// Function Semantic Analysis.
2473//===----------------------------------------------------------------------===//
2474
Chris Lattner3432c622009-10-28 03:39:23 +00002475LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2476 int functionNumber)
2477 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478
2479 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002480 for (Argument &A : F.args())
2481 if (!A.hasName())
2482 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483}
2484
2485LLParser::PerFunctionState::~PerFunctionState() {
2486 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
David Blaikie9ebdc692015-09-21 21:07:50 +00002488 for (const auto &P : ForwardRefVals) {
2489 if (isa<BasicBlock>(P.second.first))
2490 continue;
2491 P.second.first->replaceAllUsesWith(
2492 UndefValue::get(P.second.first->getType()));
2493 delete P.second.first;
2494 }
2495
2496 for (const auto &P : ForwardRefValIDs) {
2497 if (isa<BasicBlock>(P.second.first))
2498 continue;
2499 P.second.first->replaceAllUsesWith(
2500 UndefValue::get(P.second.first->getType()));
2501 delete P.second.first;
2502 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503}
2504
Chris Lattner3432c622009-10-28 03:39:23 +00002505bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002506 if (!ForwardRefVals.empty())
2507 return P.Error(ForwardRefVals.begin()->second.second,
2508 "use of undefined value '%" + ForwardRefVals.begin()->first +
2509 "'");
2510 if (!ForwardRefValIDs.empty())
2511 return P.Error(ForwardRefValIDs.begin()->second.second,
2512 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002513 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 return false;
2515}
2516
Chris Lattnerac161bf2009-01-02 07:01:27 +00002517/// GetVal - Get a value with the specified name or ID, creating a
2518/// forward reference record if needed. This can return null if the value
2519/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002520Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002521 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002522 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002523 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 // If this is a forward reference for the value, see if we already created a
2526 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002527 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002528 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 if (I != ForwardRefVals.end())
2530 Val = I->second.first;
2531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002532
Chris Lattnerac161bf2009-01-02 07:01:27 +00002533 // If we have the value in the symbol table or fwd-ref table, return it.
2534 if (Val) {
2535 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002536 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002537 P.Error(Loc, "'%" + Name + "' is not a basic block");
2538 else
2539 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002540 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002541 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002543
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002545 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002546 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002547 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002549
Chris Lattnerac161bf2009-01-02 07:01:27 +00002550 // Otherwise, create a new forward reference for this value and remember it.
2551 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002552 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002553 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002554 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002555 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002556 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002557
Chris Lattnerac161bf2009-01-02 07:01:27 +00002558 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2559 return FwdVal;
2560}
2561
David Majnemer8a1c45d2015-12-12 05:38:55 +00002562Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002563 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002564 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002565
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 // If this is a forward reference for the value, see if we already created a
2567 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002568 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002569 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 if (I != ForwardRefValIDs.end())
2571 Val = I->second.first;
2572 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002573
Chris Lattnerac161bf2009-01-02 07:01:27 +00002574 // If we have the value in the symbol table or fwd-ref table, return it.
2575 if (Val) {
2576 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002577 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002578 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002580 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002581 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002582 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002583 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002584
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002585 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002587 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002589
Chris Lattnerac161bf2009-01-02 07:01:27 +00002590 // Otherwise, create a new forward reference for this value and remember it.
2591 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002592 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002593 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002594 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002595 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002596 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002597
Chris Lattnerac161bf2009-01-02 07:01:27 +00002598 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2599 return FwdVal;
2600}
2601
2602/// SetInstName - After an instruction is parsed and inserted into its
2603/// basic block, this installs its name.
2604bool LLParser::PerFunctionState::SetInstName(int NameID,
2605 const std::string &NameStr,
2606 LocTy NameLoc, Instruction *Inst) {
2607 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002608 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002609 if (NameID != -1 || !NameStr.empty())
2610 return P.Error(NameLoc, "instructions returning void cannot have a name");
2611 return false;
2612 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002613
Chris Lattnerac161bf2009-01-02 07:01:27 +00002614 // If this was a numbered instruction, verify that the instruction is the
2615 // expected value and resolve any forward references.
2616 if (NameStr.empty()) {
2617 // If neither a name nor an ID was specified, just use the next ID.
2618 if (NameID == -1)
2619 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002620
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 if (unsigned(NameID) != NumberedVals.size())
2622 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002623 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002624
David Blaikie9ebdc692015-09-21 21:07:50 +00002625 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002627 Value *Sentinel = FI->second.first;
2628 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002629 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002630 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002631
2632 Sentinel->replaceAllUsesWith(Inst);
2633 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634 ForwardRefValIDs.erase(FI);
2635 }
2636
2637 NumberedVals.push_back(Inst);
2638 return false;
2639 }
2640
2641 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002642 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002644 Value *Sentinel = FI->second.first;
2645 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002647 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002648
2649 Sentinel->replaceAllUsesWith(Inst);
2650 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 ForwardRefVals.erase(FI);
2652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002653
Chris Lattnerac161bf2009-01-02 07:01:27 +00002654 // Set the name on the instruction.
2655 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002657 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 NameStr + "'");
2660 return false;
2661}
2662
2663/// GetBB - Get a basic block with the specified name or ID, creating a
2664/// forward reference record if needed.
2665BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2666 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002667 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2668 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002669}
2670
2671BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002672 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2673 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674}
2675
2676/// DefineBB - Define the specified basic block, which is either named or
2677/// unnamed. If there is an error, this returns null otherwise it returns
2678/// the block being defined.
2679BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2680 LocTy Loc) {
2681 BasicBlock *BB;
2682 if (Name.empty())
2683 BB = GetBB(NumberedVals.size(), Loc);
2684 else
2685 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002686 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002687
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 // Move the block to the end of the function. Forward ref'd blocks are
2689 // inserted wherever they happen to be referenced.
2690 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002691
Chris Lattnerac161bf2009-01-02 07:01:27 +00002692 // Remove the block from forward ref sets.
2693 if (Name.empty()) {
2694 ForwardRefValIDs.erase(NumberedVals.size());
2695 NumberedVals.push_back(BB);
2696 } else {
2697 // BB forward references are already in the function symbol table.
2698 ForwardRefVals.erase(Name);
2699 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002700
Chris Lattnerac161bf2009-01-02 07:01:27 +00002701 return BB;
2702}
2703
2704//===----------------------------------------------------------------------===//
2705// Constants.
2706//===----------------------------------------------------------------------===//
2707
2708/// ParseValID - Parse an abstract value that doesn't necessarily have a
2709/// type implied. For example, if we parse "4" we don't know what integer type
2710/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002711/// sanity. PFS is used to convert function-local operands of metadata (since
2712/// metadata operands are not just parsed here but also converted to values).
2713/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002714bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002715 ID.Loc = Lex.getLoc();
2716 switch (Lex.getKind()) {
2717 default: return TokError("expected value token");
2718 case lltok::GlobalID: // @42
2719 ID.UIntVal = Lex.getUIntVal();
2720 ID.Kind = ValID::t_GlobalID;
2721 break;
2722 case lltok::GlobalVar: // @foo
2723 ID.StrVal = Lex.getStrVal();
2724 ID.Kind = ValID::t_GlobalName;
2725 break;
2726 case lltok::LocalVarID: // %42
2727 ID.UIntVal = Lex.getUIntVal();
2728 ID.Kind = ValID::t_LocalID;
2729 break;
2730 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002731 ID.StrVal = Lex.getStrVal();
2732 ID.Kind = ValID::t_LocalName;
2733 break;
2734 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002735 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002736 ID.Kind = ValID::t_APSInt;
2737 break;
2738 case lltok::APFloat:
2739 ID.APFloatVal = Lex.getAPFloatVal();
2740 ID.Kind = ValID::t_APFloat;
2741 break;
2742 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002743 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 ID.Kind = ValID::t_Constant;
2745 break;
2746 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002747 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002748 ID.Kind = ValID::t_Constant;
2749 break;
2750 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2751 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2752 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002753 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002754
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 case lltok::lbrace: {
2756 // ValID ::= '{' ConstVector '}'
2757 Lex.Lex();
2758 SmallVector<Constant*, 16> Elts;
2759 if (ParseGlobalValueVector(Elts) ||
2760 ParseToken(lltok::rbrace, "expected end of struct constant"))
2761 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002762
David Blaikieadbda4b2015-08-03 20:08:41 +00002763 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002764 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002765 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2766 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002767 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002768 return false;
2769 }
2770 case lltok::less: {
2771 // ValID ::= '<' ConstVector '>' --> Vector.
2772 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2773 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002774 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 SmallVector<Constant*, 16> Elts;
2777 LocTy FirstEltLoc = Lex.getLoc();
2778 if (ParseGlobalValueVector(Elts) ||
2779 (isPackedStruct &&
2780 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2781 ParseToken(lltok::greater, "expected end of constant"))
2782 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002783
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002785 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2786 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2787 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002788 ID.UIntVal = Elts.size();
2789 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 return false;
2791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 if (Elts.empty())
2794 return Error(ID.Loc, "constant vector must not be empty");
2795
Duncan Sands9dff9be2010-02-15 16:12:20 +00002796 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002797 !Elts[0]->getType()->isFloatingPointTy() &&
2798 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002799 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002800 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002801
Chris Lattnerac161bf2009-01-02 07:01:27 +00002802 // Verify that all the vector elements have the same type.
2803 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2804 if (Elts[i]->getType() != Elts[0]->getType())
2805 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002806 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002807 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808
Chris Lattner69229312011-02-15 00:14:00 +00002809 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 ID.Kind = ValID::t_Constant;
2811 return false;
2812 }
2813 case lltok::lsquare: { // Array Constant
2814 Lex.Lex();
2815 SmallVector<Constant*, 16> Elts;
2816 LocTy FirstEltLoc = Lex.getLoc();
2817 if (ParseGlobalValueVector(Elts) ||
2818 ParseToken(lltok::rsquare, "expected end of array constant"))
2819 return true;
2820
2821 // Handle empty element.
2822 if (Elts.empty()) {
2823 // Use undef instead of an array because it's inconvenient to determine
2824 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002825 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 return false;
2827 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002828
Chris Lattnerac161bf2009-01-02 07:01:27 +00002829 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002830 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002831 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Owen Anderson4056ca92009-07-29 22:17:13 +00002833 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002836 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 if (Elts[i]->getType() != Elts[0]->getType())
2838 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002839 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002840 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002842
Jay Foad83be3612011-06-22 09:24:39 +00002843 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 ID.Kind = ValID::t_Constant;
2845 return false;
2846 }
2847 case lltok::kw_c: // c "foo"
2848 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002849 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2850 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002851 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2852 ID.Kind = ValID::t_Constant;
2853 return false;
2854
2855 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002856 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2857 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002858 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002859 Lex.Lex();
2860 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002861 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002862 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002863 ParseStringConstant(ID.StrVal) ||
2864 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002865 ParseToken(lltok::StringConstant, "expected constraint string"))
2866 return true;
2867 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002868 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002869 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002870 ID.Kind = ValID::t_InlineAsm;
2871 return false;
2872 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002873
Chris Lattner3432c622009-10-28 03:39:23 +00002874 case lltok::kw_blockaddress: {
2875 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2876 Lex.Lex();
2877
2878 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002879
Chris Lattner3432c622009-10-28 03:39:23 +00002880 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2881 ParseValID(Fn) ||
2882 ParseToken(lltok::comma, "expected comma in block address expression")||
2883 ParseValID(Label) ||
2884 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2885 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002886
Chris Lattner3432c622009-10-28 03:39:23 +00002887 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2888 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002889 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002890 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002891
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002892 // Try to find the function (but skip it if it's forward-referenced).
2893 GlobalValue *GV = nullptr;
2894 if (Fn.Kind == ValID::t_GlobalID) {
2895 if (Fn.UIntVal < NumberedVals.size())
2896 GV = NumberedVals[Fn.UIntVal];
2897 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2898 GV = M->getNamedValue(Fn.StrVal);
2899 }
2900 Function *F = nullptr;
2901 if (GV) {
2902 // Confirm that it's actually a function with a definition.
2903 if (!isa<Function>(GV))
2904 return Error(Fn.Loc, "expected function name in blockaddress");
2905 F = cast<Function>(GV);
2906 if (F->isDeclaration())
2907 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2908 }
2909
2910 if (!F) {
2911 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002912 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002913 ForwardRefBlockAddresses.insert(std::make_pair(
2914 std::move(Fn),
2915 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002916 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2917 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002918 if (!FwdRef)
2919 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2920 GlobalValue::InternalLinkage, nullptr, "");
2921 ID.ConstantVal = FwdRef;
2922 ID.Kind = ValID::t_Constant;
2923 return false;
2924 }
2925
2926 // We found the function; now find the basic block. Don't use PFS, since we
2927 // might be inside a constant expression.
2928 BasicBlock *BB;
2929 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2930 if (Label.Kind == ValID::t_LocalID)
2931 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2932 else
2933 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2934 if (!BB)
2935 return Error(Label.Loc, "referenced value is not a basic block");
2936 } else {
2937 if (Label.Kind == ValID::t_LocalID)
2938 return Error(Label.Loc, "cannot take address of numeric label after "
2939 "the function is defined");
2940 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002941 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002942 if (!BB)
2943 return Error(Label.Loc, "referenced value is not a basic block");
2944 }
2945
2946 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002947 ID.Kind = ValID::t_Constant;
2948 return false;
2949 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002950
Chris Lattnerac161bf2009-01-02 07:01:27 +00002951 case lltok::kw_trunc:
2952 case lltok::kw_zext:
2953 case lltok::kw_sext:
2954 case lltok::kw_fptrunc:
2955 case lltok::kw_fpext:
2956 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002957 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002958 case lltok::kw_uitofp:
2959 case lltok::kw_sitofp:
2960 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002963 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002964 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002965 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002966 Constant *SrcVal;
2967 Lex.Lex();
2968 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2969 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002970 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 ParseType(DestTy) ||
2972 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2973 return true;
2974 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2975 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002976 getTypeString(SrcVal->getType()) + "' to '" +
2977 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002978 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002979 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002980 ID.Kind = ValID::t_Constant;
2981 return false;
2982 }
2983 case lltok::kw_extractvalue: {
2984 Lex.Lex();
2985 Constant *Val;
2986 SmallVector<unsigned, 4> Indices;
2987 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2988 ParseGlobalTypeAndValue(Val) ||
2989 ParseIndexList(Indices) ||
2990 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2991 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002992
Chris Lattner392be582010-02-12 20:49:41 +00002993 if (!Val->getType()->isAggregateType())
2994 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002995 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002997 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002998 ID.Kind = ValID::t_Constant;
2999 return false;
3000 }
3001 case lltok::kw_insertvalue: {
3002 Lex.Lex();
3003 Constant *Val0, *Val1;
3004 SmallVector<unsigned, 4> Indices;
3005 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3006 ParseGlobalTypeAndValue(Val0) ||
3007 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3008 ParseGlobalTypeAndValue(Val1) ||
3009 ParseIndexList(Indices) ||
3010 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3011 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003012 if (!Val0->getType()->isAggregateType())
3013 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003014 Type *IndexedType =
3015 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3016 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003017 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003018 if (IndexedType != Val1->getType())
3019 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3020 getTypeString(Val1->getType()) +
3021 "' instead of '" + getTypeString(IndexedType) +
3022 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003023 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003024 ID.Kind = ValID::t_Constant;
3025 return false;
3026 }
3027 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003028 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 unsigned PredVal, Opc = Lex.getUIntVal();
3030 Constant *Val0, *Val1;
3031 Lex.Lex();
3032 if (ParseCmpPredicate(PredVal, Opc) ||
3033 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3034 ParseGlobalTypeAndValue(Val0) ||
3035 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3036 ParseGlobalTypeAndValue(Val1) ||
3037 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3038 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003039
Chris Lattnerac161bf2009-01-02 07:01:27 +00003040 if (Val0->getType() != Val1->getType())
3041 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003044
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003046 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003048 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003049 } else {
3050 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003051 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003052 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003054 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003055 }
3056 ID.Kind = ValID::t_Constant;
3057 return false;
3058 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003059
Chris Lattnerac161bf2009-01-02 07:01:27 +00003060 // Binary Operators.
3061 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003062 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003064 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003066 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003067 case lltok::kw_udiv:
3068 case lltok::kw_sdiv:
3069 case lltok::kw_fdiv:
3070 case lltok::kw_urem:
3071 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003072 case lltok::kw_frem:
3073 case lltok::kw_shl:
3074 case lltok::kw_lshr:
3075 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003076 bool NUW = false;
3077 bool NSW = false;
3078 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 unsigned Opc = Lex.getUIntVal();
3080 Constant *Val0, *Val1;
3081 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003082 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003083 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3084 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003085 if (EatIfPresent(lltok::kw_nuw))
3086 NUW = true;
3087 if (EatIfPresent(lltok::kw_nsw)) {
3088 NSW = true;
3089 if (EatIfPresent(lltok::kw_nuw))
3090 NUW = true;
3091 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003092 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3093 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003094 if (EatIfPresent(lltok::kw_exact))
3095 Exact = true;
3096 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003097 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3098 ParseGlobalTypeAndValue(Val0) ||
3099 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3100 ParseGlobalTypeAndValue(Val1) ||
3101 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3102 return true;
3103 if (Val0->getType() != Val1->getType())
3104 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003105 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003106 if (NUW)
3107 return Error(ModifierLoc, "nuw only applies to integer operations");
3108 if (NSW)
3109 return Error(ModifierLoc, "nsw only applies to integer operations");
3110 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003111 // Check that the type is valid for the operator.
3112 switch (Opc) {
3113 case Instruction::Add:
3114 case Instruction::Sub:
3115 case Instruction::Mul:
3116 case Instruction::UDiv:
3117 case Instruction::SDiv:
3118 case Instruction::URem:
3119 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003120 case Instruction::Shl:
3121 case Instruction::AShr:
3122 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003123 if (!Val0->getType()->isIntOrIntVectorTy())
3124 return Error(ID.Loc, "constexpr requires integer operands");
3125 break;
3126 case Instruction::FAdd:
3127 case Instruction::FSub:
3128 case Instruction::FMul:
3129 case Instruction::FDiv:
3130 case Instruction::FRem:
3131 if (!Val0->getType()->isFPOrFPVectorTy())
3132 return Error(ID.Loc, "constexpr requires fp operands");
3133 break;
3134 default: llvm_unreachable("Unknown binary operator!");
3135 }
Dan Gohman1b849082009-09-07 23:54:19 +00003136 unsigned Flags = 0;
3137 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3138 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003139 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003140 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003141 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003142 ID.Kind = ValID::t_Constant;
3143 return false;
3144 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003145
Chris Lattnerac161bf2009-01-02 07:01:27 +00003146 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 case lltok::kw_and:
3148 case lltok::kw_or:
3149 case lltok::kw_xor: {
3150 unsigned Opc = Lex.getUIntVal();
3151 Constant *Val0, *Val1;
3152 Lex.Lex();
3153 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3154 ParseGlobalTypeAndValue(Val0) ||
3155 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3156 ParseGlobalTypeAndValue(Val1) ||
3157 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3158 return true;
3159 if (Val0->getType() != Val1->getType())
3160 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003161 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003162 return Error(ID.Loc,
3163 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003164 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003165 ID.Kind = ValID::t_Constant;
3166 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003167 }
3168
Chris Lattnerac161bf2009-01-02 07:01:27 +00003169 case lltok::kw_getelementptr:
3170 case lltok::kw_shufflevector:
3171 case lltok::kw_insertelement:
3172 case lltok::kw_extractelement:
3173 case lltok::kw_select: {
3174 unsigned Opc = Lex.getUIntVal();
3175 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003176 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003177 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003179
Dan Gohman1639c392009-07-27 21:53:46 +00003180 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003181 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003182
3183 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3184 return true;
3185
3186 LocTy ExplicitTypeLoc = Lex.getLoc();
3187 if (Opc == Instruction::GetElementPtr) {
3188 if (ParseType(Ty) ||
3189 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3190 return true;
3191 }
3192
Peter Collingbourned93620b2016-11-10 22:34:55 +00003193 Optional<unsigned> InRangeOp;
3194 if (ParseGlobalValueVector(
3195 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003196 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3197 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattnerac161bf2009-01-02 07:01:27 +00003199 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003200 if (Elts.size() == 0 ||
3201 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003202 return Error(ID.Loc, "base of getelementptr must be a pointer");
3203
3204 Type *BaseType = Elts[0]->getType();
3205 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003206 if (Ty != BasePointerType->getElementType())
3207 return Error(
3208 ExplicitTypeLoc,
3209 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003210
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003211 unsigned GEPWidth =
3212 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3213
Jay Foaded8db7d2011-07-21 14:31:17 +00003214 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003215 for (Constant *Val : Indices) {
3216 Type *ValTy = Val->getType();
3217 if (!ValTy->getScalarType()->isIntegerTy())
3218 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003219 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003220 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003221 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003222 return Error(
3223 ID.Loc,
3224 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003225 // GEPWidth may have been unknown because the base is a scalar,
3226 // but it is known now.
3227 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003228 }
3229 }
3230
Craig Toppere3dcce92015-08-01 22:20:21 +00003231 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003232 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003233 return Error(ID.Loc, "base element of getelementptr must be sized");
3234
David Blaikie4a2e73b2015-04-02 18:55:32 +00003235 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003236 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003237
3238 if (InRangeOp) {
3239 if (*InRangeOp == 0)
3240 return Error(ID.Loc,
3241 "inrange keyword may not appear on pointer operand");
3242 --*InRangeOp;
3243 }
3244
3245 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3246 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003247 } else if (Opc == Instruction::Select) {
3248 if (Elts.size() != 3)
3249 return Error(ID.Loc, "expected three operands to select");
3250 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3251 Elts[2]))
3252 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003253 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003254 } else if (Opc == Instruction::ShuffleVector) {
3255 if (Elts.size() != 3)
3256 return Error(ID.Loc, "expected three operands to shufflevector");
3257 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3258 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003259 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003260 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003261 } else if (Opc == Instruction::ExtractElement) {
3262 if (Elts.size() != 2)
3263 return Error(ID.Loc, "expected two operands to extractelement");
3264 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3265 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003266 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003267 } else {
3268 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3269 if (Elts.size() != 3)
3270 return Error(ID.Loc, "expected three operands to insertelement");
3271 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3272 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003273 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003274 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003276
Chris Lattnerac161bf2009-01-02 07:01:27 +00003277 ID.Kind = ValID::t_Constant;
3278 return false;
3279 }
3280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003281
Chris Lattnerac161bf2009-01-02 07:01:27 +00003282 Lex.Lex();
3283 return false;
3284}
3285
3286/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003287bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003288 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003289 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003290 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003291 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003292 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003293 if (V && !(C = dyn_cast<Constant>(V)))
3294 return Error(ID.Loc, "global values must be constants");
3295 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003296}
3297
Victor Hernandez9d75c962010-01-11 22:31:58 +00003298bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003299 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003300 return ParseType(Ty) ||
3301 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003302}
3303
Rafael Espindola83a362c2015-01-06 22:55:16 +00003304bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003305 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003306
3307 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003308 if (!EatIfPresent(lltok::kw_comdat))
3309 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003310
3311 if (EatIfPresent(lltok::lparen)) {
3312 if (Lex.getKind() != lltok::ComdatVar)
3313 return TokError("expected comdat variable");
3314 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3315 Lex.Lex();
3316 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3317 return true;
3318 } else {
3319 if (GlobalName.empty())
3320 return TokError("comdat cannot be unnamed");
3321 C = getComdat(GlobalName, KwLoc);
3322 }
3323
David Majnemerdad0a642014-06-27 18:19:56 +00003324 return false;
3325}
3326
Victor Hernandez9d75c962010-01-11 22:31:58 +00003327/// ParseGlobalValueVector
3328/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003329/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3330bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3331 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003332 // Empty list.
3333 if (Lex.getKind() == lltok::rbrace ||
3334 Lex.getKind() == lltok::rsquare ||
3335 Lex.getKind() == lltok::greater ||
3336 Lex.getKind() == lltok::rparen)
3337 return false;
3338
Peter Collingbourned93620b2016-11-10 22:34:55 +00003339 do {
3340 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3341 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003342
Peter Collingbourned93620b2016-11-10 22:34:55 +00003343 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003344 if (ParseGlobalTypeAndValue(C)) return true;
3345 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003346 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003347
3348 return false;
3349}
3350
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003351bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003352 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003353 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003354 return true;
3355
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003356 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003357 return false;
3358}
3359
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003360/// MDNode:
3361/// ::= !{ ... }
3362/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003363/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003364bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003365 if (Lex.getKind() == lltok::MetadataVar)
3366 return ParseSpecializedMDNode(N);
3367
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003368 return ParseToken(lltok::exclaim, "expected '!' here") ||
3369 ParseMDNodeTail(N);
3370}
3371
3372bool LLParser::ParseMDNodeTail(MDNode *&N) {
3373 // !{ ... }
3374 if (Lex.getKind() == lltok::lbrace)
3375 return ParseMDTuple(N);
3376
3377 // !42
3378 return ParseMDNodeID(N);
3379}
3380
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003381namespace {
3382
3383/// Structure to represent an optional metadata field.
3384template <class FieldTy> struct MDFieldImpl {
3385 typedef MDFieldImpl ImplTy;
3386 FieldTy Val;
3387 bool Seen;
3388
3389 void assign(FieldTy Val) {
3390 Seen = true;
3391 this->Val = std::move(Val);
3392 }
3393
3394 explicit MDFieldImpl(FieldTy Default)
3395 : Val(std::move(Default)), Seen(false) {}
3396};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003397
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003398struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3399 uint64_t Max;
3400
3401 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3402 : ImplTy(Default), Max(Max) {}
3403};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003404
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003405struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003406 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003407};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003408
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003409struct ColumnField : public MDUnsignedField {
3410 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3411};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003412
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003413struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003414 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003415 DwarfTagField(dwarf::Tag DefaultTag)
3416 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003417};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003418
Amjad Abouda9bcf162015-12-10 12:56:35 +00003419struct DwarfMacinfoTypeField : public MDUnsignedField {
3420 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3421 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3422 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3423};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003424
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003425struct DwarfAttEncodingField : public MDUnsignedField {
3426 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3427};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003428
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003429struct DwarfVirtualityField : public MDUnsignedField {
3430 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3431};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003432
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003433struct DwarfLangField : public MDUnsignedField {
3434 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3435};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003436
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003437struct DwarfCCField : public MDUnsignedField {
3438 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3439};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003440
Adrian Prantlb939a252016-03-31 23:56:58 +00003441struct EmissionKindField : public MDUnsignedField {
3442 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3443};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003444
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003445struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3446 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003447};
3448
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003449struct MDSignedField : public MDFieldImpl<int64_t> {
3450 int64_t Min;
3451 int64_t Max;
3452
3453 MDSignedField(int64_t Default = 0)
3454 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3455 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3456 : ImplTy(Default), Min(Min), Max(Max) {}
3457};
3458
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003459struct MDBoolField : public MDFieldImpl<bool> {
3460 MDBoolField(bool Default = false) : ImplTy(Default) {}
3461};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003462
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003463struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003464 bool AllowNull;
3465
3466 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003467};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003468
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003469struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3470 MDConstant() : ImplTy(nullptr) {}
3471};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003472
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003473struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003474 bool AllowEmpty;
3475 MDStringField(bool AllowEmpty = true)
3476 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003477};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003478
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003479struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3480 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3481};
3482
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003483struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3484 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3485 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3486};
3487
Eugene Zelenko1804a772016-08-25 00:45:04 +00003488} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003489
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003490namespace llvm {
3491
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003492template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003493bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003494 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003495 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3496 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003497
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003498 auto &U = Lex.getAPSIntVal();
3499 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003500 return TokError("value for '" + Name + "' too large, limit is " +
3501 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003502 Result.assign(U.getZExtValue());
3503 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003504 Lex.Lex();
3505 return false;
3506}
3507
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003508template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003509bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3510 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3511}
3512template <>
3513bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3514 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3515}
3516
3517template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003518bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3519 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003520 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003521
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003522 if (Lex.getKind() != lltok::DwarfTag)
3523 return TokError("expected DWARF tag");
3524
3525 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3526 if (Tag == dwarf::DW_TAG_invalid)
3527 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003528 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003529
3530 Result.assign(Tag);
3531 Lex.Lex();
3532 return false;
3533}
3534
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003535template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003536bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003537 DwarfMacinfoTypeField &Result) {
3538 if (Lex.getKind() == lltok::APSInt)
3539 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3540
3541 if (Lex.getKind() != lltok::DwarfMacinfo)
3542 return TokError("expected DWARF macinfo type");
3543
3544 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3545 if (Macinfo == dwarf::DW_MACINFO_invalid)
3546 return TokError(
3547 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3548 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3549
3550 Result.assign(Macinfo);
3551 Lex.Lex();
3552 return false;
3553}
3554
3555template <>
3556bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003557 DwarfVirtualityField &Result) {
3558 if (Lex.getKind() == lltok::APSInt)
3559 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3560
3561 if (Lex.getKind() != lltok::DwarfVirtuality)
3562 return TokError("expected DWARF virtuality code");
3563
3564 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003565 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003566 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3567 Lex.getStrVal() + "'");
3568 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3569 Result.assign(Virtuality);
3570 Lex.Lex();
3571 return false;
3572}
3573
3574template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003575bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3576 if (Lex.getKind() == lltok::APSInt)
3577 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3578
3579 if (Lex.getKind() != lltok::DwarfLang)
3580 return TokError("expected DWARF language");
3581
3582 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3583 if (!Lang)
3584 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3585 "'");
3586 assert(Lang <= Result.Max && "Expected valid DWARF language");
3587 Result.assign(Lang);
3588 Lex.Lex();
3589 return false;
3590}
3591
3592template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003593bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3594 if (Lex.getKind() == lltok::APSInt)
3595 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3596
3597 if (Lex.getKind() != lltok::DwarfCC)
3598 return TokError("expected DWARF calling convention");
3599
3600 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3601 if (!CC)
3602 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3603 "'");
3604 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3605 Result.assign(CC);
3606 Lex.Lex();
3607 return false;
3608}
3609
3610template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003611bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3612 if (Lex.getKind() == lltok::APSInt)
3613 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3614
3615 if (Lex.getKind() != lltok::EmissionKind)
3616 return TokError("expected emission kind");
3617
3618 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3619 if (!Kind)
3620 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3621 "'");
3622 assert(*Kind <= Result.Max && "Expected valid emission kind");
3623 Result.assign(*Kind);
3624 Lex.Lex();
3625 return false;
3626}
3627
3628template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003629bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003630 DwarfAttEncodingField &Result) {
3631 if (Lex.getKind() == lltok::APSInt)
3632 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3633
3634 if (Lex.getKind() != lltok::DwarfAttEncoding)
3635 return TokError("expected DWARF type attribute encoding");
3636
3637 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3638 if (!Encoding)
3639 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3640 Lex.getStrVal() + "'");
3641 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3642 Result.assign(Encoding);
3643 Lex.Lex();
3644 return false;
3645}
3646
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003647/// DIFlagField
3648/// ::= uint32
3649/// ::= DIFlagVector
3650/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3651template <>
3652bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003653
3654 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003655 auto parseFlag = [&](DINode::DIFlags &Val) {
3656 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3657 uint32_t TempVal = static_cast<uint32_t>(Val);
3658 bool Res = ParseUInt32(TempVal);
3659 Val = static_cast<DINode::DIFlags>(TempVal);
3660 return Res;
3661 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003662
3663 if (Lex.getKind() != lltok::DIFlag)
3664 return TokError("expected debug info flag");
3665
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003666 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003667 if (!Val)
3668 return TokError(Twine("invalid debug info flag flag '") +
3669 Lex.getStrVal() + "'");
3670 Lex.Lex();
3671 return false;
3672 };
3673
3674 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003675 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003676 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003677 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003678 if (parseFlag(Val))
3679 return true;
3680 Combined |= Val;
3681 } while (EatIfPresent(lltok::bar));
3682
3683 Result.assign(Combined);
3684 return false;
3685}
3686
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003687template <>
3688bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003689 MDSignedField &Result) {
3690 if (Lex.getKind() != lltok::APSInt)
3691 return TokError("expected signed integer");
3692
3693 auto &S = Lex.getAPSIntVal();
3694 if (S < Result.Min)
3695 return TokError("value for '" + Name + "' too small, limit is " +
3696 Twine(Result.Min));
3697 if (S > Result.Max)
3698 return TokError("value for '" + Name + "' too large, limit is " +
3699 Twine(Result.Max));
3700 Result.assign(S.getExtValue());
3701 assert(Result.Val >= Result.Min && "Expected value in range");
3702 assert(Result.Val <= Result.Max && "Expected value in range");
3703 Lex.Lex();
3704 return false;
3705}
3706
3707template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003708bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3709 switch (Lex.getKind()) {
3710 default:
3711 return TokError("expected 'true' or 'false'");
3712 case lltok::kw_true:
3713 Result.assign(true);
3714 break;
3715 case lltok::kw_false:
3716 Result.assign(false);
3717 break;
3718 }
3719 Lex.Lex();
3720 return false;
3721}
3722
3723template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003724bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003725 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003726 if (!Result.AllowNull)
3727 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003728 Lex.Lex();
3729 Result.assign(nullptr);
3730 return false;
3731 }
3732
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003733 Metadata *MD;
3734 if (ParseMetadata(MD, nullptr))
3735 return true;
3736
3737 Result.assign(MD);
3738 return false;
3739}
3740
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003741template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003742bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003743 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003744 std::string S;
3745 if (ParseStringConstant(S))
3746 return true;
3747
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003748 if (!Result.AllowEmpty && S.empty())
3749 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3750
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003751 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003752 return false;
3753}
3754
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003755template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003756bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3757 SmallVector<Metadata *, 4> MDs;
3758 if (ParseMDNodeVector(MDs))
3759 return true;
3760
3761 Result.assign(std::move(MDs));
3762 return false;
3763}
3764
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003765template <>
3766bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3767 ChecksumKindField &Result) {
3768 if (Lex.getKind() != lltok::ChecksumKind)
3769 return TokError(
3770 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3771
3772 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3773
3774 Result.assign(CSKind);
3775 Lex.Lex();
3776 return false;
3777}
3778
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003779} // end namespace llvm
3780
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003781template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003782bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003783 do {
3784 if (Lex.getKind() != lltok::LabelStr)
3785 return TokError("expected field label here");
3786
3787 if (parseField())
3788 return true;
3789 } while (EatIfPresent(lltok::comma));
3790
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003791 return false;
3792}
3793
3794template <class ParserTy>
3795bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3796 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3797 Lex.Lex();
3798
3799 if (ParseToken(lltok::lparen, "expected '(' here"))
3800 return true;
3801 if (Lex.getKind() != lltok::rparen)
3802 if (ParseMDFieldsImplBody(parseField))
3803 return true;
3804
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003805 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003806 return ParseToken(lltok::rparen, "expected ')' here");
3807}
3808
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003809template <class FieldTy>
3810bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3811 if (Result.Seen)
3812 return TokError("field '" + Name + "' cannot be specified more than once");
3813
3814 LocTy Loc = Lex.getLoc();
3815 Lex.Lex();
3816 return ParseMDField(Loc, Name, Result);
3817}
3818
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003819bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3820 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003821
3822#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003823 if (Lex.getStrVal() == #CLASS) \
3824 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003825#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003826
3827 return TokError("expected metadata type");
3828}
3829
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003830#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3831#define NOP_FIELD(NAME, TYPE, INIT)
3832#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3833 if (!NAME.Seen) \
3834 return Error(ClosingLoc, "missing required field '" #NAME "'");
3835#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003836 if (Lex.getStrVal() == #NAME) \
3837 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003838#define PARSE_MD_FIELDS() \
3839 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3840 do { \
3841 LocTy ClosingLoc; \
3842 if (ParseMDFieldsImpl([&]() -> bool { \
3843 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3844 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3845 }, ClosingLoc)) \
3846 return true; \
3847 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3848 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003849#define GET_OR_DISTINCT(CLASS, ARGS) \
3850 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003851
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003852/// ParseDILocationFields:
3853/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3854bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003855#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003856 OPTIONAL(line, LineField, ); \
3857 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003858 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003859 OPTIONAL(inlinedAt, MDField, );
3860 PARSE_MD_FIELDS();
3861#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003862
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003863 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003864 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003865 return false;
3866}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003867
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003868/// ParseGenericDINode:
3869/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3870bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003871#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003872 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003873 OPTIONAL(header, MDStringField, ); \
3874 OPTIONAL(operands, MDFieldList, );
3875 PARSE_MD_FIELDS();
3876#undef VISIT_MD_FIELDS
3877
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003878 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003879 (Context, tag.Val, header.Val, operands.Val));
3880 return false;
3881}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003882
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003883/// ParseDISubrange:
3884/// ::= !DISubrange(count: 30, lowerBound: 2)
3885bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003886#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003887 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003888 OPTIONAL(lowerBound, MDSignedField, );
3889 PARSE_MD_FIELDS();
3890#undef VISIT_MD_FIELDS
3891
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003892 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003893 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003894}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003895
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003896/// ParseDIEnumerator:
3897/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3898bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003899#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003900 REQUIRED(name, MDStringField, ); \
3901 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003902 PARSE_MD_FIELDS();
3903#undef VISIT_MD_FIELDS
3904
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003905 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003906 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003907}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003908
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003909/// ParseDIBasicType:
3910/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3911bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003912#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003913 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003914 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003915 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003916 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003917 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003918 PARSE_MD_FIELDS();
3919#undef VISIT_MD_FIELDS
3920
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003921 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003922 align.Val, encoding.Val));
3923 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003924}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003925
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003926/// ParseDIDerivedType:
3927/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003928/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003929/// align: 32, offset: 0, flags: 0, extraData: !3,
3930/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003931bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003932#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3933 REQUIRED(tag, DwarfTagField, ); \
3934 OPTIONAL(name, MDStringField, ); \
3935 OPTIONAL(file, MDField, ); \
3936 OPTIONAL(line, LineField, ); \
3937 OPTIONAL(scope, MDField, ); \
3938 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003939 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003940 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003941 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003942 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003943 OPTIONAL(extraData, MDField, ); \
3944 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003945 PARSE_MD_FIELDS();
3946#undef VISIT_MD_FIELDS
3947
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003948 Optional<unsigned> DWARFAddressSpace;
3949 if (dwarfAddressSpace.Val != UINT32_MAX)
3950 DWARFAddressSpace = dwarfAddressSpace.Val;
3951
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003952 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003953 (Context, tag.Val, name.Val, file.Val, line.Val,
3954 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003955 offset.Val, DWARFAddressSpace, flags.Val,
3956 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003957 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003958}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003959
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003960bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003961#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3962 REQUIRED(tag, DwarfTagField, ); \
3963 OPTIONAL(name, MDStringField, ); \
3964 OPTIONAL(file, MDField, ); \
3965 OPTIONAL(line, LineField, ); \
3966 OPTIONAL(scope, MDField, ); \
3967 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003968 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003969 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003970 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003971 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003972 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003973 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003974 OPTIONAL(vtableHolder, MDField, ); \
3975 OPTIONAL(templateParams, MDField, ); \
3976 OPTIONAL(identifier, MDStringField, );
3977 PARSE_MD_FIELDS();
3978#undef VISIT_MD_FIELDS
3979
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003980 // If this has an identifier try to build an ODR type.
3981 if (identifier.Val)
3982 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003983 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3984 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3985 elements.Val, runtimeLang.Val, vtableHolder.Val,
3986 templateParams.Val)) {
3987 Result = CT;
3988 return false;
3989 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003990
3991 // Create a new node, and save it in the context if it belongs in the type
3992 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003993 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003994 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003995 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3996 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3997 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3998 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003999}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00004000
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004001bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004003 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004004 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004005 REQUIRED(types, MDField, );
4006 PARSE_MD_FIELDS();
4007#undef VISIT_MD_FIELDS
4008
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004009 Result = GET_OR_DISTINCT(DISubroutineType,
4010 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004011 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004012}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004013
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004014/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004015/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4016/// checksumkind: CSK_MD5,
4017/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004018bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004019#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4020 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004021 REQUIRED(directory, MDStringField, ); \
4022 OPTIONAL(checksumkind, ChecksumKindField, ); \
4023 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004024 PARSE_MD_FIELDS();
4025#undef VISIT_MD_FIELDS
4026
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004027 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4028 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004029 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004030}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004031
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004032/// ParseDICompileUnit:
4033/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004034/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004035/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004036/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004037/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004038bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004039 if (!IsDistinct)
4040 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4041
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004042#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4043 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004044 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004045 OPTIONAL(producer, MDStringField, ); \
4046 OPTIONAL(isOptimized, MDBoolField, ); \
4047 OPTIONAL(flags, MDStringField, ); \
4048 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4049 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004050 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004051 OPTIONAL(enums, MDField, ); \
4052 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004053 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004054 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004055 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004056 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004057 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4058 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004059 PARSE_MD_FIELDS();
4060#undef VISIT_MD_FIELDS
4061
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004062 Result = DICompileUnit::getDistinct(
4063 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4064 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004065 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004066 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004067 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004068}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004069
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004070/// ParseDISubprogram:
4071/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004072/// file: !1, line: 7, type: !2, isLocal: false,
4073/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004074/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004075/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004076/// isOptimized: false, templateParams: !4, declaration: !5,
4077/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004078bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004079 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004080#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4081 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004082 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004083 OPTIONAL(linkageName, MDStringField, ); \
4084 OPTIONAL(file, MDField, ); \
4085 OPTIONAL(line, LineField, ); \
4086 OPTIONAL(type, MDField, ); \
4087 OPTIONAL(isLocal, MDBoolField, ); \
4088 OPTIONAL(isDefinition, MDBoolField, (true)); \
4089 OPTIONAL(scopeLine, LineField, ); \
4090 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004091 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004092 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004093 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004094 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004095 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004096 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004097 OPTIONAL(templateParams, MDField, ); \
4098 OPTIONAL(declaration, MDField, ); \
4099 OPTIONAL(variables, MDField, );
4100 PARSE_MD_FIELDS();
4101#undef VISIT_MD_FIELDS
4102
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004103 if (isDefinition.Val && !IsDistinct)
4104 return Lex.Error(
4105 Loc,
4106 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4107
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004108 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004109 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4110 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4111 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004112 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4113 isOptimized.Val, unit.Val, templateParams.Val,
4114 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004115 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004116}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004117
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004118/// ParseDILexicalBlock:
4119/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4120bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004121#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004122 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004123 OPTIONAL(file, MDField, ); \
4124 OPTIONAL(line, LineField, ); \
4125 OPTIONAL(column, ColumnField, );
4126 PARSE_MD_FIELDS();
4127#undef VISIT_MD_FIELDS
4128
4129 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004130 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004131 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004132}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004133
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004134/// ParseDILexicalBlockFile:
4135/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4136bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004138 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004139 OPTIONAL(file, MDField, ); \
4140 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4141 PARSE_MD_FIELDS();
4142#undef VISIT_MD_FIELDS
4143
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004144 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004145 (Context, scope.Val, file.Val, discriminator.Val));
4146 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004147}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004148
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004149/// ParseDINamespace:
4150/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4151bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004152#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4153 REQUIRED(scope, MDField, ); \
4154 OPTIONAL(file, MDField, ); \
4155 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004156 OPTIONAL(line, LineField, ); \
4157 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004158 PARSE_MD_FIELDS();
4159#undef VISIT_MD_FIELDS
4160
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004161 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantldbfda632016-11-03 19:42:02 +00004162 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004163 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004164}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004165
Amjad Abouda9bcf162015-12-10 12:56:35 +00004166/// ParseDIMacro:
4167/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4168bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4169#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4170 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004171 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004172 REQUIRED(name, MDStringField, ); \
4173 OPTIONAL(value, MDStringField, );
4174 PARSE_MD_FIELDS();
4175#undef VISIT_MD_FIELDS
4176
4177 Result = GET_OR_DISTINCT(DIMacro,
4178 (Context, type.Val, line.Val, name.Val, value.Val));
4179 return false;
4180}
4181
4182/// ParseDIMacroFile:
4183/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4184bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4185#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4186 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004187 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004188 REQUIRED(file, MDField, ); \
4189 OPTIONAL(nodes, MDField, );
4190 PARSE_MD_FIELDS();
4191#undef VISIT_MD_FIELDS
4192
4193 Result = GET_OR_DISTINCT(DIMacroFile,
4194 (Context, type.Val, line.Val, file.Val, nodes.Val));
4195 return false;
4196}
4197
Adrian Prantlab1243f2015-06-29 23:03:47 +00004198/// ParseDIModule:
4199/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4200/// includePath: "/usr/include", isysroot: "/")
4201bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4202#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4203 REQUIRED(scope, MDField, ); \
4204 REQUIRED(name, MDStringField, ); \
4205 OPTIONAL(configMacros, MDStringField, ); \
4206 OPTIONAL(includePath, MDStringField, ); \
4207 OPTIONAL(isysroot, MDStringField, );
4208 PARSE_MD_FIELDS();
4209#undef VISIT_MD_FIELDS
4210
4211 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4212 configMacros.Val, includePath.Val, isysroot.Val));
4213 return false;
4214}
4215
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004216/// ParseDITemplateTypeParameter:
4217/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4218bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004219#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004220 OPTIONAL(name, MDStringField, ); \
4221 REQUIRED(type, MDField, );
4222 PARSE_MD_FIELDS();
4223#undef VISIT_MD_FIELDS
4224
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004225 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004226 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004227 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004228}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004229
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004230/// ParseDITemplateValueParameter:
4231/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004232/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004233bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004235 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004236 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004237 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004238 REQUIRED(value, MDField, );
4239 PARSE_MD_FIELDS();
4240#undef VISIT_MD_FIELDS
4241
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004242 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004243 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004244 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004245}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004246
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004247/// ParseDIGlobalVariable:
4248/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004249/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004250/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004251bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004252#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004253 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004254 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004255 OPTIONAL(linkageName, MDStringField, ); \
4256 OPTIONAL(file, MDField, ); \
4257 OPTIONAL(line, LineField, ); \
4258 OPTIONAL(type, MDField, ); \
4259 OPTIONAL(isLocal, MDBoolField, ); \
4260 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004261 OPTIONAL(declaration, MDField, ); \
4262 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004263 PARSE_MD_FIELDS();
4264#undef VISIT_MD_FIELDS
4265
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004266 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004267 (Context, scope.Val, name.Val, linkageName.Val,
4268 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004269 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004270 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004271}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004272
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004273/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004274/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004275/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4276/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004277/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004278/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4279/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004280bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004281#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004282 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004283 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004284 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004285 OPTIONAL(file, MDField, ); \
4286 OPTIONAL(line, LineField, ); \
4287 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004288 OPTIONAL(flags, DIFlagField, ); \
4289 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004290 PARSE_MD_FIELDS();
4291#undef VISIT_MD_FIELDS
4292
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004293 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004294 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004295 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004296 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004297}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004298
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004299/// ParseDIExpression:
4300/// ::= !DIExpression(0, 7, -1)
4301bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004302 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4303 Lex.Lex();
4304
4305 if (ParseToken(lltok::lparen, "expected '(' here"))
4306 return true;
4307
4308 SmallVector<uint64_t, 8> Elements;
4309 if (Lex.getKind() != lltok::rparen)
4310 do {
4311 if (Lex.getKind() == lltok::DwarfOp) {
4312 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4313 Lex.Lex();
4314 Elements.push_back(Op);
4315 continue;
4316 }
4317 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4318 }
4319
4320 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4321 return TokError("expected unsigned integer");
4322
4323 auto &U = Lex.getAPSIntVal();
4324 if (U.ugt(UINT64_MAX))
4325 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4326 Elements.push_back(U.getZExtValue());
4327 Lex.Lex();
4328 } while (EatIfPresent(lltok::comma));
4329
4330 if (ParseToken(lltok::rparen, "expected ')' here"))
4331 return true;
4332
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004333 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004334 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004335}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004336
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004337/// ParseDIGlobalVariableExpression:
4338/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4339bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4340 bool IsDistinct) {
4341#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4342 REQUIRED(var, MDField, ); \
4343 OPTIONAL(expr, MDField, );
4344 PARSE_MD_FIELDS();
4345#undef VISIT_MD_FIELDS
4346
4347 Result =
4348 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4349 return false;
4350}
4351
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004352/// ParseDIObjCProperty:
4353/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004354/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004355bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004356#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004357 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004358 OPTIONAL(file, MDField, ); \
4359 OPTIONAL(line, LineField, ); \
4360 OPTIONAL(setter, MDStringField, ); \
4361 OPTIONAL(getter, MDStringField, ); \
4362 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4363 OPTIONAL(type, MDField, );
4364 PARSE_MD_FIELDS();
4365#undef VISIT_MD_FIELDS
4366
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004367 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004368 (Context, name.Val, file.Val, line.Val, setter.Val,
4369 getter.Val, attributes.Val, type.Val));
4370 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004371}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004372
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004373/// ParseDIImportedEntity:
4374/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004375/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004376bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4378 REQUIRED(tag, DwarfTagField, ); \
4379 REQUIRED(scope, MDField, ); \
4380 OPTIONAL(entity, MDField, ); \
4381 OPTIONAL(line, LineField, ); \
4382 OPTIONAL(name, MDStringField, );
4383 PARSE_MD_FIELDS();
4384#undef VISIT_MD_FIELDS
4385
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004386 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004387 entity.Val, line.Val, name.Val));
4388 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004389}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004390
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004391#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004392#undef NOP_FIELD
4393#undef REQUIRE_FIELD
4394#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004395
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004396/// ParseMetadataAsValue
4397/// ::= metadata i32 %local
4398/// ::= metadata i32 @global
4399/// ::= metadata i32 7
4400/// ::= metadata !0
4401/// ::= metadata !{...}
4402/// ::= metadata !"string"
4403bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4404 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004405 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004406 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004407 return true;
4408
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004409 V = MetadataAsValue::get(Context, MD);
4410 return false;
4411}
4412
4413/// ParseValueAsMetadata
4414/// ::= i32 %local
4415/// ::= i32 @global
4416/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004417bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4418 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004419 Type *Ty;
4420 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004421 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004422 return true;
4423 if (Ty->isMetadataTy())
4424 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4425
4426 Value *V;
4427 if (ParseValue(Ty, V, PFS))
4428 return true;
4429
4430 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004431 return false;
4432}
4433
4434/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004435/// ::= i32 %local
4436/// ::= i32 @global
4437/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004438/// ::= !42
4439/// ::= !{...}
4440/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004441/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004442bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004443 if (Lex.getKind() == lltok::MetadataVar) {
4444 MDNode *N;
4445 if (ParseSpecializedMDNode(N))
4446 return true;
4447 MD = N;
4448 return false;
4449 }
4450
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004451 // ValueAsMetadata:
4452 // <type> <value>
4453 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004454 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004455
4456 // '!'.
4457 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4458 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004459
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004460 // MDString:
4461 // ::= '!' STRINGCONSTANT
4462 if (Lex.getKind() == lltok::StringConstant) {
4463 MDString *S;
4464 if (ParseMDString(S))
4465 return true;
4466 MD = S;
4467 return false;
4468 }
4469
Dan Gohman8939ba332010-07-14 18:26:50 +00004470 // MDNode:
4471 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004472 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004473 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004474 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004475 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004476 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004477 return false;
4478}
4479
Victor Hernandez9d75c962010-01-11 22:31:58 +00004480//===----------------------------------------------------------------------===//
4481// Function Parsing.
4482//===----------------------------------------------------------------------===//
4483
Chris Lattner229907c2011-07-18 04:54:35 +00004484bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004485 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004486 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004488
Chris Lattnerac161bf2009-01-02 07:01:27 +00004489 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004491 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004492 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004493 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004495 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004496 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004497 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004498 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004499 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004500 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004501 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4502 (ID.UIntVal >> 1) & 1,
4503 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004504 return false;
4505 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004506 case ValID::t_GlobalName:
4507 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004508 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004509 case ValID::t_GlobalID:
4510 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004511 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004512 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004513 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004514 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004515 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004516 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004517 return false;
4518 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004519 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004520 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4521 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004522
Dan Gohman518cda42011-12-17 00:04:22 +00004523 // The lexer has no type info, so builds all half, float, and double FP
4524 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004525 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004527 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004528 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004529 &Ignored);
4530 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004531 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004532 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004534 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004535
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004536 if (V->getType() != Ty)
4537 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004538 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004539
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 return false;
4541 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004542 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004543 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004544 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 return false;
4546 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004547 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004548 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004549 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004550 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004551 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004552 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004553 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004554 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004555 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004556 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004558 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004559 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004561 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004562 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004563 case ValID::t_None:
4564 if (!Ty->isTokenTy())
4565 return Error(ID.Loc, "invalid type for none constant");
4566 V = Constant::getNullValue(Ty);
4567 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004568 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004569 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004570 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004571
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 V = ID.ConstantVal;
4573 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004574 case ValID::t_ConstantStruct:
4575 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004576 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004577 if (ST->getNumElements() != ID.UIntVal)
4578 return Error(ID.Loc,
4579 "initializer with struct type has wrong # elements");
4580 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4581 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004582
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004583 // Verify that the elements are compatible with the structtype.
4584 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4585 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4586 return Error(ID.Loc, "element " + Twine(i) +
4587 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004588
David Blaikieadbda4b2015-08-03 20:08:41 +00004589 V = ConstantStruct::get(
4590 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004591 } else
4592 return Error(ID.Loc, "constant expression type mismatch");
4593 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004594 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004595 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004596}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004597
Alex Lorenzd2255952015-07-17 22:07:03 +00004598bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4599 C = nullptr;
4600 ValID ID;
4601 auto Loc = Lex.getLoc();
4602 if (ParseValID(ID, /*PFS=*/nullptr))
4603 return true;
4604 switch (ID.Kind) {
4605 case ValID::t_APSInt:
4606 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004607 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004608 case ValID::t_Constant:
4609 case ValID::t_ConstantStruct:
4610 case ValID::t_PackedConstantStruct: {
4611 Value *V;
4612 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4613 return true;
4614 assert(isa<Constant>(V) && "Expected a constant value");
4615 C = cast<Constant>(V);
4616 return false;
4617 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004618 case ValID::t_Null:
4619 C = Constant::getNullValue(Ty);
4620 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004621 default:
4622 return Error(Loc, "expected a constant value");
4623 }
4624}
4625
David Majnemer8a1c45d2015-12-12 05:38:55 +00004626bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004627 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004629 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004630}
4631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004632bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004633 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004634 return ParseType(Ty) ||
4635 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636}
4637
Chris Lattner3ed871f2009-10-27 19:13:16 +00004638bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4639 PerFunctionState &PFS) {
4640 Value *V;
4641 Loc = Lex.getLoc();
4642 if (ParseTypeAndValue(V, PFS)) return true;
4643 if (!isa<BasicBlock>(V))
4644 return Error(Loc, "expected a basic block");
4645 BB = cast<BasicBlock>(V);
4646 return false;
4647}
4648
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649/// FunctionHeader
4650/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004651/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004652/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004653bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4654 // Parse the linkage.
4655 LocTy LinkageLoc = Lex.getLoc();
4656 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004657
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004658 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004659 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004660 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004661 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004662 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004663 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004665 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4666 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004667 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004668 return true;
4669
4670 // Verify that the linkage is ok.
4671 switch ((GlobalValue::LinkageTypes)Linkage) {
4672 case GlobalValue::ExternalLinkage:
4673 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004674 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004675 if (isDefine)
4676 return Error(LinkageLoc, "invalid linkage for function definition");
4677 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004678 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004680 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004681 case GlobalValue::LinkOnceAnyLinkage:
4682 case GlobalValue::LinkOnceODRLinkage:
4683 case GlobalValue::WeakAnyLinkage:
4684 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004685 if (!isDefine)
4686 return Error(LinkageLoc, "invalid linkage for function declaration");
4687 break;
4688 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004689 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004690 return Error(LinkageLoc, "invalid function linkage type");
4691 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004692
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004693 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4694 return Error(LinkageLoc,
4695 "symbol with local linkage must have default visibility");
4696
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004697 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004698 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004699
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004701
4702 std::string FunctionName;
4703 if (Lex.getKind() == lltok::GlobalVar) {
4704 FunctionName = Lex.getStrVal();
4705 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4706 unsigned NameID = Lex.getUIntVal();
4707
4708 if (NameID != NumberedVals.size())
4709 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004710 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004711 } else {
4712 return TokError("expected function name");
4713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004714
Chris Lattner3822f632009-01-02 08:05:26 +00004715 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004716
Chris Lattner3822f632009-01-02 08:05:26 +00004717 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004719
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004720 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004722 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004723 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004724 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004725 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004726 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004727 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004728 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004729 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004730 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004731 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004732 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004733 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004734
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004735 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004736 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004737 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004738 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004739 (EatIfPresent(lltok::kw_section) &&
4740 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004741 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004742 ParseOptionalAlignment(Alignment) ||
4743 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004744 ParseStringConstant(GC)) ||
4745 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004746 ParseGlobalTypeAndValue(Prefix)) ||
4747 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004748 ParseGlobalTypeAndValue(Prologue)) ||
4749 (EatIfPresent(lltok::kw_personality) &&
4750 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004751 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752
Michael Gottesman41748d72013-06-27 00:25:01 +00004753 if (FuncAttrs.contains(Attribute::Builtin))
4754 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004755
Chris Lattnerac161bf2009-01-02 07:01:27 +00004756 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004757 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004758 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004759 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 // Okay, if we got here, the function is syntactically valid. Convert types
4763 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004764 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004765 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004766
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004768 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004769 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770 }
4771
Reid Kleckner7f720332017-04-13 00:58:09 +00004772 AttributeList PAL =
4773 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4774 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004775
Bill Wendling749a43d2012-12-30 13:50:49 +00004776 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004777 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4778
Chris Lattner229907c2011-07-18 04:54:35 +00004779 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004780 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004781 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004782
Craig Topper2617dcc2014-04-15 06:32:26 +00004783 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004784 if (!FunctionName.empty()) {
4785 // If this was a definition of a forward reference, remove the definition
4786 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004787 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 if (FRVI != ForwardRefVals.end()) {
4789 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004790 if (!Fn)
4791 return Error(FRVI->second.second, "invalid forward reference to "
4792 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004793 if (Fn->getType() != PFT)
4794 return Error(FRVI->second.second, "invalid forward reference to "
4795 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004796
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797 ForwardRefVals.erase(FRVI);
4798 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004799 // Reject redefinitions.
4800 return Error(NameLoc, "invalid redefinition of function '" +
4801 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004802 } else if (M->getNamedValue(FunctionName)) {
4803 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004805
Dan Gohman399d6ae2009-08-29 23:37:49 +00004806 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 // If this is a definition of a forward referenced function, make sure the
4808 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004809 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 if (I != ForwardRefValIDs.end()) {
4811 Fn = cast<Function>(I->second.first);
4812 if (Fn->getType() != PFT)
4813 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004814 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004815 ForwardRefValIDs.erase(I);
4816 }
4817 }
4818
Craig Topper2617dcc2014-04-15 06:32:26 +00004819 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4821 else // Move the forward-reference to the correct spot in the module.
4822 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4823
4824 if (FunctionName.empty())
4825 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004826
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4828 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004829 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 Fn->setCallingConv(CC);
4831 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004832 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 Fn->setAlignment(Alignment);
4834 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004835 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004836 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004837 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004838 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004839 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004840 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004841
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 // Add all of the arguments we parsed to the function.
4843 Function::arg_iterator ArgIt = Fn->arg_begin();
4844 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4845 // If the argument has a name, insert it into the argument symbol table.
4846 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004847
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 // Set the name, if it conflicted, it will be auto-renamed.
4849 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004850
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004851 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004852 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4853 ArgList[i].Name + "'");
4854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004855
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004856 if (isDefine)
4857 return false;
4858
Robin Morisset039781e2014-08-29 21:53:01 +00004859 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004860 ValID ID;
4861 if (FunctionName.empty()) {
4862 ID.Kind = ValID::t_GlobalID;
4863 ID.UIntVal = NumberedVals.size() - 1;
4864 } else {
4865 ID.Kind = ValID::t_GlobalName;
4866 ID.StrVal = FunctionName;
4867 }
4868 auto Blocks = ForwardRefBlockAddresses.find(ID);
4869 if (Blocks != ForwardRefBlockAddresses.end())
4870 return Error(Blocks->first.Loc,
4871 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004872 return false;
4873}
4874
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004875bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4876 ValID ID;
4877 if (FunctionNumber == -1) {
4878 ID.Kind = ValID::t_GlobalName;
4879 ID.StrVal = F.getName();
4880 } else {
4881 ID.Kind = ValID::t_GlobalID;
4882 ID.UIntVal = FunctionNumber;
4883 }
4884
4885 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4886 if (Blocks == P.ForwardRefBlockAddresses.end())
4887 return false;
4888
4889 for (const auto &I : Blocks->second) {
4890 const ValID &BBID = I.first;
4891 GlobalValue *GV = I.second;
4892
4893 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4894 "Expected local id or name");
4895 BasicBlock *BB;
4896 if (BBID.Kind == ValID::t_LocalName)
4897 BB = GetBB(BBID.StrVal, BBID.Loc);
4898 else
4899 BB = GetBB(BBID.UIntVal, BBID.Loc);
4900 if (!BB)
4901 return P.Error(BBID.Loc, "referenced value is not a basic block");
4902
4903 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4904 GV->eraseFromParent();
4905 }
4906
4907 P.ForwardRefBlockAddresses.erase(Blocks);
4908 return false;
4909}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910
4911/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004912/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004914 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 return TokError("expected '{' in function body");
4916 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004917
Chris Lattner3432c622009-10-28 03:39:23 +00004918 int FunctionNumber = -1;
4919 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004920
Chris Lattner3432c622009-10-28 03:39:23 +00004921 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004922
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004923 // Resolve block addresses and allow basic blocks to be forward-declared
4924 // within this function.
4925 if (PFS.resolveForwardRefBlockAddresses())
4926 return true;
4927 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4928
Chris Lattnerbbddd962010-01-09 19:20:07 +00004929 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004930 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004931 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004932
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004933 while (Lex.getKind() != lltok::rbrace &&
4934 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004935 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004936
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004937 while (Lex.getKind() != lltok::rbrace)
4938 if (ParseUseListOrder(&PFS))
4939 return true;
4940
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 // Eat the }.
4942 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004943
Chris Lattnerac161bf2009-01-02 07:01:27 +00004944 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004945 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946}
4947
4948/// ParseBasicBlock
4949/// ::= LabelStr? Instruction*
4950bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4951 // If this basic block starts out with a name, remember it.
4952 std::string Name;
4953 LocTy NameLoc = Lex.getLoc();
4954 if (Lex.getKind() == lltok::LabelStr) {
4955 Name = Lex.getStrVal();
4956 Lex.Lex();
4957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004958
Chris Lattnerac161bf2009-01-02 07:01:27 +00004959 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004960 if (!BB)
4961 return Error(NameLoc,
4962 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004963
Chris Lattnerac161bf2009-01-02 07:01:27 +00004964 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004965
Chris Lattnerac161bf2009-01-02 07:01:27 +00004966 // Parse the instructions in this block until we get a terminator.
4967 Instruction *Inst;
4968 do {
4969 // This instruction may have three possibilities for a name: a) none
4970 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4971 LocTy NameLoc = Lex.getLoc();
4972 int NameID = -1;
4973 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004974
Chris Lattnerac161bf2009-01-02 07:01:27 +00004975 if (Lex.getKind() == lltok::LocalVarID) {
4976 NameID = Lex.getUIntVal();
4977 Lex.Lex();
4978 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4979 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004980 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004981 NameStr = Lex.getStrVal();
4982 Lex.Lex();
4983 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4984 return true;
4985 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004986
Chris Lattner77b89dc2009-12-30 05:23:43 +00004987 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004988 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004989 case InstError: return true;
4990 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004991 BB->getInstList().push_back(Inst);
4992
Chris Lattner77b89dc2009-12-30 05:23:43 +00004993 // With a normal result, we check to see if the instruction is followed by
4994 // a comma and metadata.
4995 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004996 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004997 return true;
4998 break;
4999 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00005000 BB->getInstList().push_back(Inst);
5001
Chris Lattner77b89dc2009-12-30 05:23:43 +00005002 // If the instruction parser ate an extra comma at the end of it, it
5003 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005004 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005005 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005006 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005007 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005008
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009 // Set the name on the instruction.
5010 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5011 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005012
Chris Lattnerac161bf2009-01-02 07:01:27 +00005013 return false;
5014}
5015
5016//===----------------------------------------------------------------------===//
5017// Instruction Parsing.
5018//===----------------------------------------------------------------------===//
5019
5020/// ParseInstruction - Parse one of the many different instructions.
5021///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005022int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5023 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005024 lltok::Kind Token = Lex.getKind();
5025 if (Token == lltok::Eof)
5026 return TokError("found end of file when expecting more instructions");
5027 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005028 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005029 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005030
Chris Lattnerac161bf2009-01-02 07:01:27 +00005031 switch (Token) {
5032 default: return Error(Loc, "expected instruction opcode");
5033 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005034 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005035 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5036 case lltok::kw_br: return ParseBr(Inst, PFS);
5037 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005038 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005040 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005041 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5042 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005043 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5044 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005045 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005046 // Binary Operators.
5047 case lltok::kw_add:
5048 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005049 case lltok::kw_mul:
5050 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005051 bool NUW = EatIfPresent(lltok::kw_nuw);
5052 bool NSW = EatIfPresent(lltok::kw_nsw);
5053 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005054
Chris Lattnera676c0f2011-02-07 16:40:21 +00005055 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005056
Chris Lattnera676c0f2011-02-07 16:40:21 +00005057 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5058 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5059 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005060 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005061 case lltok::kw_fadd:
5062 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005063 case lltok::kw_fmul:
5064 case lltok::kw_fdiv:
5065 case lltok::kw_frem: {
5066 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5067 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5068 if (Res != 0)
5069 return Res;
5070 if (FMF.any())
5071 Inst->setFastMathFlags(FMF);
5072 return 0;
5073 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005074
Chris Lattner35315d02011-02-06 21:44:57 +00005075 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005076 case lltok::kw_udiv:
5077 case lltok::kw_lshr:
5078 case lltok::kw_ashr: {
5079 bool Exact = EatIfPresent(lltok::kw_exact);
5080
5081 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5082 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5083 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005084 }
5085
Chris Lattnerac161bf2009-01-02 07:01:27 +00005086 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005087 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 case lltok::kw_and:
5089 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005090 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005091 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5092 case lltok::kw_fcmp: {
5093 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5094 int Res = ParseCompare(Inst, PFS, KeywordVal);
5095 if (Res != 0)
5096 return Res;
5097 if (FMF.any())
5098 Inst->setFastMathFlags(FMF);
5099 return 0;
5100 }
5101
Chris Lattnerac161bf2009-01-02 07:01:27 +00005102 // Casts.
5103 case lltok::kw_trunc:
5104 case lltok::kw_zext:
5105 case lltok::kw_sext:
5106 case lltok::kw_fptrunc:
5107 case lltok::kw_fpext:
5108 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005109 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005110 case lltok::kw_uitofp:
5111 case lltok::kw_sitofp:
5112 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005113 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005115 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005116 // Other.
5117 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005118 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5120 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5121 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5122 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005123 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005124 // Call.
5125 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5126 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5127 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005128 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005130 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005131 case lltok::kw_load: return ParseLoad(Inst, PFS);
5132 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005133 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5134 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005135 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005136 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5137 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5138 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5139 }
5140}
5141
5142/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5143bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005144 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005145 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005146 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005147 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5148 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5149 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5150 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5151 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5152 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5153 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5154 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5155 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5156 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5157 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5158 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5159 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5160 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5161 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5162 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5163 }
5164 } else {
5165 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005166 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5168 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5169 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5170 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5171 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5172 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5173 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5174 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5175 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5176 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5177 }
5178 }
5179 Lex.Lex();
5180 return false;
5181}
5182
5183//===----------------------------------------------------------------------===//
5184// Terminator Instructions.
5185//===----------------------------------------------------------------------===//
5186
5187/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005188/// ::= 'ret' void (',' !dbg, !1)*
5189/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005190bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005191 PerFunctionState &PFS) {
5192 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005193 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005194 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005196 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005197
Chris Lattnerfdd87902009-10-05 05:54:46 +00005198 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005199 if (!ResType->isVoidTy())
5200 return Error(TypeLoc, "value doesn't match function result type '" +
5201 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005202
Owen Anderson55f1c092009-08-13 21:58:54 +00005203 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 return false;
5205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Chris Lattnerac161bf2009-01-02 07:01:27 +00005207 Value *RV;
5208 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005210 if (ResType != RV->getType())
5211 return Error(TypeLoc, "value doesn't match function result type '" +
5212 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005213
Owen Anderson55f1c092009-08-13 21:58:54 +00005214 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005215 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005216}
5217
Chris Lattnerac161bf2009-01-02 07:01:27 +00005218/// ParseBr
5219/// ::= 'br' TypeAndValue
5220/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5221bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5222 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005223 Value *Op0;
5224 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005225 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005226
Chris Lattnerac161bf2009-01-02 07:01:27 +00005227 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5228 Inst = BranchInst::Create(BB);
5229 return false;
5230 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005231
Owen Anderson55f1c092009-08-13 21:58:54 +00005232 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005233 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005234
Chris Lattnerac161bf2009-01-02 07:01:27 +00005235 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005236 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005237 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005238 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005240
Chris Lattner3ed871f2009-10-27 19:13:16 +00005241 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005242 return false;
5243}
5244
5245/// ParseSwitch
5246/// Instruction
5247/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5248/// JumpTable
5249/// ::= (TypeAndValue ',' TypeAndValue)*
5250bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5251 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005252 Value *Cond;
5253 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5255 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005256 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5258 return true;
5259
Duncan Sands19d0b472010-02-16 11:11:14 +00005260 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005261 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005262
Chris Lattnerac161bf2009-01-02 07:01:27 +00005263 // Parse the jump table pairs.
5264 SmallPtrSet<Value*, 32> SeenCases;
5265 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5266 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005267 Value *Constant;
5268 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005269
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5271 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005272 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005273 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005274
David Blaikie70573dc2014-11-19 07:49:26 +00005275 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 return Error(CondLoc, "duplicate case value in switch");
5277 if (!isa<ConstantInt>(Constant))
5278 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005279
Chris Lattner3ed871f2009-10-27 19:13:16 +00005280 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005282
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005284
Chris Lattner3ed871f2009-10-27 19:13:16 +00005285 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005286 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5287 SI->addCase(Table[i].first, Table[i].second);
5288 Inst = SI;
5289 return false;
5290}
5291
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005292/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005293/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005294/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5295bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005296 LocTy AddrLoc;
5297 Value *Address;
5298 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005299 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5300 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005301 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005302
Duncan Sands19d0b472010-02-16 11:11:14 +00005303 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005304 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005305
Chris Lattner3ed871f2009-10-27 19:13:16 +00005306 // Parse the destination list.
5307 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005308
Chris Lattner3ed871f2009-10-27 19:13:16 +00005309 if (Lex.getKind() != lltok::rsquare) {
5310 BasicBlock *DestBB;
5311 if (ParseTypeAndBasicBlock(DestBB, PFS))
5312 return true;
5313 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005314
Chris Lattner3ed871f2009-10-27 19:13:16 +00005315 while (EatIfPresent(lltok::comma)) {
5316 if (ParseTypeAndBasicBlock(DestBB, PFS))
5317 return true;
5318 DestList.push_back(DestBB);
5319 }
5320 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005321
Chris Lattner3ed871f2009-10-27 19:13:16 +00005322 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5323 return true;
5324
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005325 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005326 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5327 IBI->addDestination(DestList[i]);
5328 Inst = IBI;
5329 return false;
5330}
5331
Chris Lattnerac161bf2009-01-02 07:01:27 +00005332/// ParseInvoke
5333/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5334/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5335bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5336 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005337 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005338 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005339 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005340 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005341 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005342 LocTy RetTypeLoc;
5343 ValID CalleeID;
5344 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005345 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005346
Chris Lattner3ed871f2009-10-27 19:13:16 +00005347 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005348 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005349 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005350 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005351 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5352 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005353 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005354 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005355 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005356 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005357 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005358 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005359
Chris Lattnerac161bf2009-01-02 07:01:27 +00005360 // If RetType is a non-function pointer type, then this is the short syntax
5361 // for the call, which means that RetType is just the return type. Infer the
5362 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005363 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5364 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005365 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005366 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5368 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005369
Chris Lattnerac161bf2009-01-02 07:01:27 +00005370 if (!FunctionType::isValidReturnType(RetType))
5371 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005372
Owen Anderson4056ca92009-07-29 22:17:13 +00005373 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005375
David Blaikie41ba2b42015-07-27 23:32:19 +00005376 CalleeID.FTy = Ty;
5377
Chris Lattnerac161bf2009-01-02 07:01:27 +00005378 // Look up the callee.
5379 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005380 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5381 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005382
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005383 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005384 SmallVector<Value *, 8> Args;
5385 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005386
Chris Lattnerac161bf2009-01-02 07:01:27 +00005387 // Loop through FunctionType's arguments and ensure they are specified
5388 // correctly. Also, gather any parameter attributes.
5389 FunctionType::param_iterator I = Ty->param_begin();
5390 FunctionType::param_iterator E = Ty->param_end();
5391 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005392 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393 if (I != E) {
5394 ExpectedTy = *I++;
5395 } else if (!Ty->isVarArg()) {
5396 return Error(ArgList[i].Loc, "too many arguments specified");
5397 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005398
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5400 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005401 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005402 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005403 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005405
Chris Lattnerac161bf2009-01-02 07:01:27 +00005406 if (I != E)
5407 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005408
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005409 if (FnAttrs.hasAlignmentAttr())
5410 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005411
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005412 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005413 AttributeList PAL =
5414 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5415 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005417 InvokeInst *II =
5418 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005419 II->setCallingConv(CC);
5420 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005421 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005422 Inst = II;
5423 return false;
5424}
5425
Bill Wendlingf891bf82011-07-31 06:30:59 +00005426/// ParseResume
5427/// ::= 'resume' TypeAndValue
5428bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5429 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005430 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5431 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005432
Bill Wendlingf891bf82011-07-31 06:30:59 +00005433 ResumeInst *RI = ResumeInst::Create(Exn);
5434 Inst = RI;
5435 return false;
5436}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005437
David Majnemer654e1302015-07-31 17:58:14 +00005438bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5439 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005440 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005441 return true;
5442
5443 while (Lex.getKind() != lltok::rsquare) {
5444 // If this isn't the first argument, we need a comma.
5445 if (!Args.empty() &&
5446 ParseToken(lltok::comma, "expected ',' in argument list"))
5447 return true;
5448
5449 // Parse the argument.
5450 LocTy ArgLoc;
5451 Type *ArgTy = nullptr;
5452 if (ParseType(ArgTy, ArgLoc))
5453 return true;
5454
5455 Value *V;
5456 if (ArgTy->isMetadataTy()) {
5457 if (ParseMetadataAsValue(V, PFS))
5458 return true;
5459 } else {
5460 if (ParseValue(ArgTy, V, PFS))
5461 return true;
5462 }
5463 Args.push_back(V);
5464 }
5465
5466 Lex.Lex(); // Lex the ']'.
5467 return false;
5468}
5469
5470/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005471/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005472bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005473 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005474
David Majnemer8a1c45d2015-12-12 05:38:55 +00005475 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5476 return true;
5477
5478 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005479 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005480
5481 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5482 return true;
5483
5484 BasicBlock *UnwindBB = nullptr;
5485 if (Lex.getKind() == lltok::kw_to) {
5486 Lex.Lex();
5487 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5488 return true;
5489 } else {
5490 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5491 return true;
5492 }
5493 }
5494
David Majnemer8a1c45d2015-12-12 05:38:55 +00005495 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005496 return false;
5497}
5498
5499/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005500/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005501bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005502 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005503
David Majnemer8a1c45d2015-12-12 05:38:55 +00005504 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5505 return true;
5506
5507 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005508 return true;
5509
David Majnemer0bc0eef2015-08-15 02:46:08 +00005510 BasicBlock *BB;
5511 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5512 ParseTypeAndBasicBlock(BB, PFS))
5513 return true;
5514
David Majnemer8a1c45d2015-12-12 05:38:55 +00005515 Inst = CatchReturnInst::Create(CatchPad, BB);
5516 return false;
5517}
5518
5519/// ParseCatchSwitch
5520/// ::= 'catchswitch' within Parent
5521bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5522 Value *ParentPad;
5523 LocTy BBLoc;
5524
5525 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5526 return true;
5527
5528 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5529 Lex.getKind() != lltok::LocalVarID)
5530 return TokError("expected scope value for catchswitch");
5531
5532 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5533 return true;
5534
5535 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5536 return true;
5537
5538 SmallVector<BasicBlock *, 32> Table;
5539 do {
5540 BasicBlock *DestBB;
5541 if (ParseTypeAndBasicBlock(DestBB, PFS))
5542 return true;
5543 Table.push_back(DestBB);
5544 } while (EatIfPresent(lltok::comma));
5545
5546 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5547 return true;
5548
5549 if (ParseToken(lltok::kw_unwind,
5550 "expected 'unwind' after catchswitch scope"))
5551 return true;
5552
5553 BasicBlock *UnwindBB = nullptr;
5554 if (EatIfPresent(lltok::kw_to)) {
5555 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5556 return true;
5557 } else {
5558 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5559 return true;
5560 }
5561
5562 auto *CatchSwitch =
5563 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5564 for (BasicBlock *DestBB : Table)
5565 CatchSwitch->addHandler(DestBB);
5566 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005567 return false;
5568}
5569
5570/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005571/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005572bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005573 Value *CatchSwitch = nullptr;
5574
5575 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5576 return true;
5577
5578 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5579 return TokError("expected scope value for catchpad");
5580
5581 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5582 return true;
5583
David Majnemer654e1302015-07-31 17:58:14 +00005584 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005585 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005586 return true;
5587
David Majnemer8a1c45d2015-12-12 05:38:55 +00005588 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005589 return false;
5590}
5591
David Majnemer654e1302015-07-31 17:58:14 +00005592/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005593/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005594bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005595 Value *ParentPad = nullptr;
5596
5597 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5598 return true;
5599
5600 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5601 Lex.getKind() != lltok::LocalVarID)
5602 return TokError("expected scope value for cleanuppad");
5603
5604 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5605 return true;
5606
David Majnemer654e1302015-07-31 17:58:14 +00005607 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005608 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005609 return true;
5610
David Majnemer8a1c45d2015-12-12 05:38:55 +00005611 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005612 return false;
5613}
5614
Chris Lattnerac161bf2009-01-02 07:01:27 +00005615//===----------------------------------------------------------------------===//
5616// Binary Operators.
5617//===----------------------------------------------------------------------===//
5618
5619/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005620/// ::= ArithmeticOps TypeAndValue ',' Value
5621///
5622/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5623/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005624bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005625 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626 LocTy Loc; Value *LHS, *RHS;
5627 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5628 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5629 ParseValue(LHS->getType(), RHS, PFS))
5630 return true;
5631
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005632 bool Valid;
5633 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005634 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005635 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005636 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5637 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005638 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005639 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5640 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005641 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005642
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005643 if (!Valid)
5644 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005645
Chris Lattnerac161bf2009-01-02 07:01:27 +00005646 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5647 return false;
5648}
5649
5650/// ParseLogical
5651/// ::= ArithmeticOps TypeAndValue ',' Value {
5652bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5653 unsigned Opc) {
5654 LocTy Loc; Value *LHS, *RHS;
5655 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5656 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5657 ParseValue(LHS->getType(), RHS, PFS))
5658 return true;
5659
Duncan Sands9dff9be2010-02-15 16:12:20 +00005660 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005661 return Error(Loc,"instruction requires integer or integer vector operands");
5662
5663 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5664 return false;
5665}
5666
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667/// ParseCompare
5668/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5669/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005670bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5671 unsigned Opc) {
5672 // Parse the integer/fp comparison predicate.
5673 LocTy Loc;
5674 unsigned Pred;
5675 Value *LHS, *RHS;
5676 if (ParseCmpPredicate(Pred, Opc) ||
5677 ParseTypeAndValue(LHS, Loc, PFS) ||
5678 ParseToken(lltok::comma, "expected ',' after compare value") ||
5679 ParseValue(LHS->getType(), RHS, PFS))
5680 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005681
Chris Lattnerac161bf2009-01-02 07:01:27 +00005682 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005683 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005685 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005686 } else {
5687 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005688 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005689 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005690 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005691 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 }
5693 return false;
5694}
5695
5696//===----------------------------------------------------------------------===//
5697// Other Instructions.
5698//===----------------------------------------------------------------------===//
5699
5700
5701/// ParseCast
5702/// ::= CastOpc TypeAndValue 'to' Type
5703bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5704 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005705 LocTy Loc;
5706 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005707 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005708 if (ParseTypeAndValue(Op, Loc, PFS) ||
5709 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5710 ParseType(DestTy))
5711 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005712
Chris Lattner89d856e2009-03-01 00:53:13 +00005713 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5714 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005715 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005716 getTypeString(Op->getType()) + "' to '" +
5717 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005718 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005719 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5720 return false;
5721}
5722
5723/// ParseSelect
5724/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5725bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5726 LocTy Loc;
5727 Value *Op0, *Op1, *Op2;
5728 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5729 ParseToken(lltok::comma, "expected ',' after select condition") ||
5730 ParseTypeAndValue(Op1, PFS) ||
5731 ParseToken(lltok::comma, "expected ',' after select value") ||
5732 ParseTypeAndValue(Op2, PFS))
5733 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005734
Chris Lattnerac161bf2009-01-02 07:01:27 +00005735 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5736 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005737
Chris Lattnerac161bf2009-01-02 07:01:27 +00005738 Inst = SelectInst::Create(Op0, Op1, Op2);
5739 return false;
5740}
5741
Chris Lattnerb55ab542009-01-05 08:18:44 +00005742/// ParseVA_Arg
5743/// ::= 'va_arg' TypeAndValue ',' Type
5744bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005746 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005747 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005748 if (ParseTypeAndValue(Op, PFS) ||
5749 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005750 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005751 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005752
Chris Lattnerb55ab542009-01-05 08:18:44 +00005753 if (!EltTy->isFirstClassType())
5754 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005755
5756 Inst = new VAArgInst(Op, EltTy);
5757 return false;
5758}
5759
5760/// ParseExtractElement
5761/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5762bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5763 LocTy Loc;
5764 Value *Op0, *Op1;
5765 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5766 ParseToken(lltok::comma, "expected ',' after extract value") ||
5767 ParseTypeAndValue(Op1, PFS))
5768 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005769
Chris Lattnerac161bf2009-01-02 07:01:27 +00005770 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5771 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005772
Eric Christopherc9742252009-07-25 02:28:41 +00005773 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005774 return false;
5775}
5776
5777/// ParseInsertElement
5778/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5779bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5780 LocTy Loc;
5781 Value *Op0, *Op1, *Op2;
5782 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5783 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5784 ParseTypeAndValue(Op1, PFS) ||
5785 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5786 ParseTypeAndValue(Op2, PFS))
5787 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005788
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005790 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005791
Chris Lattnerac161bf2009-01-02 07:01:27 +00005792 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5793 return false;
5794}
5795
5796/// ParseShuffleVector
5797/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5798bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5799 LocTy Loc;
5800 Value *Op0, *Op1, *Op2;
5801 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5802 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5803 ParseTypeAndValue(Op1, PFS) ||
5804 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5805 ParseTypeAndValue(Op2, PFS))
5806 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005807
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005809 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005810
Chris Lattnerac161bf2009-01-02 07:01:27 +00005811 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5812 return false;
5813}
5814
5815/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005816/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005817int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005818 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005819 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005820
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005821 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005822 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5823 ParseValue(Ty, Op0, PFS) ||
5824 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005825 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005826 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5827 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005828
Chris Lattnerf4f03422009-12-30 05:27:33 +00005829 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005831
5832 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005834
Chris Lattner3822f632009-01-02 08:05:26 +00005835 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005836 break;
5837
Chris Lattnerf4f03422009-12-30 05:27:33 +00005838 if (Lex.getKind() == lltok::MetadataVar) {
5839 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005840 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005841 }
Devang Patel8f842d32009-10-16 18:45:49 +00005842
Chris Lattner3822f632009-01-02 08:05:26 +00005843 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 ParseValue(Ty, Op0, PFS) ||
5845 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005846 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005847 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5848 return true;
5849 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005850
Chris Lattnerac161bf2009-01-02 07:01:27 +00005851 if (!Ty->isFirstClassType())
5852 return Error(TypeLoc, "phi node must have first class type");
5853
Jay Foad52131342011-03-30 11:28:46 +00005854 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005855 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5856 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5857 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005858 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005859}
5860
Bill Wendlingfae14752011-08-12 20:24:12 +00005861/// ParseLandingPad
5862/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5863/// Clause
5864/// ::= 'catch' TypeAndValue
5865/// ::= 'filter'
5866/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5867bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005868 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005869
David Majnemer7fddecc2015-06-17 20:52:32 +00005870 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005871 return true;
5872
David Majnemer7fddecc2015-06-17 20:52:32 +00005873 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005874 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5875
5876 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5877 LandingPadInst::ClauseType CT;
5878 if (EatIfPresent(lltok::kw_catch))
5879 CT = LandingPadInst::Catch;
5880 else if (EatIfPresent(lltok::kw_filter))
5881 CT = LandingPadInst::Filter;
5882 else
5883 return TokError("expected 'catch' or 'filter' clause type");
5884
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005885 Value *V;
5886 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005887 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005888 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005889
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005890 // A 'catch' type expects a non-array constant. A filter clause expects an
5891 // array constant.
5892 if (CT == LandingPadInst::Catch) {
5893 if (isa<ArrayType>(V->getType()))
5894 Error(VLoc, "'catch' clause has an invalid type");
5895 } else {
5896 if (!isa<ArrayType>(V->getType()))
5897 Error(VLoc, "'filter' clause has an invalid type");
5898 }
5899
Owen Andersonf8f259d2015-03-09 07:13:42 +00005900 Constant *CV = dyn_cast<Constant>(V);
5901 if (!CV)
5902 return Error(VLoc, "clause argument must be a constant");
5903 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005904 }
5905
Owen Andersonf8f259d2015-03-09 07:13:42 +00005906 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005907 return false;
5908}
5909
Chris Lattnerac161bf2009-01-02 07:01:27 +00005910/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005911/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5912/// OptionalAttrs Type Value ParameterList OptionalAttrs
5913/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5914/// OptionalAttrs Type Value ParameterList OptionalAttrs
5915/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5916/// OptionalAttrs Type Value ParameterList OptionalAttrs
5917/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5918/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005919bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005920 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005921 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005922 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005923 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005924 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005925 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005926 LocTy RetTypeLoc;
5927 ValID CalleeID;
5928 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005929 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005930 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005931
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005932 if (TCK != CallInst::TCK_None &&
5933 ParseToken(lltok::kw_call,
5934 "expected 'tail call', 'musttail call', or 'notail call'"))
5935 return true;
5936
5937 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5938
5939 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005940 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005941 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005942 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5943 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005944 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5945 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005946 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005947
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005948 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5949 return Error(CallLoc, "fast-math-flags specified for call without "
5950 "floating-point scalar or vector return type");
5951
Chris Lattnerac161bf2009-01-02 07:01:27 +00005952 // If RetType is a non-function pointer type, then this is the short syntax
5953 // for the call, which means that RetType is just the return type. Infer the
5954 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005955 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5956 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005957 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005958 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005959 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5960 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005961
Chris Lattnerac161bf2009-01-02 07:01:27 +00005962 if (!FunctionType::isValidReturnType(RetType))
5963 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005964
Owen Anderson4056ca92009-07-29 22:17:13 +00005965 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005967
David Blaikie41ba2b42015-07-27 23:32:19 +00005968 CalleeID.FTy = Ty;
5969
Chris Lattnerac161bf2009-01-02 07:01:27 +00005970 // Look up the callee.
5971 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005972 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5973 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005974
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005975 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005976 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005977
Chris Lattnerac161bf2009-01-02 07:01:27 +00005978 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005979
Chris Lattnerac161bf2009-01-02 07:01:27 +00005980 // Loop through FunctionType's arguments and ensure they are specified
5981 // correctly. Also, gather any parameter attributes.
5982 FunctionType::param_iterator I = Ty->param_begin();
5983 FunctionType::param_iterator E = Ty->param_end();
5984 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005985 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005986 if (I != E) {
5987 ExpectedTy = *I++;
5988 } else if (!Ty->isVarArg()) {
5989 return Error(ArgList[i].Loc, "too many arguments specified");
5990 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005991
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5993 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005994 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005995 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005996 Attrs.push_back(ArgList[i].Attrs);
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
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00006002 if (FnAttrs.hasAlignmentAttr())
6003 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006004
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006005 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006006 AttributeList PAL =
6007 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6008 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006009
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006010 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006011 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006012 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006013 if (FMF.any())
6014 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006015 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006016 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006017 Inst = CI;
6018 return false;
6019}
6020
6021//===----------------------------------------------------------------------===//
6022// Memory Instructions.
6023//===----------------------------------------------------------------------===//
6024
6025/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006026/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6027/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006028int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006029 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006030 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006031 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006032 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006033 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006034
6035 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006036 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006037
David Majnemera3b0eb22015-02-16 08:38:03 +00006038 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006039
David Majnemera3b0eb22015-02-16 08:38:03 +00006040 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6041 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006042
Chris Lattnerb2f39502009-12-30 05:44:30 +00006043 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006044 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006045 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006046 if (ParseOptionalAlignment(Alignment))
6047 return true;
6048 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6049 return true;
6050 } else if (Lex.getKind() == lltok::kw_addrspace) {
6051 ASLoc = Lex.getLoc();
6052 if (ParseOptionalAddrSpace(AddrSpace))
6053 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006054 } else if (Lex.getKind() == lltok::MetadataVar) {
6055 AteExtraComma = true;
6056 } else {
6057 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006058 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6059 (!AteExtraComma &&
6060 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006061 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006062 }
6063 }
6064
Dan Gohman2140a742010-05-28 01:14:11 +00006065 if (Size && !Size->getType()->isIntegerTy())
6066 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006067
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006068 const DataLayout &DL = M->getDataLayout();
6069 unsigned AS = DL.getAllocaAddrSpace();
6070 if (AS != AddrSpace) {
6071 // TODO: In the future it should be possible to specify addrspace per-alloca.
6072 return Error(ASLoc, "address space must match datalayout");
6073 }
6074
6075 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006076 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006077 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006078 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006079 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006080}
6081
6082/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006083/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006084/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006085/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006086int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006087 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006088 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006089 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006090 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006091 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006092 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006093
6094 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006095 isAtomic = true;
6096 Lex.Lex();
6097 }
6098
Chris Lattnerbc639292011-11-27 06:56:53 +00006099 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006100 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006101 isVolatile = true;
6102 Lex.Lex();
6103 }
6104
David Blaikie15d9a4c2015-04-06 20:59:48 +00006105 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006106 LocTy ExplicitTypeLoc = Lex.getLoc();
6107 if (ParseType(Ty) ||
6108 ParseToken(lltok::comma, "expected comma after load's type") ||
6109 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006110 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006111 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6112 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006113
David Blaikie15d9a4c2015-04-06 20:59:48 +00006114 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006115 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006116 if (isAtomic && !Alignment)
6117 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006118 if (Ordering == AtomicOrdering::Release ||
6119 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006120 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006121
David Blaikiea79ac142015-02-27 21:17:42 +00006122 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6123 return Error(ExplicitTypeLoc,
6124 "explicit pointee type doesn't match operand's pointee type");
6125
David Blaikie15d9a4c2015-04-06 20:59:48 +00006126 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006127 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006128}
6129
6130/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006131
6132/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6133/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006134/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006135int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006136 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006137 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006138 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006139 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006140 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006141 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006142
6143 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006144 isAtomic = true;
6145 Lex.Lex();
6146 }
6147
Chris Lattnerbc639292011-11-27 06:56:53 +00006148 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006149 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006150 isVolatile = true;
6151 Lex.Lex();
6152 }
6153
Chris Lattnerac161bf2009-01-02 07:01:27 +00006154 if (ParseTypeAndValue(Val, Loc, PFS) ||
6155 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006156 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006157 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006158 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006159 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006160
Duncan Sands19d0b472010-02-16 11:11:14 +00006161 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006162 return Error(PtrLoc, "store operand must be a pointer");
6163 if (!Val->getType()->isFirstClassType())
6164 return Error(Loc, "store operand must be a first class value");
6165 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6166 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006167 if (isAtomic && !Alignment)
6168 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006169 if (Ordering == AtomicOrdering::Acquire ||
6170 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006171 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006172
Eli Friedman59b66882011-08-09 23:02:53 +00006173 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006174 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006175}
6176
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006177/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006178/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6179/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006180int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006181 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6182 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006183 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6184 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006185 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006186 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006187 bool isWeak = false;
6188
6189 if (EatIfPresent(lltok::kw_weak))
6190 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006191
6192 if (EatIfPresent(lltok::kw_volatile))
6193 isVolatile = true;
6194
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006195 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6196 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6197 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6198 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6199 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006200 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6201 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006202 return true;
6203
JF Bastien800f87a2016-04-06 21:19:33 +00006204 if (SuccessOrdering == AtomicOrdering::Unordered ||
6205 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006206 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006207 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6208 return TokError("cmpxchg failure argument shall be no stronger than the "
6209 "success argument");
6210 if (FailureOrdering == AtomicOrdering::Release ||
6211 FailureOrdering == AtomicOrdering::AcquireRelease)
6212 return TokError(
6213 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006214 if (!Ptr->getType()->isPointerTy())
6215 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6216 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6217 return Error(CmpLoc, "compare value and pointer type do not match");
6218 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6219 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006220 if (!New->getType()->isFirstClassType())
6221 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006222 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6223 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006224 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006225 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006226 Inst = CXI;
6227 return AteExtraComma ? InstExtraComma : InstNormal;
6228}
6229
6230/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006231/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6232/// 'singlethread'? AtomicOrdering
6233int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006234 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6235 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006236 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006237 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006238 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006239 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006240
6241 if (EatIfPresent(lltok::kw_volatile))
6242 isVolatile = true;
6243
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006244 switch (Lex.getKind()) {
6245 default: return TokError("expected binary operation in atomicrmw");
6246 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6247 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6248 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6249 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6250 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6251 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6252 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6253 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6254 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6255 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6256 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6257 }
6258 Lex.Lex(); // Eat the operation.
6259
6260 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6261 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6262 ParseTypeAndValue(Val, ValLoc, PFS) ||
6263 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6264 return true;
6265
JF Bastien800f87a2016-04-06 21:19:33 +00006266 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006267 return TokError("atomicrmw cannot be unordered");
6268 if (!Ptr->getType()->isPointerTy())
6269 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6270 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6271 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6272 if (!Val->getType()->isIntegerTy())
6273 return Error(ValLoc, "atomicrmw operand must be an integer");
6274 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6275 if (Size < 8 || (Size & (Size - 1)))
6276 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6277 " integer");
6278
6279 AtomicRMWInst *RMWI =
6280 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6281 RMWI->setVolatile(isVolatile);
6282 Inst = RMWI;
6283 return AteExtraComma ? InstExtraComma : InstNormal;
6284}
6285
Eli Friedmanfee02c62011-07-25 23:16:38 +00006286/// ParseFence
6287/// ::= 'fence' 'singlethread'? AtomicOrdering
6288int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006289 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006290 SynchronizationScope Scope = CrossThread;
6291 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6292 return true;
6293
JF Bastien800f87a2016-04-06 21:19:33 +00006294 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006295 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006296 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006297 return TokError("fence cannot be monotonic");
6298
6299 Inst = new FenceInst(Context, Ordering, Scope);
6300 return InstNormal;
6301}
6302
Chris Lattnerac161bf2009-01-02 07:01:27 +00006303/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006304/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006305int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006306 Value *Ptr = nullptr;
6307 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006308 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006309
Dan Gohman16cbbe42009-07-29 15:58:36 +00006310 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006311
David Blaikie79e6c742015-02-27 19:29:02 +00006312 Type *Ty = nullptr;
6313 LocTy ExplicitTypeLoc = Lex.getLoc();
6314 if (ParseType(Ty) ||
6315 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6316 ParseTypeAndValue(Ptr, Loc, PFS))
6317 return true;
6318
Eli Benderskyd9806682013-04-22 17:03:42 +00006319 Type *BaseType = Ptr->getType();
6320 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6321 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006322 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006323
David Blaikie8d757942015-03-09 23:08:44 +00006324 if (Ty != BasePointerType->getElementType())
6325 return Error(ExplicitTypeLoc,
6326 "explicit pointee type doesn't match operand's pointee type");
6327
Chris Lattnerac161bf2009-01-02 07:01:27 +00006328 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006329 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006330 // GEP returns a vector of pointers if at least one of parameters is a vector.
6331 // All vector parameters should have the same vector width.
6332 unsigned GEPWidth = BaseType->isVectorTy() ?
6333 BaseType->getVectorNumElements() : 0;
6334
Chris Lattner3822f632009-01-02 08:05:26 +00006335 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006336 if (Lex.getKind() == lltok::MetadataVar) {
6337 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006338 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006339 }
Chris Lattner3822f632009-01-02 08:05:26 +00006340 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006341 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006342 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006343
Nadav Rotem3924cb02011-12-05 06:29:09 +00006344 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006345 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6346 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006347 return Error(EltLoc,
6348 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006349 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006350 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006351 Indices.push_back(Val);
6352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006353
Craig Toppere3dcce92015-08-01 22:20:21 +00006354 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006355 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006356 return Error(Loc, "base element of getelementptr must be sized");
6357
David Blaikied33bad32015-04-17 22:32:13 +00006358 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006359 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006360 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006361 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006362 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006363 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006364}
6365
6366/// ParseExtractValue
6367/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006368int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006369 Value *Val; LocTy Loc;
6370 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006371 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006372 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006373 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006374 return true;
6375
Chris Lattner392be582010-02-12 20:49:41 +00006376 if (!Val->getType()->isAggregateType())
6377 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006378
Jay Foad57aa6362011-07-13 10:26:04 +00006379 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006381 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006382 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006383}
6384
6385/// ParseInsertValue
6386/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006387int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006388 Value *Val0, *Val1; LocTy Loc0, Loc1;
6389 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006390 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6392 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6393 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006394 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006395 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006396
Chris Lattner392be582010-02-12 20:49:41 +00006397 if (!Val0->getType()->isAggregateType())
6398 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006399
David Majnemer30074532015-02-11 07:43:58 +00006400 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6401 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006402 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006403 if (IndexedType != Val1->getType())
6404 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6405 getTypeString(Val1->getType()) + "' instead of '" +
6406 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006407 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006408 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006409}
Nick Lewycky49f89192009-04-04 07:22:01 +00006410
6411//===----------------------------------------------------------------------===//
6412// Embedded metadata.
6413//===----------------------------------------------------------------------===//
6414
6415/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006416/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006417/// Element
6418/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006419bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006420 if (ParseToken(lltok::lbrace, "expected '{' here"))
6421 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006422
Dan Gohman1e0213a2010-07-13 19:33:27 +00006423 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006424 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006425 return false;
6426
Nick Lewycky49f89192009-04-04 07:22:01 +00006427 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006428 // Null is a special case since it is typeless.
6429 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006430 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006431 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006432 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006433
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006434 Metadata *MD;
6435 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006436 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006437 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006438 } while (EatIfPresent(lltok::comma));
6439
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006440 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006441}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006442
6443//===----------------------------------------------------------------------===//
6444// Use-list order directives.
6445//===----------------------------------------------------------------------===//
6446bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6447 SMLoc Loc) {
6448 if (V->use_empty())
6449 return Error(Loc, "value has no uses");
6450
6451 unsigned NumUses = 0;
6452 SmallDenseMap<const Use *, unsigned, 16> Order;
6453 for (const Use &U : V->uses()) {
6454 if (++NumUses > Indexes.size())
6455 break;
6456 Order[&U] = Indexes[NumUses - 1];
6457 }
6458 if (NumUses < 2)
6459 return Error(Loc, "value only has one use");
6460 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6461 return Error(Loc, "wrong number of indexes, expected " +
6462 Twine(std::distance(V->use_begin(), V->use_end())));
6463
6464 V->sortUseList([&](const Use &L, const Use &R) {
6465 return Order.lookup(&L) < Order.lookup(&R);
6466 });
6467 return false;
6468}
6469
6470/// ParseUseListOrderIndexes
6471/// ::= '{' uint32 (',' uint32)+ '}'
6472bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6473 SMLoc Loc = Lex.getLoc();
6474 if (ParseToken(lltok::lbrace, "expected '{' here"))
6475 return true;
6476 if (Lex.getKind() == lltok::rbrace)
6477 return Lex.Error("expected non-empty list of uselistorder indexes");
6478
6479 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6480 // indexes should be distinct numbers in the range [0, size-1], and should
6481 // not be in order.
6482 unsigned Offset = 0;
6483 unsigned Max = 0;
6484 bool IsOrdered = true;
6485 assert(Indexes.empty() && "Expected empty order vector");
6486 do {
6487 unsigned Index;
6488 if (ParseUInt32(Index))
6489 return true;
6490
6491 // Update consistency checks.
6492 Offset += Index - Indexes.size();
6493 Max = std::max(Max, Index);
6494 IsOrdered &= Index == Indexes.size();
6495
6496 Indexes.push_back(Index);
6497 } while (EatIfPresent(lltok::comma));
6498
6499 if (ParseToken(lltok::rbrace, "expected '}' here"))
6500 return true;
6501
6502 if (Indexes.size() < 2)
6503 return Error(Loc, "expected >= 2 uselistorder indexes");
6504 if (Offset != 0 || Max >= Indexes.size())
6505 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6506 if (IsOrdered)
6507 return Error(Loc, "expected uselistorder indexes to change the order");
6508
6509 return false;
6510}
6511
6512/// ParseUseListOrder
6513/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6514bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6515 SMLoc Loc = Lex.getLoc();
6516 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6517 return true;
6518
6519 Value *V;
6520 SmallVector<unsigned, 16> Indexes;
6521 if (ParseTypeAndValue(V, PFS) ||
6522 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6523 ParseUseListOrderIndexes(Indexes))
6524 return true;
6525
6526 return sortUseListOrder(V, Indexes, Loc);
6527}
6528
6529/// ParseUseListOrderBB
6530/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6531bool LLParser::ParseUseListOrderBB() {
6532 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6533 SMLoc Loc = Lex.getLoc();
6534 Lex.Lex();
6535
6536 ValID Fn, Label;
6537 SmallVector<unsigned, 16> Indexes;
6538 if (ParseValID(Fn) ||
6539 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6540 ParseValID(Label) ||
6541 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6542 ParseUseListOrderIndexes(Indexes))
6543 return true;
6544
6545 // Check the function.
6546 GlobalValue *GV;
6547 if (Fn.Kind == ValID::t_GlobalName)
6548 GV = M->getNamedValue(Fn.StrVal);
6549 else if (Fn.Kind == ValID::t_GlobalID)
6550 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6551 else
6552 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6553 if (!GV)
6554 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6555 auto *F = dyn_cast<Function>(GV);
6556 if (!F)
6557 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6558 if (F->isDeclaration())
6559 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6560
6561 // Check the basic block.
6562 if (Label.Kind == ValID::t_LocalID)
6563 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6564 if (Label.Kind != ValID::t_LocalName)
6565 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006566 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006567 if (!V)
6568 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6569 if (!isa<BasicBlock>(V))
6570 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6571
6572 return sortUseListOrder(V, Indexes, Loc);
6573}