blob: dba464f0edecaa6229257cbe991a91cca9394807 [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 Kleckner9d16fa02017-04-19 17:28:52 +0000146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000150 AttributeList AS = CI->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000153 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000158 AttributeList AS = II->getAttributes();
Reid Klecknereb9dd5b2017-04-10 23:31:05 +0000159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
Bill Wendling59dce372013-02-12 10:13:06 +0000161 FnAttrs.merge(B);
Reid Kleckner9d16fa02017-04-19 17:28:52 +0000162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
Bill Wendlingb32b0412013-02-08 06:32:06 +0000164 II->setAttributes(AS);
165 } else {
166 llvm_unreachable("invalid object with forward attribute group reference");
167 }
168 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000169
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000170 // If there are entries in ForwardRefBlockAddresses at this point, the
171 // function was never defined.
172 if (!ForwardRefBlockAddresses.empty())
173 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
174 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000175
David Majnemer19b51052015-02-11 07:43:56 +0000176 for (const auto &NT : NumberedTypes)
177 if (NT.second.second.isValid())
178 return Error(NT.second.second,
179 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000180
181 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
182 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
183 if (I->second.second.isValid())
184 return Error(I->second.second,
185 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000186
David Majnemerdad0a642014-06-27 18:19:56 +0000187 if (!ForwardRefComdats.empty())
188 return Error(ForwardRefComdats.begin()->second,
189 "use of undefined comdat '$" +
190 ForwardRefComdats.begin()->first + "'");
191
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 if (!ForwardRefVals.empty())
193 return Error(ForwardRefVals.begin()->second.second,
194 "use of undefined value '@" + ForwardRefVals.begin()->first +
195 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Chris Lattnerac161bf2009-01-02 07:01:27 +0000197 if (!ForwardRefValIDs.empty())
198 return Error(ForwardRefValIDs.begin()->second.second,
199 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000200 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000201
Devang Pateld2541152009-07-08 19:23:54 +0000202 if (!ForwardRefMDNodes.empty())
203 return Error(ForwardRefMDNodes.begin()->second.second,
204 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000205 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000206
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000207 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000208 for (auto &N : NumberedMetadata) {
209 if (N.second && !N.second->isResolved())
210 N.second->resolveCycles();
211 }
Devang Pateld2541152009-07-08 19:23:54 +0000212
Mehdi Aminie4709272016-09-14 22:29:59 +0000213 for (auto *Inst : InstsWithTBAATag) {
214 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
215 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
216 auto *UpgradedMD = UpgradeTBAANode(*MD);
217 if (MD != UpgradedMD)
218 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
219 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000220
Chris Lattnerac161bf2009-01-02 07:01:27 +0000221 // Look for intrinsic functions and CallInst that need to be upgraded
222 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000223 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000224
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000225 // Some types could be renamed during loading if several modules are
226 // loaded in the same LLVMContext (LTO scenario). In this case we should
227 // remangle intrinsics names as well.
228 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
229 Function *F = &*FI++;
230 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
231 F->replaceAllUsesWith(Remangled.getValue());
232 F->eraseFromParent();
233 }
234 }
235
Manman Ren8b4306c2013-12-02 21:29:56 +0000236 UpgradeDebugInfo(*M);
237
Manman Renb5d7ff42016-05-25 23:14:48 +0000238 UpgradeModuleFlags(*M);
239
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000240 if (!Slots)
241 return false;
242 // Initialize the slot mapping.
243 // Because by this point we've parsed and validated everything, we can "steal"
244 // the mapping from LLParser as it doesn't need it anymore.
245 Slots->GlobalValues = std::move(NumberedVals);
246 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000247 for (const auto &I : NamedTypes)
248 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
249 for (const auto &I : NumberedTypes)
250 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000251
Chris Lattnerac161bf2009-01-02 07:01:27 +0000252 return false;
253}
254
255//===----------------------------------------------------------------------===//
256// Top-Level Entities
257//===----------------------------------------------------------------------===//
258
259bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000260 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 switch (Lex.getKind()) {
262 default: return TokError("expected top-level entity");
263 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000264 case lltok::kw_declare: if (ParseDeclare()) return true; break;
265 case lltok::kw_define: if (ParseDefine()) return true; break;
266 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
267 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000268 case lltok::kw_source_filename:
269 if (ParseSourceFileName())
270 return true;
271 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000272 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000273 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000274 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000275 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000276 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000277 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000278 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000279 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000280 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000281 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
282 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000283 if (ParseUseListOrderBB())
284 return true;
285 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000286 }
287 }
288}
289
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290/// toplevelentity
291/// ::= 'module' 'asm' STRINGCONSTANT
292bool LLParser::ParseModuleAsm() {
293 assert(Lex.getKind() == lltok::kw_module);
294 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000295
296 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000297 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
298 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000299
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000300 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000301 return false;
302}
303
304/// toplevelentity
305/// ::= 'target' 'triple' '=' STRINGCONSTANT
306/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
307bool LLParser::ParseTargetDefinition() {
308 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000309 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000310 switch (Lex.Lex()) {
311 default: return TokError("unknown target property");
312 case lltok::kw_triple:
313 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000314 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
315 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000316 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000317 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 return false;
319 case lltok::kw_datalayout:
320 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000321 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
322 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000323 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000324 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return false;
326 }
327}
328
Bill Wendling706d3d62012-11-28 08:41:48 +0000329/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000330/// ::= 'source_filename' '=' STRINGCONSTANT
331bool LLParser::ParseSourceFileName() {
332 assert(Lex.getKind() == lltok::kw_source_filename);
333 std::string Str;
334 Lex.Lex();
335 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
336 ParseStringConstant(Str))
337 return true;
338 M->setSourceFileName(Str);
339 return false;
340}
341
342/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000343/// ::= 'deplibs' '=' '[' ']'
344/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
345/// FIXME: Remove in 4.0. Currently parse, but ignore.
346bool LLParser::ParseDepLibs() {
347 assert(Lex.getKind() == lltok::kw_deplibs);
348 Lex.Lex();
349 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
350 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
351 return true;
352
353 if (EatIfPresent(lltok::rsquare))
354 return false;
355
356 do {
357 std::string Str;
358 if (ParseStringConstant(Str)) return true;
359 } while (EatIfPresent(lltok::comma));
360
361 return ParseToken(lltok::rsquare, "expected ']' at end of list");
362}
363
Dan Gohman466876b2009-08-12 23:32:33 +0000364/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000365/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000366bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000367 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000369 Lex.Lex(); // eat LocalVarID;
370
371 if (ParseToken(lltok::equal, "expected '=' after name") ||
372 ParseToken(lltok::kw_type, "expected 'type' after '='"))
373 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000374
Craig Topper2617dcc2014-04-15 06:32:26 +0000375 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000376 if (ParseStructDefinition(TypeLoc, "",
377 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379 if (!isa<StructType>(Result)) {
380 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
381 if (Entry.first)
382 return Error(TypeLoc, "non-struct types may not be recursive");
383 Entry.first = Result;
384 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000385 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000386
Chris Lattnerac161bf2009-01-02 07:01:27 +0000387 return false;
388}
389
390/// toplevelentity
391/// ::= LocalVar '=' 'type' type
392bool LLParser::ParseNamedType() {
393 std::string Name = Lex.getStrVal();
394 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000395 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000396
Chris Lattner3822f632009-01-02 08:05:26 +0000397 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000398 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000399 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000400
Craig Topper2617dcc2014-04-15 06:32:26 +0000401 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000402 if (ParseStructDefinition(NameLoc, Name,
403 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 if (!isa<StructType>(Result)) {
406 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
407 if (Entry.first)
408 return Error(NameLoc, "non-struct types may not be recursive");
409 Entry.first = Result;
410 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000411 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000412
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000413 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000414}
415
Chris Lattnerac161bf2009-01-02 07:01:27 +0000416/// toplevelentity
417/// ::= 'declare' FunctionHeader
418bool LLParser::ParseDeclare() {
419 assert(Lex.getKind() == lltok::kw_declare);
420 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421
Peter Collingbourne21521892016-06-21 23:42:48 +0000422 std::vector<std::pair<unsigned, MDNode *>> MDs;
423 while (Lex.getKind() == lltok::MetadataVar) {
424 unsigned MDK;
425 MDNode *N;
426 if (ParseMetadataAttachment(MDK, N))
427 return true;
428 MDs.push_back({MDK, N});
429 }
430
Chris Lattnerac161bf2009-01-02 07:01:27 +0000431 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000432 if (ParseFunctionHeader(F, false))
433 return true;
434 for (auto &MD : MDs)
435 F->addMetadata(MD.first, *MD.second);
436 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000437}
438
439/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000440/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441bool LLParser::ParseDefine() {
442 assert(Lex.getKind() == lltok::kw_define);
443 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000444
Chris Lattnerac161bf2009-01-02 07:01:27 +0000445 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000446 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000447 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000448 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449}
450
Chris Lattner3822f632009-01-02 08:05:26 +0000451/// ParseGlobalType
452/// ::= 'constant'
453/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454bool LLParser::ParseGlobalType(bool &IsConstant) {
455 if (Lex.getKind() == lltok::kw_constant)
456 IsConstant = true;
457 else if (Lex.getKind() == lltok::kw_global)
458 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000459 else {
460 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000461 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000462 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000463 Lex.Lex();
464 return false;
465}
466
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000467bool LLParser::ParseOptionalUnnamedAddr(
468 GlobalVariable::UnnamedAddr &UnnamedAddr) {
469 if (EatIfPresent(lltok::kw_unnamed_addr))
470 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
471 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
472 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
473 else
474 UnnamedAddr = GlobalValue::UnnamedAddr::None;
475 return false;
476}
477
Dan Gohman466876b2009-08-12 23:32:33 +0000478/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000479/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000480/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
481/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000482/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000483/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
484/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000485bool LLParser::ParseUnnamedGlobal() {
486 unsigned VarID = NumberedVals.size();
487 std::string Name;
488 LocTy NameLoc = Lex.getLoc();
489
490 // Handle the GlobalID form.
491 if (Lex.getKind() == lltok::GlobalID) {
492 if (Lex.getUIntVal() != VarID)
493 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000494 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000495 Lex.Lex(); // eat GlobalID;
496
497 if (ParseToken(lltok::equal, "expected '=' after name"))
498 return true;
499 }
500
501 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000502 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000503 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000504 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000505 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000506 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000507 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000508
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000509 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000510 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000511 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000512
513 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
514 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000515}
516
Chris Lattnerac161bf2009-01-02 07:01:27 +0000517/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000518/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000519/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
520/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000521bool LLParser::ParseNamedGlobal() {
522 assert(Lex.getKind() == lltok::GlobalVar);
523 LocTy NameLoc = Lex.getLoc();
524 std::string Name = Lex.getStrVal();
525 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Chris Lattnerac161bf2009-01-02 07:01:27 +0000527 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000528 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000529 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000530 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000531 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000532 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000533 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000534 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000535
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000536 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000537 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000538 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000539
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000540 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
541 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000542}
543
David Majnemerdad0a642014-06-27 18:19:56 +0000544bool LLParser::parseComdat() {
545 assert(Lex.getKind() == lltok::ComdatVar);
546 std::string Name = Lex.getStrVal();
547 LocTy NameLoc = Lex.getLoc();
548 Lex.Lex();
549
550 if (ParseToken(lltok::equal, "expected '=' here"))
551 return true;
552
553 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
554 return TokError("expected comdat type");
555
556 Comdat::SelectionKind SK;
557 switch (Lex.getKind()) {
558 default:
559 return TokError("unknown selection kind");
560 case lltok::kw_any:
561 SK = Comdat::Any;
562 break;
563 case lltok::kw_exactmatch:
564 SK = Comdat::ExactMatch;
565 break;
566 case lltok::kw_largest:
567 SK = Comdat::Largest;
568 break;
569 case lltok::kw_noduplicates:
570 SK = Comdat::NoDuplicates;
571 break;
572 case lltok::kw_samesize:
573 SK = Comdat::SameSize;
574 break;
575 }
576 Lex.Lex();
577
578 // See if the comdat was forward referenced, if so, use the comdat.
579 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
580 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
581 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
582 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
583
584 Comdat *C;
585 if (I != ComdatSymTab.end())
586 C = &I->second;
587 else
588 C = M->getOrInsertComdat(Name);
589 C->setSelectionKind(SK);
590
591 return false;
592}
593
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000594// MDString:
595// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000596bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000597 std::string Str;
598 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000599 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600 return false;
601}
602
603// MDNode:
604// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000605bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000607 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000608 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000609 if (ParseUInt32(MID))
610 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000611
Chris Lattner8eff0152010-04-01 05:14:45 +0000612 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000613 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000614 Result = NumberedMetadata[MID];
615 return false;
616 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000617
Chris Lattner8eff0152010-04-01 05:14:45 +0000618 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000619 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000620 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000621
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000622 Result = FwdRef.first.get();
623 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000624 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000625}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000626
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000627/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000628/// !foo = !{ !1, !2 }
629bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000630 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000631 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000632 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000633
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000634 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000635 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000636 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000637 return true;
638
Dan Gohman2637cc12010-07-21 23:38:33 +0000639 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000640 if (Lex.getKind() != lltok::rbrace)
641 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000642 if (ParseToken(lltok::exclaim, "Expected '!' here"))
643 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000644
Craig Topper2617dcc2014-04-15 06:32:26 +0000645 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000646 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000647 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000648 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000649
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000650 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000651}
652
Devang Patel39e64d42009-07-01 19:21:12 +0000653/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000654/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000655bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000656 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000657 Lex.Lex();
658 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000659
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000660 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000661 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000662 ParseToken(lltok::equal, "expected '=' here"))
663 return true;
664
665 // Detect common error, from old metadata syntax.
666 if (Lex.getKind() == lltok::Type)
667 return TokError("unexpected type in metadata definition");
668
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000669 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000670 if (Lex.getKind() == lltok::MetadataVar) {
671 if (ParseSpecializedMDNode(Init, IsDistinct))
672 return true;
673 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
674 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000675 return true;
676
Chris Lattnerfc58af22009-12-30 04:51:58 +0000677 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000678 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000679 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000680 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000681 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000682
Chris Lattnerfc58af22009-12-30 04:51:58 +0000683 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
684 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000685 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000686 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000687 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000688 }
689
Devang Patel39e64d42009-07-01 19:21:12 +0000690 return false;
691}
692
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000693static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
694 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
695 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
696}
697
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000698/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000699/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
700/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000701/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000702///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000703/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000704/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000705///
Eric Christopher536f0a92015-05-28 23:07:39 +0000706/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000707///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000708bool LLParser::parseIndirectSymbol(
709 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
710 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
711 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000712 bool IsAlias;
713 if (Lex.getKind() == lltok::kw_alias)
714 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000715 else if (Lex.getKind() == lltok::kw_ifunc)
716 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000717 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000718 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720
Rafael Espindola78527052013-10-06 15:10:43 +0000721 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
722
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000723 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000724 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000725
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000726 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000727 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000728 "symbol with local linkage must have default visibility");
729
David Blaikie2f408302015-09-11 03:22:04 +0000730 Type *Ty;
731 LocTy ExplicitTypeLoc = Lex.getLoc();
732 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000733 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000734 return true;
735
Rafael Espindola64c1e182014-06-03 02:41:57 +0000736 Constant *Aliasee;
737 LocTy AliaseeLoc = Lex.getLoc();
738 if (Lex.getKind() != lltok::kw_bitcast &&
739 Lex.getKind() != lltok::kw_getelementptr &&
740 Lex.getKind() != lltok::kw_addrspacecast &&
741 Lex.getKind() != lltok::kw_inttoptr) {
742 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000743 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000744 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000745 // The bitcast dest type is not present, it is implied by the dest type.
746 ValID ID;
747 if (ParseValID(ID))
748 return true;
749 if (ID.Kind != ValID::t_Constant)
750 return Error(AliaseeLoc, "invalid aliasee");
751 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000753
Rafael Espindola64c1e182014-06-03 02:41:57 +0000754 Type *AliaseeType = Aliasee->getType();
755 auto *PTy = dyn_cast<PointerType>(AliaseeType);
756 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000757 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000758 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000759
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000760 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000761 return Error(
762 ExplicitTypeLoc,
763 "explicit pointee type doesn't match operand's pointee type");
764
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000765 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
766 return Error(
767 ExplicitTypeLoc,
768 "explicit pointee type should be a function type");
769
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000770 GlobalValue *GVal = nullptr;
771
772 // See if the alias was forward referenced, if so, prepare to replace the
773 // forward reference.
774 if (!Name.empty()) {
775 GVal = M->getNamedValue(Name);
776 if (GVal) {
777 if (!ForwardRefVals.erase(Name))
778 return Error(NameLoc, "redefinition of global '@" + Name + "'");
779 }
780 } else {
781 auto I = ForwardRefValIDs.find(NumberedVals.size());
782 if (I != ForwardRefValIDs.end()) {
783 GVal = I->second.first;
784 ForwardRefValIDs.erase(I);
785 }
786 }
787
Chris Lattnerac161bf2009-01-02 07:01:27 +0000788 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000789 std::unique_ptr<GlobalIndirectSymbol> GA;
790 if (IsAlias)
791 GA.reset(GlobalAlias::create(Ty, AddrSpace,
792 (GlobalValue::LinkageTypes)Linkage, Name,
793 Aliasee, /*Parent*/ nullptr));
794 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000795 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
796 (GlobalValue::LinkageTypes)Linkage, Name,
797 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000798 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000799 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000800 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000801 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
Rafael Espindola54fc2982015-06-17 17:53:31 +0000803 if (Name.empty())
804 NumberedVals.push_back(GA.get());
805
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000806 if (GVal) {
807 // Verify that types agree.
808 if (GVal->getType() != GA->getType())
809 return Error(
810 ExplicitTypeLoc,
811 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000812
Chris Lattnerac161bf2009-01-02 07:01:27 +0000813 // If they agree, just RAUW the old value with the alias and remove the
814 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000815 GVal->replaceAllUsesWith(GA.get());
816 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000817 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerac161bf2009-01-02 07:01:27 +0000819 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000820 if (IsAlias)
821 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
822 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000823 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000824 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000825
Rafael Espindolaaa273822014-05-09 21:49:17 +0000826 // The module owns this now
827 GA.release();
828
Chris Lattnerac161bf2009-01-02 07:01:27 +0000829 return false;
830}
831
832/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000833/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000834/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000835/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000836/// ::= 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
Chris Lattnerac161bf2009-01-02 07:01:27 +0000839///
Eric Christopher536f0a92015-05-28 23:07:39 +0000840/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000841/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000842///
843bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
844 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000845 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000846 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000847 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000848 if (!isValidVisibilityForLinkage(Visibility, Linkage))
849 return Error(NameLoc,
850 "symbol with local linkage must have default visibility");
851
Chris Lattnerac161bf2009-01-02 07:01:27 +0000852 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000853 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000854 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000855 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000856
Craig Topper2617dcc2014-04-15 06:32:26 +0000857 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000858 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000859 ParseOptionalToken(lltok::kw_externally_initialized,
860 IsExternallyInitialized,
861 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000862 ParseGlobalType(IsConstant) ||
863 ParseType(Ty, TyLoc))
864 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000865
Chris Lattnerac161bf2009-01-02 07:01:27 +0000866 // If the linkage is specified and is external, then no initializer is
867 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000868 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000869 if (!HasLinkage ||
870 !GlobalValue::isValidDeclarationLinkage(
871 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000872 if (ParseGlobalValue(Ty, Init))
873 return true;
874 }
875
David Majnemer49b3d9b2015-02-16 08:41:08 +0000876 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000877 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000878
David Majnemer598bd052014-12-09 05:56:09 +0000879 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000880
881 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000882 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000883 GVal = M->getNamedValue(Name);
884 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000885 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000886 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000887 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000888 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000889 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000890 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000891 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000892 ForwardRefValIDs.erase(I);
893 }
894 }
895
David Majnemer598bd052014-12-09 05:56:09 +0000896 GlobalVariable *GV;
897 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000898 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
899 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000900 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000901 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000902 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 return Error(TyLoc,
904 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000905
David Majnemer598bd052014-12-09 05:56:09 +0000906 GV = cast<GlobalVariable>(GVal);
907
Chris Lattnerac161bf2009-01-02 07:01:27 +0000908 // Move the forward-reference to the correct spot in the module.
909 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
910 }
911
912 if (Name.empty())
913 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000914
Chris Lattnerac161bf2009-01-02 07:01:27 +0000915 // Set the parsed properties on the global.
916 if (Init)
917 GV->setInitializer(Init);
918 GV->setConstant(IsConstant);
919 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
920 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000921 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000922 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000923 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000924 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000925
Chris Lattnerac161bf2009-01-02 07:01:27 +0000926 // Parse attributes on the global.
927 while (Lex.getKind() == lltok::comma) {
928 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattnerac161bf2009-01-02 07:01:27 +0000930 if (Lex.getKind() == lltok::kw_section) {
931 Lex.Lex();
932 GV->setSection(Lex.getStrVal());
933 if (ParseToken(lltok::StringConstant, "expected global section string"))
934 return true;
935 } else if (Lex.getKind() == lltok::kw_align) {
936 unsigned Alignment;
937 if (ParseOptionalAlignment(Alignment)) return true;
938 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000939 } else if (Lex.getKind() == lltok::MetadataVar) {
940 if (ParseGlobalObjectMetadataAttachment(*GV))
941 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000942 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000943 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000944 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000945 return true;
946 if (C)
947 GV->setComdat(C);
948 else
949 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000950 }
951 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000952
Chris Lattnerac161bf2009-01-02 07:01:27 +0000953 return false;
954}
955
Bill Wendling63b88192013-02-06 06:52:58 +0000956/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000957/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000958bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000959 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000960 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000961 Lex.Lex();
962
David Majnemerb39e22b2014-12-09 18:33:57 +0000963 if (Lex.getKind() != lltok::AttrGrpID)
964 return TokError("expected attribute group id");
965
Bill Wendling63b88192013-02-06 06:52:58 +0000966 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000967 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000968 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000969 Lex.Lex();
970
971 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000972 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000973 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000974 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000975 ParseToken(lltok::rbrace, "expected end of attribute group"))
976 return true;
977
Bill Wendlingb32b0412013-02-08 06:32:06 +0000978 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000979 return Error(AttrGrpLoc, "attribute group has no attributes");
980
981 return false;
982}
983
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000985/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000986bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
987 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000988 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000989 bool HaveError = false;
990
991 B.clear();
992
Bill Wendling63b88192013-02-06 06:52:58 +0000993 while (true) {
994 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000995 if (Token == lltok::kw_builtin)
996 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000997 switch (Token) {
998 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000999 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001000 return Error(Lex.getLoc(), "unterminated attribute group");
1001 case lltok::rbrace:
1002 // Finished.
1003 return false;
1004
Bill Wendlingb32b0412013-02-08 06:32:06 +00001005 case lltok::AttrGrpID: {
1006 // Allow a function to reference an attribute group:
1007 //
1008 // define void @foo() #1 { ... }
1009 if (inAttrGrp)
1010 HaveError |=
1011 Error(Lex.getLoc(),
1012 "cannot have an attribute group reference in an attribute group");
1013
1014 unsigned AttrGrpNum = Lex.getUIntVal();
1015 if (inAttrGrp) break;
1016
1017 // Save the reference to the attribute group. We'll fill it in later.
1018 FwdRefAttrGrps.push_back(AttrGrpNum);
1019 break;
1020 }
Bill Wendling63b88192013-02-06 06:52:58 +00001021 // Target-dependent attributes:
1022 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001023 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001024 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001025 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001026 }
1027
1028 // Target-independent attributes:
1029 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001030 // As a hack, we allow function alignment to be initially parsed as an
1031 // attribute on a function declaration/definition or added to an attribute
1032 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001033 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001034 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001035 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001036 if (ParseToken(lltok::equal, "expected '=' here") ||
1037 ParseUInt32(Alignment))
1038 return true;
1039 } else {
1040 if (ParseOptionalAlignment(Alignment))
1041 return true;
1042 }
Bill Wendling63b88192013-02-06 06:52:58 +00001043 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001044 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001045 }
1046 case lltok::kw_alignstack: {
1047 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001048 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001049 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001050 if (ParseToken(lltok::equal, "expected '=' here") ||
1051 ParseUInt32(Alignment))
1052 return true;
1053 } else {
1054 if (ParseOptionalStackAlignment(Alignment))
1055 return true;
1056 }
Bill Wendling63b88192013-02-06 06:52:58 +00001057 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001058 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001059 }
George Burgess IV278199f2016-04-12 01:05:35 +00001060 case lltok::kw_allocsize: {
1061 unsigned ElemSizeArg;
1062 Optional<unsigned> NumElemsArg;
1063 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1064 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1065 return true;
1066 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1067 continue;
1068 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001069 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1070 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1071 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1072 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1073 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001074 case lltok::kw_inaccessiblememonly:
1075 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1076 case lltok::kw_inaccessiblemem_or_argmemonly:
1077 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001078 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1079 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1080 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1081 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1082 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1083 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1084 case lltok::kw_noimplicitfloat:
1085 B.addAttribute(Attribute::NoImplicitFloat); break;
1086 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1087 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1088 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1089 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001090 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001091 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1092 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1093 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1094 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1095 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1096 case lltok::kw_returns_twice:
1097 B.addAttribute(Attribute::ReturnsTwice); break;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001098 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001099 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1100 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1101 case lltok::kw_sspstrong:
1102 B.addAttribute(Attribute::StackProtectStrong); break;
1103 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1104 case lltok::kw_sanitize_address:
1105 B.addAttribute(Attribute::SanitizeAddress); break;
1106 case lltok::kw_sanitize_thread:
1107 B.addAttribute(Attribute::SanitizeThread); break;
1108 case lltok::kw_sanitize_memory:
1109 B.addAttribute(Attribute::SanitizeMemory); break;
1110 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001111 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001112
1113 // Error handling.
1114 case lltok::kw_inreg:
1115 case lltok::kw_signext:
1116 case lltok::kw_zeroext:
1117 HaveError |=
1118 Error(Lex.getLoc(),
1119 "invalid use of attribute on a function");
1120 break;
1121 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001122 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001123 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001124 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001125 case lltok::kw_nest:
1126 case lltok::kw_noalias:
1127 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001128 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001129 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001130 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001131 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001132 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001133 HaveError |=
1134 Error(Lex.getLoc(),
1135 "invalid use of parameter-only attribute on a function");
1136 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001137 }
1138
1139 Lex.Lex();
1140 }
1141}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001142
1143//===----------------------------------------------------------------------===//
1144// GlobalValue Reference/Resolution Routines.
1145//===----------------------------------------------------------------------===//
1146
Karl Schimpf77729782015-09-03 18:06:44 +00001147static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1148 const std::string &Name) {
1149 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1150 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1151 else
1152 return new GlobalVariable(*M, PTy->getElementType(), false,
1153 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1154 nullptr, GlobalVariable::NotThreadLocal,
1155 PTy->getAddressSpace());
1156}
1157
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158/// GetGlobalVal - Get a value with the specified name or ID, creating a
1159/// forward reference record if needed. This can return null if the value
1160/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001161GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001162 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001163 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001164 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001165 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001166 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001167 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001168
Chris Lattnerac161bf2009-01-02 07:01:27 +00001169 // Look this name up in the normal function symbol table.
1170 GlobalValue *Val =
1171 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001172
Chris Lattnerac161bf2009-01-02 07:01:27 +00001173 // If this is a forward reference for the value, see if we already created a
1174 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001175 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001176 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001177 if (I != ForwardRefVals.end())
1178 Val = I->second.first;
1179 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 // If we have the value in the symbol table or fwd-ref table, return it.
1182 if (Val) {
1183 if (Val->getType() == Ty) return Val;
1184 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001185 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001186 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001187 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001188
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001190 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001191 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1192 return FwdVal;
1193}
1194
Chris Lattner229907c2011-07-18 04:54:35 +00001195GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1196 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001197 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001198 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001199 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001201
Craig Topper2617dcc2014-04-15 06:32:26 +00001202 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001203
Chris Lattnerac161bf2009-01-02 07:01:27 +00001204 // If this is a forward reference for the value, see if we already created a
1205 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001206 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001207 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 if (I != ForwardRefValIDs.end())
1209 Val = I->second.first;
1210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001211
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 // If we have the value in the symbol table or fwd-ref table, return it.
1213 if (Val) {
1214 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001215 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001216 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001217 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001219
Chris Lattnerac161bf2009-01-02 07:01:27 +00001220 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001221 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001222 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1223 return FwdVal;
1224}
1225
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001227// Comdat Reference/Resolution Routines.
1228//===----------------------------------------------------------------------===//
1229
1230Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1231 // Look this name up in the comdat symbol table.
1232 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1233 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1234 if (I != ComdatSymTab.end())
1235 return &I->second;
1236
1237 // Otherwise, create a new forward reference for this value and remember it.
1238 Comdat *C = M->getOrInsertComdat(Name);
1239 ForwardRefComdats[Name] = Loc;
1240 return C;
1241}
1242
David Majnemerdad0a642014-06-27 18:19:56 +00001243//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001244// Helper Routines.
1245//===----------------------------------------------------------------------===//
1246
1247/// ParseToken - If the current token has the specified kind, eat it and return
1248/// success. Otherwise, emit the specified error and return failure.
1249bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1250 if (Lex.getKind() != T)
1251 return TokError(ErrMsg);
1252 Lex.Lex();
1253 return false;
1254}
1255
Chris Lattner3822f632009-01-02 08:05:26 +00001256/// ParseStringConstant
1257/// ::= StringConstant
1258bool LLParser::ParseStringConstant(std::string &Result) {
1259 if (Lex.getKind() != lltok::StringConstant)
1260 return TokError("expected string constant");
1261 Result = Lex.getStrVal();
1262 Lex.Lex();
1263 return false;
1264}
1265
1266/// ParseUInt32
1267/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001268bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001269 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1270 return TokError("expected integer");
1271 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1272 if (Val64 != unsigned(Val64))
1273 return TokError("expected 32-bit integer (too large)");
1274 Val = Val64;
1275 Lex.Lex();
1276 return false;
1277}
1278
Hal Finkelb0407ba2014-07-18 15:51:28 +00001279/// ParseUInt64
1280/// ::= uint64
1281bool LLParser::ParseUInt64(uint64_t &Val) {
1282 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1283 return TokError("expected integer");
1284 Val = Lex.getAPSIntVal().getLimitedValue();
1285 Lex.Lex();
1286 return false;
1287}
1288
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001289/// ParseTLSModel
1290/// := 'localdynamic'
1291/// := 'initialexec'
1292/// := 'localexec'
1293bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1294 switch (Lex.getKind()) {
1295 default:
1296 return TokError("expected localdynamic, initialexec or localexec");
1297 case lltok::kw_localdynamic:
1298 TLM = GlobalVariable::LocalDynamicTLSModel;
1299 break;
1300 case lltok::kw_initialexec:
1301 TLM = GlobalVariable::InitialExecTLSModel;
1302 break;
1303 case lltok::kw_localexec:
1304 TLM = GlobalVariable::LocalExecTLSModel;
1305 break;
1306 }
1307
1308 Lex.Lex();
1309 return false;
1310}
1311
1312/// ParseOptionalThreadLocal
1313/// := /*empty*/
1314/// := 'thread_local'
1315/// := 'thread_local' '(' tlsmodel ')'
1316bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1317 TLM = GlobalVariable::NotThreadLocal;
1318 if (!EatIfPresent(lltok::kw_thread_local))
1319 return false;
1320
1321 TLM = GlobalVariable::GeneralDynamicTLSModel;
1322 if (Lex.getKind() == lltok::lparen) {
1323 Lex.Lex();
1324 return ParseTLSModel(TLM) ||
1325 ParseToken(lltok::rparen, "expected ')' after thread local model");
1326 }
1327 return false;
1328}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001329
1330/// ParseOptionalAddrSpace
1331/// := /*empty*/
1332/// := 'addrspace' '(' uint32 ')'
1333bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1334 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001335 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001336 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001337 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001338 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001339 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001340}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001341
Artur Pilipenko17376c42015-08-03 14:31:49 +00001342/// ParseStringAttribute
1343/// := StringConstant
1344/// := StringConstant '=' StringConstant
1345bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1346 std::string Attr = Lex.getStrVal();
1347 Lex.Lex();
1348 std::string Val;
1349 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1350 return true;
1351 B.addAttribute(Attr, Val);
1352 return false;
1353}
1354
Bill Wendling34c2eb22012-12-04 23:40:58 +00001355/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1356bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1357 bool HaveError = false;
1358
1359 B.clear();
1360
Eugene Zelenko1804a772016-08-25 00:45:04 +00001361 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001362 lltok::Kind Token = Lex.getKind();
1363 switch (Token) {
1364 default: // End of attributes.
1365 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001366 case lltok::StringConstant: {
1367 if (ParseStringAttribute(B))
1368 return true;
1369 continue;
1370 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001371 case lltok::kw_align: {
1372 unsigned Alignment;
1373 if (ParseOptionalAlignment(Alignment))
1374 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001375 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001376 continue;
1377 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001378 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001379 case lltok::kw_dereferenceable: {
1380 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001381 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001382 return true;
1383 B.addDereferenceableAttr(Bytes);
1384 continue;
1385 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001386 case lltok::kw_dereferenceable_or_null: {
1387 uint64_t Bytes;
1388 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1389 return true;
1390 B.addDereferenceableOrNullAttr(Bytes);
1391 continue;
1392 }
Reid Klecknera534a382013-12-19 02:14:12 +00001393 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001394 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1395 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1396 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1397 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001398 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001399 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1400 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001401 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001402 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1403 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001404 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001405 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001406 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001407 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001408
Stephen Lin7577ed52013-04-20 13:16:13 +00001409 case lltok::kw_alignstack:
1410 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001411 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001412 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001413 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001414 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001415 case lltok::kw_minsize:
1416 case lltok::kw_naked:
1417 case lltok::kw_nobuiltin:
1418 case lltok::kw_noduplicate:
1419 case lltok::kw_noimplicitfloat:
1420 case lltok::kw_noinline:
1421 case lltok::kw_nonlazybind:
1422 case lltok::kw_noredzone:
1423 case lltok::kw_noreturn:
1424 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001425 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001426 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001427 case lltok::kw_returns_twice:
1428 case lltok::kw_sanitize_address:
1429 case lltok::kw_sanitize_memory:
1430 case lltok::kw_sanitize_thread:
1431 case lltok::kw_ssp:
1432 case lltok::kw_sspreq:
1433 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001434 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001435 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001436 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1437 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001438 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001439
Bill Wendling34c2eb22012-12-04 23:40:58 +00001440 Lex.Lex();
1441 }
1442}
1443
1444/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1445bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1446 bool HaveError = false;
1447
1448 B.clear();
1449
Eugene Zelenko1804a772016-08-25 00:45:04 +00001450 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001451 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001452 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001453 default: // End of attributes.
1454 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001455 case lltok::StringConstant: {
1456 if (ParseStringAttribute(B))
1457 return true;
1458 continue;
1459 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001460 case lltok::kw_dereferenceable: {
1461 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001462 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001463 return true;
1464 B.addDereferenceableAttr(Bytes);
1465 continue;
1466 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001467 case lltok::kw_dereferenceable_or_null: {
1468 uint64_t Bytes;
1469 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1470 return true;
1471 B.addDereferenceableOrNullAttr(Bytes);
1472 continue;
1473 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001474 case lltok::kw_align: {
1475 unsigned Alignment;
1476 if (ParseOptionalAlignment(Alignment))
1477 return true;
1478 B.addAlignmentAttr(Alignment);
1479 continue;
1480 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001481 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1482 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001483 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001484 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1485 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001486
Bill Wendling34c2eb22012-12-04 23:40:58 +00001487 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001488 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001489 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001490 case lltok::kw_nest:
1491 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001492 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001493 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001494 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001495 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001496 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001497 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001498
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001499 case lltok::kw_alignstack:
1500 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001501 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001502 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001503 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001504 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001505 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001506 case lltok::kw_minsize:
1507 case lltok::kw_naked:
1508 case lltok::kw_nobuiltin:
1509 case lltok::kw_noduplicate:
1510 case lltok::kw_noimplicitfloat:
1511 case lltok::kw_noinline:
1512 case lltok::kw_nonlazybind:
1513 case lltok::kw_noredzone:
1514 case lltok::kw_noreturn:
1515 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001516 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001517 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001518 case lltok::kw_returns_twice:
1519 case lltok::kw_sanitize_address:
1520 case lltok::kw_sanitize_memory:
1521 case lltok::kw_sanitize_thread:
1522 case lltok::kw_ssp:
1523 case lltok::kw_sspreq:
1524 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001525 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001526 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001527 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001528 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001529
1530 case lltok::kw_readnone:
1531 case lltok::kw_readonly:
1532 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001533 }
1534
Chris Lattnerac161bf2009-01-02 07:01:27 +00001535 Lex.Lex();
1536 }
1537}
1538
Rafael Espindolac6269912016-05-10 17:16:45 +00001539static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1540 HasLinkage = true;
1541 switch (Kind) {
1542 default:
1543 HasLinkage = false;
1544 return GlobalValue::ExternalLinkage;
1545 case lltok::kw_private:
1546 return GlobalValue::PrivateLinkage;
1547 case lltok::kw_internal:
1548 return GlobalValue::InternalLinkage;
1549 case lltok::kw_weak:
1550 return GlobalValue::WeakAnyLinkage;
1551 case lltok::kw_weak_odr:
1552 return GlobalValue::WeakODRLinkage;
1553 case lltok::kw_linkonce:
1554 return GlobalValue::LinkOnceAnyLinkage;
1555 case lltok::kw_linkonce_odr:
1556 return GlobalValue::LinkOnceODRLinkage;
1557 case lltok::kw_available_externally:
1558 return GlobalValue::AvailableExternallyLinkage;
1559 case lltok::kw_appending:
1560 return GlobalValue::AppendingLinkage;
1561 case lltok::kw_common:
1562 return GlobalValue::CommonLinkage;
1563 case lltok::kw_extern_weak:
1564 return GlobalValue::ExternalWeakLinkage;
1565 case lltok::kw_external:
1566 return GlobalValue::ExternalLinkage;
1567 }
1568}
1569
Chris Lattnerac161bf2009-01-02 07:01:27 +00001570/// ParseOptionalLinkage
1571/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001572/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001573/// ::= 'internal'
1574/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001575/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001576/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001577/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001578/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001579/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001580/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581/// ::= 'extern_weak'
1582/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001583bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1584 unsigned &Visibility,
1585 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001586 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1587 if (HasLinkage)
1588 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001589 ParseOptionalVisibility(Visibility);
1590 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001591 return false;
1592}
1593
1594/// ParseOptionalVisibility
1595/// ::= /*empty*/
1596/// ::= 'default'
1597/// ::= 'hidden'
1598/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001599///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001600void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001601 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001602 default:
1603 Res = GlobalValue::DefaultVisibility;
1604 return;
1605 case lltok::kw_default:
1606 Res = GlobalValue::DefaultVisibility;
1607 break;
1608 case lltok::kw_hidden:
1609 Res = GlobalValue::HiddenVisibility;
1610 break;
1611 case lltok::kw_protected:
1612 Res = GlobalValue::ProtectedVisibility;
1613 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001614 }
1615 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001616}
1617
Nico Rieck7157bb72014-01-14 15:22:47 +00001618/// ParseOptionalDLLStorageClass
1619/// ::= /*empty*/
1620/// ::= 'dllimport'
1621/// ::= 'dllexport'
1622///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001623void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001624 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001625 default:
1626 Res = GlobalValue::DefaultStorageClass;
1627 return;
1628 case lltok::kw_dllimport:
1629 Res = GlobalValue::DLLImportStorageClass;
1630 break;
1631 case lltok::kw_dllexport:
1632 Res = GlobalValue::DLLExportStorageClass;
1633 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001634 }
1635 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001636}
1637
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638/// ParseOptionalCallingConv
1639/// ::= /*empty*/
1640/// ::= 'ccc'
1641/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001642/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001643/// ::= 'coldcc'
1644/// ::= 'x86_stdcallcc'
1645/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001646/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001647/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001648/// ::= 'arm_apcscc'
1649/// ::= 'arm_aapcscc'
1650/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001651/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001652/// ::= 'avr_intrcc'
1653/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001654/// ::= 'ptx_kernel'
1655/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001656/// ::= 'spir_func'
1657/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001658/// ::= 'x86_64_sysvcc'
1659/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001660/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001661/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001662/// ::= 'preserve_mostcc'
1663/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001664/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001665/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001666/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001667/// ::= 'hhvmcc'
1668/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001669/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001670/// ::= 'amdgpu_vs'
1671/// ::= 'amdgpu_tcs'
1672/// ::= 'amdgpu_tes'
1673/// ::= 'amdgpu_gs'
1674/// ::= 'amdgpu_ps'
1675/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001676/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001677/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001678///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001679bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001680 switch (Lex.getKind()) {
1681 default: CC = CallingConv::C; return false;
1682 case lltok::kw_ccc: CC = CallingConv::C; break;
1683 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1684 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1685 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1686 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001687 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001688 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001689 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001690 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1691 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1692 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001693 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001694 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1695 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001696 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1697 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001698 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1699 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001700 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001701 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1702 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001703 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001704 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001705 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1706 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001707 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001708 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001709 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001710 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1711 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001712 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001713 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1714 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1715 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1716 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001717 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001718 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001719 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001720 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001721 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001723
Chris Lattnerac161bf2009-01-02 07:01:27 +00001724 Lex.Lex();
1725 return false;
1726}
1727
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001728/// ParseMetadataAttachment
1729/// ::= !dbg !42
1730bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1731 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1732
1733 std::string Name = Lex.getStrVal();
1734 Kind = M->getMDKindID(Name);
1735 Lex.Lex();
1736
1737 return ParseMDNode(MD);
1738}
1739
Chris Lattner5c427632009-12-30 05:31:19 +00001740/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001741/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001742bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001743 do {
1744 if (Lex.getKind() != lltok::MetadataVar)
1745 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001746
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001747 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001748 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001749 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001750 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001751
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001752 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001753 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001754 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001755
Chris Lattner596760d2009-12-29 21:25:40 +00001756 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001757 } while (EatIfPresent(lltok::comma));
1758 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001759}
1760
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001761/// ParseGlobalObjectMetadataAttachment
1762/// ::= !dbg !57
1763bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1764 unsigned MDK;
1765 MDNode *N;
1766 if (ParseMetadataAttachment(MDK, N))
1767 return true;
1768
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001769 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001770 return false;
1771}
1772
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001773/// ParseOptionalFunctionMetadata
1774/// ::= (!dbg !57)*
1775bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001776 while (Lex.getKind() == lltok::MetadataVar)
1777 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001778 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001779 return false;
1780}
1781
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782/// ParseOptionalAlignment
1783/// ::= /* empty */
1784/// ::= 'align' 4
1785bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1786 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001787 if (!EatIfPresent(lltok::kw_align))
1788 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001789 LocTy AlignLoc = Lex.getLoc();
1790 if (ParseUInt32(Alignment)) return true;
1791 if (!isPowerOf2_32(Alignment))
1792 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001793 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001794 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001795 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796}
1797
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001798/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001799/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001800/// ::= AttrKind '(' 4 ')'
1801///
1802/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1803bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1804 uint64_t &Bytes) {
1805 assert((AttrKind == lltok::kw_dereferenceable ||
1806 AttrKind == lltok::kw_dereferenceable_or_null) &&
1807 "contract!");
1808
Hal Finkelb0407ba2014-07-18 15:51:28 +00001809 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001810 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001811 return false;
1812 LocTy ParenLoc = Lex.getLoc();
1813 if (!EatIfPresent(lltok::lparen))
1814 return Error(ParenLoc, "expected '('");
1815 LocTy DerefLoc = Lex.getLoc();
1816 if (ParseUInt64(Bytes)) return true;
1817 ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::rparen))
1819 return Error(ParenLoc, "expected ')'");
1820 if (!Bytes)
1821 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1822 return false;
1823}
1824
Chris Lattnerb2f39502009-12-30 05:44:30 +00001825/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001826/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001827/// ::= ',' align 4
1828///
1829/// This returns with AteExtraComma set to true if it ate an excess comma at the
1830/// end.
1831bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1832 bool &AteExtraComma) {
1833 AteExtraComma = false;
1834 while (EatIfPresent(lltok::comma)) {
1835 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001836 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001837 AteExtraComma = true;
1838 return false;
1839 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001840
Chris Lattner95b0ff42010-04-23 00:50:50 +00001841 if (Lex.getKind() != lltok::kw_align)
1842 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001843
Chris Lattner95b0ff42010-04-23 00:50:50 +00001844 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001846
Devang Patelea8a4b92009-09-17 23:04:48 +00001847 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001848}
1849
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001850/// ParseOptionalCommaAddrSpace
1851/// ::=
1852/// ::= ',' addrspace(1)
1853///
1854/// This returns with AteExtraComma set to true if it ate an excess comma at the
1855/// end.
1856bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1857 LocTy &Loc,
1858 bool &AteExtraComma) {
1859 AteExtraComma = false;
1860 while (EatIfPresent(lltok::comma)) {
1861 // Metadata at the end is an early exit.
1862 if (Lex.getKind() == lltok::MetadataVar) {
1863 AteExtraComma = true;
1864 return false;
1865 }
1866
1867 Loc = Lex.getLoc();
1868 if (Lex.getKind() != lltok::kw_addrspace)
1869 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1870
1871 if (ParseOptionalAddrSpace(AddrSpace))
1872 return true;
1873 }
1874
1875 return false;
1876}
1877
George Burgess IV278199f2016-04-12 01:05:35 +00001878bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1879 Optional<unsigned> &HowManyArg) {
1880 Lex.Lex();
1881
1882 auto StartParen = Lex.getLoc();
1883 if (!EatIfPresent(lltok::lparen))
1884 return Error(StartParen, "expected '('");
1885
1886 if (ParseUInt32(BaseSizeArg))
1887 return true;
1888
1889 if (EatIfPresent(lltok::comma)) {
1890 auto HowManyAt = Lex.getLoc();
1891 unsigned HowMany;
1892 if (ParseUInt32(HowMany))
1893 return true;
1894 if (HowMany == BaseSizeArg)
1895 return Error(HowManyAt,
1896 "'allocsize' indices can't refer to the same parameter");
1897 HowManyArg = HowMany;
1898 } else
1899 HowManyArg = None;
1900
1901 auto EndParen = Lex.getLoc();
1902 if (!EatIfPresent(lltok::rparen))
1903 return Error(EndParen, "expected ')'");
1904 return false;
1905}
1906
Eli Friedmanfee02c62011-07-25 23:16:38 +00001907/// ParseScopeAndOrdering
1908/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1909/// else: ::=
1910///
1911/// This sets Scope and Ordering to the parsed values.
1912bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1913 AtomicOrdering &Ordering) {
1914 if (!isAtomic)
1915 return false;
1916
1917 Scope = CrossThread;
1918 if (EatIfPresent(lltok::kw_singlethread))
1919 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001920
1921 return ParseOrdering(Ordering);
1922}
1923
1924/// ParseOrdering
1925/// ::= AtomicOrdering
1926///
1927/// This sets Ordering to the parsed value.
1928bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001929 switch (Lex.getKind()) {
1930 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001931 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1932 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1933 // Not specified yet:
1934 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1935 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1936 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1937 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1938 case lltok::kw_seq_cst:
1939 Ordering = AtomicOrdering::SequentiallyConsistent;
1940 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001941 }
1942 Lex.Lex();
1943 return false;
1944}
1945
Charles Davisbe5557e2010-02-12 00:31:15 +00001946/// ParseOptionalStackAlignment
1947/// ::= /* empty */
1948/// ::= 'alignstack' '(' 4 ')'
1949bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1950 Alignment = 0;
1951 if (!EatIfPresent(lltok::kw_alignstack))
1952 return false;
1953 LocTy ParenLoc = Lex.getLoc();
1954 if (!EatIfPresent(lltok::lparen))
1955 return Error(ParenLoc, "expected '('");
1956 LocTy AlignLoc = Lex.getLoc();
1957 if (ParseUInt32(Alignment)) return true;
1958 ParenLoc = Lex.getLoc();
1959 if (!EatIfPresent(lltok::rparen))
1960 return Error(ParenLoc, "expected ')'");
1961 if (!isPowerOf2_32(Alignment))
1962 return Error(AlignLoc, "stack alignment is not a power of two");
1963 return false;
1964}
Devang Patelea8a4b92009-09-17 23:04:48 +00001965
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001966/// ParseIndexList - This parses the index list for an insert/extractvalue
1967/// instruction. This sets AteExtraComma in the case where we eat an extra
1968/// comma at the end of the line and find that it is followed by metadata.
1969/// Clients that don't allow metadata can call the version of this function that
1970/// only takes one argument.
1971///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001972/// ParseIndexList
1973/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001974///
1975bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1976 bool &AteExtraComma) {
1977 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001978
Chris Lattnerac161bf2009-01-02 07:01:27 +00001979 if (Lex.getKind() != lltok::comma)
1980 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Chris Lattner3822f632009-01-02 08:05:26 +00001982 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001983 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001984 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001985 AteExtraComma = true;
1986 return false;
1987 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001988 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001989 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 Indices.push_back(Idx);
1991 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001992
Chris Lattnerac161bf2009-01-02 07:01:27 +00001993 return false;
1994}
1995
1996//===----------------------------------------------------------------------===//
1997// Type Parsing.
1998//===----------------------------------------------------------------------===//
1999
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002000/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002001bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002003 switch (Lex.getKind()) {
2004 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002005 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002006 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002007 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002009 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002010 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002011 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 // Type ::= StructType
2013 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002014 return true;
2015 break;
2016 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018 Lex.Lex(); // eat the lsquare.
2019 if (ParseArrayVectorType(Result, false))
2020 return true;
2021 break;
2022 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002023 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002024 Lex.Lex();
2025 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002027 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029 } else if (ParseArrayVectorType(Result, true))
2030 return true;
2031 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 case lltok::LocalVar: {
2033 // Type ::= %foo
2034 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002036 // If the type hasn't been defined yet, create a forward definition and
2037 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002038 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002039 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002041 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002043 Lex.Lex();
2044 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002046
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 case lltok::LocalVarID: {
2048 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002050
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051 // If the type hasn't been defined yet, create a forward definition and
2052 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002053 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002054 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002055 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002056 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002057 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002058 Lex.Lex();
2059 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002060 }
2061 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002062
2063 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002064 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 switch (Lex.getKind()) {
2066 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002067 default:
2068 if (!AllowVoid && Result->isVoidTy())
2069 return Error(TypeLoc, "void type only allowed for function results");
2070 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002071
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002072 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002073 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076 if (Result->isVoidTy())
2077 return TokError("pointers to void are invalid - use i8* instead");
2078 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002079 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002080 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 Lex.Lex();
2082 break;
2083
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002084 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002086 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002088 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002089 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002090 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002091 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002092 unsigned AddrSpace;
2093 if (ParseOptionalAddrSpace(AddrSpace) ||
2094 ParseToken(lltok::star, "expected '*' in address space"))
2095 return true;
2096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002097 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 break;
2099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattnerac161bf2009-01-02 07:01:27 +00002101 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2102 case lltok::lparen:
2103 if (ParseFunctionType(Result))
2104 return true;
2105 break;
2106 }
2107 }
2108}
2109
2110/// ParseParameterList
2111/// ::= '(' ')'
2112/// ::= '(' Arg (',' Arg)* ')'
2113/// Arg
2114/// ::= Type OptionalAttributes Value OptionalAttributes
2115bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002116 PerFunctionState &PFS, bool IsMustTailCall,
2117 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 if (ParseToken(lltok::lparen, "expected '(' in call"))
2119 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121 while (Lex.getKind() != lltok::rparen) {
2122 // If this isn't the first argument, we need a comma.
2123 if (!ArgList.empty() &&
2124 ParseToken(lltok::comma, "expected ',' in argument list"))
2125 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002126
Reid Kleckner83498642014-08-26 00:33:28 +00002127 // Parse an ellipsis if this is a musttail call in a variadic function.
2128 if (Lex.getKind() == lltok::dotdotdot) {
2129 const char *Msg = "unexpected ellipsis in argument list for ";
2130 if (!IsMustTailCall)
2131 return TokError(Twine(Msg) + "non-musttail call");
2132 if (!InVarArgsFunc)
2133 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2134 Lex.Lex(); // Lex the '...', it is purely for readability.
2135 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2136 }
2137
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 // Parse the argument.
2139 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002140 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002141 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002142 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002143 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002145
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002146 if (ArgTy->isMetadataTy()) {
2147 if (ParseMetadataAsValue(V, PFS))
2148 return true;
2149 } else {
2150 // Otherwise, handle normal operands.
2151 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2152 return true;
2153 }
Reid Klecknerb5180542017-03-21 16:57:19 +00002154 ArgList.push_back(ParamInfo(
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002155 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002156 }
2157
Reid Kleckner83498642014-08-26 00:33:28 +00002158 if (IsMustTailCall && InVarArgsFunc)
2159 return TokError("expected '...' at end of argument list for musttail call "
2160 "in varargs function");
2161
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 Lex.Lex(); // Lex the ')'.
2163 return false;
2164}
2165
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002166/// ParseOptionalOperandBundles
2167/// ::= /*empty*/
2168/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2169///
2170/// OperandBundle
2171/// ::= bundle-tag '(' ')'
2172/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2173///
2174/// bundle-tag ::= String Constant
2175bool LLParser::ParseOptionalOperandBundles(
2176 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2177 LocTy BeginLoc = Lex.getLoc();
2178 if (!EatIfPresent(lltok::lsquare))
2179 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002180
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002181 while (Lex.getKind() != lltok::rsquare) {
2182 // If this isn't the first operand bundle, we need a comma.
2183 if (!BundleList.empty() &&
2184 ParseToken(lltok::comma, "expected ',' in input list"))
2185 return true;
2186
2187 std::string Tag;
2188 if (ParseStringConstant(Tag))
2189 return true;
2190
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002191 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2192 return true;
2193
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002194 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002195 while (Lex.getKind() != lltok::rparen) {
2196 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002197 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002198 ParseToken(lltok::comma, "expected ',' in input list"))
2199 return true;
2200
2201 Type *Ty = nullptr;
2202 Value *Input = nullptr;
2203 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2204 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002205 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002206 }
2207
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002208 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2209
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002210 Lex.Lex(); // Lex the ')'.
2211 }
2212
2213 if (BundleList.empty())
2214 return Error(BeginLoc, "operand bundle set must not be empty");
2215
2216 Lex.Lex(); // Lex the ']'.
2217 return false;
2218}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002219
Chris Lattner2ed06b42009-01-05 18:34:07 +00002220/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002221/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222/// ::= '(' ArgTypeListI ')'
2223/// ArgTypeListI
2224/// ::= /*empty*/
2225/// ::= '...'
2226/// ::= ArgTypeList ',' '...'
2227/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002228///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002229bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2230 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231 isVarArg = false;
2232 assert(Lex.getKind() == lltok::lparen);
2233 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002234
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 if (Lex.getKind() == lltok::rparen) {
2236 // empty
2237 } else if (Lex.getKind() == lltok::dotdotdot) {
2238 isVarArg = true;
2239 Lex.Lex();
2240 } else {
2241 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002242 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002243 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002245
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002246 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002247 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnerfdd87902009-10-05 05:54:46 +00002249 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002250 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Chris Lattnerdef19492011-06-17 06:36:20 +00002252 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 Name = Lex.getStrVal();
2254 Lex.Lex();
2255 }
Chris Lattner3822f632009-01-02 08:05:26 +00002256
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002257 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002258 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002259
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002260 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002261 AttributeSet::get(ArgTy->getContext(), Attrs),
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002262 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263
Chris Lattner3822f632009-01-02 08:05:26 +00002264 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002265 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002266 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002267 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 break;
2269 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 // Otherwise must be an argument type.
2272 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002273 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002274
Chris Lattnerfdd87902009-10-05 05:54:46 +00002275 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002276 return Error(TypeLoc, "argument can not have void type");
2277
Chris Lattnerdef19492011-06-17 06:36:20 +00002278 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279 Name = Lex.getStrVal();
2280 Lex.Lex();
2281 } else {
2282 Name = "";
2283 }
Chris Lattner3822f632009-01-02 08:05:26 +00002284
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002285 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002286 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002287
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002288 ArgList.emplace_back(TypeLoc, ArgTy,
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002289 AttributeSet::get(ArgTy->getContext(), Attrs),
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00002290 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002291 }
2292 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Chris Lattner3822f632009-01-02 08:05:26 +00002294 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002296
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297/// ParseFunctionType
2298/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002299bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002300 assert(Lex.getKind() == lltok::lparen);
2301
Chris Lattnerce473c72009-01-05 08:04:33 +00002302 if (!FunctionType::isValidReturnType(Result))
2303 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002309
Chris Lattnerac161bf2009-01-02 07:01:27 +00002310 // Reject names on the arguments lists.
2311 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2312 if (!ArgList[i].Name.empty())
2313 return Error(ArgList[i].Loc, "argument name invalid in function type");
Reid Klecknerc2cb5602017-04-12 00:38:00 +00002314 if (ArgList[i].Attrs.hasAttributes())
Chris Lattner6bc5c892011-06-17 17:37:13 +00002315 return Error(ArgList[i].Loc,
2316 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002318
Jay Foadb804a2b2011-07-12 14:06:48 +00002319 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002320 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002321 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002323 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002324 return false;
2325}
2326
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002327/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2328/// other structs.
2329bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2330 SmallVector<Type*, 8> Elts;
2331 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002333 Result = StructType::get(Context, Elts, Packed);
2334 return false;
2335}
2336
2337/// ParseStructDefinition - Parse a struct in a 'type' definition.
2338bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2339 std::pair<Type*, LocTy> &Entry,
2340 Type *&ResultTy) {
2341 // If the type was already defined, diagnose the redefinition.
2342 if (Entry.first && !Entry.second.isValid())
2343 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002344
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002345 // If we have opaque, just return without filling in the definition for the
2346 // struct. This counts as a definition as far as the .ll file goes.
2347 if (EatIfPresent(lltok::kw_opaque)) {
2348 // This type is being defined, so clear the location to indicate this.
2349 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002350
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002351 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002352 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002353 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002354 ResultTy = Entry.first;
2355 return false;
2356 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 // If the type starts with '<', then it is either a packed struct or a vector.
2359 bool isPacked = EatIfPresent(lltok::less);
2360
2361 // If we don't have a struct, then we have a random type alias, which we
2362 // accept for compatibility with old files. These types are not allowed to be
2363 // forward referenced and not allowed to be recursive.
2364 if (Lex.getKind() != lltok::lbrace) {
2365 if (Entry.first)
2366 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002367
Craig Topper2617dcc2014-04-15 06:32:26 +00002368 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002369 if (isPacked)
2370 return ParseArrayVectorType(ResultTy, true);
2371 return ParseType(ResultTy);
2372 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002373
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002374 // This type is being defined, so clear the location to indicate this.
2375 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002376
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002377 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002378 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002379 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002380
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002381 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002382
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002383 SmallVector<Type*, 8> Body;
2384 if (ParseStructBody(Body) ||
2385 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2386 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002387
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002388 STy->setBody(Body, isPacked);
2389 ResultTy = STy;
2390 return false;
2391}
2392
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002394/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002395/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002398/// ::= '<' '{' Type (',' Type)* '}' '>'
2399bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002400 assert(Lex.getKind() == lltok::lbrace);
2401 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002403 // Handle the empty struct.
2404 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406
Chris Lattnerf880ca22009-03-09 04:49:14 +00002407 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002408 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002409 if (ParseType(Ty)) return true;
2410 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002411
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002412 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002413 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002414
Chris Lattner3822f632009-01-02 08:05:26 +00002415 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002416 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002419 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002420 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002422 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002423 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002424
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002425 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002426}
2427
2428/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2429/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002431/// ::= '[' APSINTVAL 'x' Types ']'
2432/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002433bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002434 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2435 Lex.getAPSIntVal().getBitWidth() > 64)
2436 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 LocTy SizeLoc = Lex.getLoc();
2439 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002440 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441
Chris Lattner3822f632009-01-02 08:05:26 +00002442 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2443 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444
2445 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002446 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002447 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002448
Chris Lattner3822f632009-01-02 08:05:26 +00002449 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2450 "expected end of sequential type"))
2451 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Chris Lattnerac161bf2009-01-02 07:01:27 +00002453 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002454 if (Size == 0)
2455 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 if ((unsigned)Size != Size)
2457 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002458 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002459 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002460 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002462 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002463 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002464 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465 }
2466 return false;
2467}
2468
2469//===----------------------------------------------------------------------===//
2470// Function Semantic Analysis.
2471//===----------------------------------------------------------------------===//
2472
Chris Lattner3432c622009-10-28 03:39:23 +00002473LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2474 int functionNumber)
2475 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002476
2477 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002478 for (Argument &A : F.args())
2479 if (!A.hasName())
2480 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481}
2482
2483LLParser::PerFunctionState::~PerFunctionState() {
2484 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485
David Blaikie9ebdc692015-09-21 21:07:50 +00002486 for (const auto &P : ForwardRefVals) {
2487 if (isa<BasicBlock>(P.second.first))
2488 continue;
2489 P.second.first->replaceAllUsesWith(
2490 UndefValue::get(P.second.first->getType()));
2491 delete P.second.first;
2492 }
2493
2494 for (const auto &P : ForwardRefValIDs) {
2495 if (isa<BasicBlock>(P.second.first))
2496 continue;
2497 P.second.first->replaceAllUsesWith(
2498 UndefValue::get(P.second.first->getType()));
2499 delete P.second.first;
2500 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002501}
2502
Chris Lattner3432c622009-10-28 03:39:23 +00002503bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 if (!ForwardRefVals.empty())
2505 return P.Error(ForwardRefVals.begin()->second.second,
2506 "use of undefined value '%" + ForwardRefVals.begin()->first +
2507 "'");
2508 if (!ForwardRefValIDs.empty())
2509 return P.Error(ForwardRefValIDs.begin()->second.second,
2510 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002511 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 return false;
2513}
2514
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515/// GetVal - Get a value with the specified name or ID, creating a
2516/// forward reference record if needed. This can return null if the value
2517/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002518Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002519 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002521 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002522
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 // If this is a forward reference for the value, see if we already created a
2524 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002525 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002526 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002527 if (I != ForwardRefVals.end())
2528 Val = I->second.first;
2529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Chris Lattnerac161bf2009-01-02 07:01:27 +00002531 // If we have the value in the symbol table or fwd-ref table, return it.
2532 if (Val) {
2533 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002534 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002535 P.Error(Loc, "'%" + Name + "' is not a basic block");
2536 else
2537 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002538 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002539 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002541
Chris Lattnerac161bf2009-01-02 07:01:27 +00002542 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002543 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002545 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002547
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 // Otherwise, create a new forward reference for this value and remember it.
2549 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002550 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002551 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002552 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002553 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2557 return FwdVal;
2558}
2559
David Majnemer8a1c45d2015-12-12 05:38:55 +00002560Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002562 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattnerac161bf2009-01-02 07:01:27 +00002564 // If this is a forward reference for the value, see if we already created a
2565 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002566 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002567 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 if (I != ForwardRefValIDs.end())
2569 Val = I->second.first;
2570 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002571
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 // If we have the value in the symbol table or fwd-ref table, return it.
2573 if (Val) {
2574 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002575 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002576 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002578 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002579 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002580 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002582
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002583 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002584 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002585 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587
Chris Lattnerac161bf2009-01-02 07:01:27 +00002588 // Otherwise, create a new forward reference for this value and remember it.
2589 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002590 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002591 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002592 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002593 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Chris Lattnerac161bf2009-01-02 07:01:27 +00002596 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2597 return FwdVal;
2598}
2599
2600/// SetInstName - After an instruction is parsed and inserted into its
2601/// basic block, this installs its name.
2602bool LLParser::PerFunctionState::SetInstName(int NameID,
2603 const std::string &NameStr,
2604 LocTy NameLoc, Instruction *Inst) {
2605 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002606 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002607 if (NameID != -1 || !NameStr.empty())
2608 return P.Error(NameLoc, "instructions returning void cannot have a name");
2609 return false;
2610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002611
Chris Lattnerac161bf2009-01-02 07:01:27 +00002612 // If this was a numbered instruction, verify that the instruction is the
2613 // expected value and resolve any forward references.
2614 if (NameStr.empty()) {
2615 // If neither a name nor an ID was specified, just use the next ID.
2616 if (NameID == -1)
2617 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Chris Lattnerac161bf2009-01-02 07:01:27 +00002619 if (unsigned(NameID) != NumberedVals.size())
2620 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002621 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002622
David Blaikie9ebdc692015-09-21 21:07:50 +00002623 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002624 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002625 Value *Sentinel = FI->second.first;
2626 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002627 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002628 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002629
2630 Sentinel->replaceAllUsesWith(Inst);
2631 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 ForwardRefValIDs.erase(FI);
2633 }
2634
2635 NumberedVals.push_back(Inst);
2636 return false;
2637 }
2638
2639 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002640 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002642 Value *Sentinel = FI->second.first;
2643 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002644 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002645 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002646
2647 Sentinel->replaceAllUsesWith(Inst);
2648 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002649 ForwardRefVals.erase(FI);
2650 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002651
Chris Lattnerac161bf2009-01-02 07:01:27 +00002652 // Set the name on the instruction.
2653 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002655 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 NameStr + "'");
2658 return false;
2659}
2660
2661/// GetBB - Get a basic block with the specified name or ID, creating a
2662/// forward reference record if needed.
2663BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2664 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002665 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2666 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002667}
2668
2669BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002670 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2671 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002672}
2673
2674/// DefineBB - Define the specified basic block, which is either named or
2675/// unnamed. If there is an error, this returns null otherwise it returns
2676/// the block being defined.
2677BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2678 LocTy Loc) {
2679 BasicBlock *BB;
2680 if (Name.empty())
2681 BB = GetBB(NumberedVals.size(), Loc);
2682 else
2683 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002684 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnerac161bf2009-01-02 07:01:27 +00002686 // Move the block to the end of the function. Forward ref'd blocks are
2687 // inserted wherever they happen to be referenced.
2688 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002689
Chris Lattnerac161bf2009-01-02 07:01:27 +00002690 // Remove the block from forward ref sets.
2691 if (Name.empty()) {
2692 ForwardRefValIDs.erase(NumberedVals.size());
2693 NumberedVals.push_back(BB);
2694 } else {
2695 // BB forward references are already in the function symbol table.
2696 ForwardRefVals.erase(Name);
2697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002698
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 return BB;
2700}
2701
2702//===----------------------------------------------------------------------===//
2703// Constants.
2704//===----------------------------------------------------------------------===//
2705
2706/// ParseValID - Parse an abstract value that doesn't necessarily have a
2707/// type implied. For example, if we parse "4" we don't know what integer type
2708/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002709/// sanity. PFS is used to convert function-local operands of metadata (since
2710/// metadata operands are not just parsed here but also converted to values).
2711/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002712bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 ID.Loc = Lex.getLoc();
2714 switch (Lex.getKind()) {
2715 default: return TokError("expected value token");
2716 case lltok::GlobalID: // @42
2717 ID.UIntVal = Lex.getUIntVal();
2718 ID.Kind = ValID::t_GlobalID;
2719 break;
2720 case lltok::GlobalVar: // @foo
2721 ID.StrVal = Lex.getStrVal();
2722 ID.Kind = ValID::t_GlobalName;
2723 break;
2724 case lltok::LocalVarID: // %42
2725 ID.UIntVal = Lex.getUIntVal();
2726 ID.Kind = ValID::t_LocalID;
2727 break;
2728 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002729 ID.StrVal = Lex.getStrVal();
2730 ID.Kind = ValID::t_LocalName;
2731 break;
2732 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002733 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 ID.Kind = ValID::t_APSInt;
2735 break;
2736 case lltok::APFloat:
2737 ID.APFloatVal = Lex.getAPFloatVal();
2738 ID.Kind = ValID::t_APFloat;
2739 break;
2740 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002741 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 ID.Kind = ValID::t_Constant;
2743 break;
2744 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002745 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 ID.Kind = ValID::t_Constant;
2747 break;
2748 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2749 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2750 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002751 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002752
Chris Lattnerac161bf2009-01-02 07:01:27 +00002753 case lltok::lbrace: {
2754 // ValID ::= '{' ConstVector '}'
2755 Lex.Lex();
2756 SmallVector<Constant*, 16> Elts;
2757 if (ParseGlobalValueVector(Elts) ||
2758 ParseToken(lltok::rbrace, "expected end of struct constant"))
2759 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002760
David Blaikieadbda4b2015-08-03 20:08:41 +00002761 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002762 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002763 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2764 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002765 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 return false;
2767 }
2768 case lltok::less: {
2769 // ValID ::= '<' ConstVector '>' --> Vector.
2770 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2771 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002772 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002773
Chris Lattnerac161bf2009-01-02 07:01:27 +00002774 SmallVector<Constant*, 16> Elts;
2775 LocTy FirstEltLoc = Lex.getLoc();
2776 if (ParseGlobalValueVector(Elts) ||
2777 (isPackedStruct &&
2778 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2779 ParseToken(lltok::greater, "expected end of constant"))
2780 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002783 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2784 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2785 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002786 ID.UIntVal = Elts.size();
2787 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 return false;
2789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790
Chris Lattnerac161bf2009-01-02 07:01:27 +00002791 if (Elts.empty())
2792 return Error(ID.Loc, "constant vector must not be empty");
2793
Duncan Sands9dff9be2010-02-15 16:12:20 +00002794 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002795 !Elts[0]->getType()->isFloatingPointTy() &&
2796 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002797 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002798 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002799
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 // Verify that all the vector elements have the same type.
2801 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2802 if (Elts[i]->getType() != Elts[0]->getType())
2803 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002804 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002805 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002806
Chris Lattner69229312011-02-15 00:14:00 +00002807 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 ID.Kind = ValID::t_Constant;
2809 return false;
2810 }
2811 case lltok::lsquare: { // Array Constant
2812 Lex.Lex();
2813 SmallVector<Constant*, 16> Elts;
2814 LocTy FirstEltLoc = Lex.getLoc();
2815 if (ParseGlobalValueVector(Elts) ||
2816 ParseToken(lltok::rsquare, "expected end of array constant"))
2817 return true;
2818
2819 // Handle empty element.
2820 if (Elts.empty()) {
2821 // Use undef instead of an array because it's inconvenient to determine
2822 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002823 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 return false;
2825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnerac161bf2009-01-02 07:01:27 +00002827 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002828 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002829 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002830
Owen Anderson4056ca92009-07-29 22:17:13 +00002831 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002834 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002835 if (Elts[i]->getType() != Elts[0]->getType())
2836 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002837 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002838 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Jay Foad83be3612011-06-22 09:24:39 +00002841 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002842 ID.Kind = ValID::t_Constant;
2843 return false;
2844 }
2845 case lltok::kw_c: // c "foo"
2846 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002847 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2848 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002849 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2850 ID.Kind = ValID::t_Constant;
2851 return false;
2852
2853 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002854 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2855 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002856 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 Lex.Lex();
2858 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002859 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002860 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002861 ParseStringConstant(ID.StrVal) ||
2862 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002863 ParseToken(lltok::StringConstant, "expected constraint string"))
2864 return true;
2865 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002866 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002867 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002868 ID.Kind = ValID::t_InlineAsm;
2869 return false;
2870 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002871
Chris Lattner3432c622009-10-28 03:39:23 +00002872 case lltok::kw_blockaddress: {
2873 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2874 Lex.Lex();
2875
2876 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002877
Chris Lattner3432c622009-10-28 03:39:23 +00002878 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2879 ParseValID(Fn) ||
2880 ParseToken(lltok::comma, "expected comma in block address expression")||
2881 ParseValID(Label) ||
2882 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2883 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002884
Chris Lattner3432c622009-10-28 03:39:23 +00002885 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2886 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002887 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002888 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002889
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002890 // Try to find the function (but skip it if it's forward-referenced).
2891 GlobalValue *GV = nullptr;
2892 if (Fn.Kind == ValID::t_GlobalID) {
2893 if (Fn.UIntVal < NumberedVals.size())
2894 GV = NumberedVals[Fn.UIntVal];
2895 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2896 GV = M->getNamedValue(Fn.StrVal);
2897 }
2898 Function *F = nullptr;
2899 if (GV) {
2900 // Confirm that it's actually a function with a definition.
2901 if (!isa<Function>(GV))
2902 return Error(Fn.Loc, "expected function name in blockaddress");
2903 F = cast<Function>(GV);
2904 if (F->isDeclaration())
2905 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2906 }
2907
2908 if (!F) {
2909 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002910 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002911 ForwardRefBlockAddresses.insert(std::make_pair(
2912 std::move(Fn),
2913 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002914 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2915 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002916 if (!FwdRef)
2917 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2918 GlobalValue::InternalLinkage, nullptr, "");
2919 ID.ConstantVal = FwdRef;
2920 ID.Kind = ValID::t_Constant;
2921 return false;
2922 }
2923
2924 // We found the function; now find the basic block. Don't use PFS, since we
2925 // might be inside a constant expression.
2926 BasicBlock *BB;
2927 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2928 if (Label.Kind == ValID::t_LocalID)
2929 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2930 else
2931 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2932 if (!BB)
2933 return Error(Label.Loc, "referenced value is not a basic block");
2934 } else {
2935 if (Label.Kind == ValID::t_LocalID)
2936 return Error(Label.Loc, "cannot take address of numeric label after "
2937 "the function is defined");
2938 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002939 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002940 if (!BB)
2941 return Error(Label.Loc, "referenced value is not a basic block");
2942 }
2943
2944 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002945 ID.Kind = ValID::t_Constant;
2946 return false;
2947 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002948
Chris Lattnerac161bf2009-01-02 07:01:27 +00002949 case lltok::kw_trunc:
2950 case lltok::kw_zext:
2951 case lltok::kw_sext:
2952 case lltok::kw_fptrunc:
2953 case lltok::kw_fpext:
2954 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002955 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002956 case lltok::kw_uitofp:
2957 case lltok::kw_sitofp:
2958 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002960 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002963 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002964 Constant *SrcVal;
2965 Lex.Lex();
2966 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2967 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002968 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002969 ParseType(DestTy) ||
2970 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2971 return true;
2972 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2973 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002974 getTypeString(SrcVal->getType()) + "' to '" +
2975 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002976 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002977 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 ID.Kind = ValID::t_Constant;
2979 return false;
2980 }
2981 case lltok::kw_extractvalue: {
2982 Lex.Lex();
2983 Constant *Val;
2984 SmallVector<unsigned, 4> Indices;
2985 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2986 ParseGlobalTypeAndValue(Val) ||
2987 ParseIndexList(Indices) ||
2988 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2989 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002990
Chris Lattner392be582010-02-12 20:49:41 +00002991 if (!Val->getType()->isAggregateType())
2992 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002993 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002994 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002995 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002996 ID.Kind = ValID::t_Constant;
2997 return false;
2998 }
2999 case lltok::kw_insertvalue: {
3000 Lex.Lex();
3001 Constant *Val0, *Val1;
3002 SmallVector<unsigned, 4> Indices;
3003 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3004 ParseGlobalTypeAndValue(Val0) ||
3005 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3006 ParseGlobalTypeAndValue(Val1) ||
3007 ParseIndexList(Indices) ||
3008 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3009 return true;
Chris Lattner392be582010-02-12 20:49:41 +00003010 if (!Val0->getType()->isAggregateType())
3011 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00003012 Type *IndexedType =
3013 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3014 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003015 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003016 if (IndexedType != Val1->getType())
3017 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3018 getTypeString(Val1->getType()) +
3019 "' instead of '" + getTypeString(IndexedType) +
3020 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003021 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 ID.Kind = ValID::t_Constant;
3023 return false;
3024 }
3025 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003026 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 unsigned PredVal, Opc = Lex.getUIntVal();
3028 Constant *Val0, *Val1;
3029 Lex.Lex();
3030 if (ParseCmpPredicate(PredVal, Opc) ||
3031 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3032 ParseGlobalTypeAndValue(Val0) ||
3033 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3034 ParseGlobalTypeAndValue(Val1) ||
3035 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3036 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 if (Val0->getType() != Val1->getType())
3039 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003040
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Chris Lattnerac161bf2009-01-02 07:01:27 +00003043 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003044 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003046 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003047 } else {
3048 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003049 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003050 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003051 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003052 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003053 }
3054 ID.Kind = ValID::t_Constant;
3055 return false;
3056 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003057
Chris Lattnerac161bf2009-01-02 07:01:27 +00003058 // Binary Operators.
3059 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003060 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003062 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003063 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003064 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 case lltok::kw_udiv:
3066 case lltok::kw_sdiv:
3067 case lltok::kw_fdiv:
3068 case lltok::kw_urem:
3069 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003070 case lltok::kw_frem:
3071 case lltok::kw_shl:
3072 case lltok::kw_lshr:
3073 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003074 bool NUW = false;
3075 bool NSW = false;
3076 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003077 unsigned Opc = Lex.getUIntVal();
3078 Constant *Val0, *Val1;
3079 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003080 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003081 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3082 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003083 if (EatIfPresent(lltok::kw_nuw))
3084 NUW = true;
3085 if (EatIfPresent(lltok::kw_nsw)) {
3086 NSW = true;
3087 if (EatIfPresent(lltok::kw_nuw))
3088 NUW = true;
3089 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003090 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3091 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003092 if (EatIfPresent(lltok::kw_exact))
3093 Exact = true;
3094 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003095 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3096 ParseGlobalTypeAndValue(Val0) ||
3097 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3098 ParseGlobalTypeAndValue(Val1) ||
3099 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3100 return true;
3101 if (Val0->getType() != Val1->getType())
3102 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003103 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003104 if (NUW)
3105 return Error(ModifierLoc, "nuw only applies to integer operations");
3106 if (NSW)
3107 return Error(ModifierLoc, "nsw only applies to integer operations");
3108 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003109 // Check that the type is valid for the operator.
3110 switch (Opc) {
3111 case Instruction::Add:
3112 case Instruction::Sub:
3113 case Instruction::Mul:
3114 case Instruction::UDiv:
3115 case Instruction::SDiv:
3116 case Instruction::URem:
3117 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003118 case Instruction::Shl:
3119 case Instruction::AShr:
3120 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003121 if (!Val0->getType()->isIntOrIntVectorTy())
3122 return Error(ID.Loc, "constexpr requires integer operands");
3123 break;
3124 case Instruction::FAdd:
3125 case Instruction::FSub:
3126 case Instruction::FMul:
3127 case Instruction::FDiv:
3128 case Instruction::FRem:
3129 if (!Val0->getType()->isFPOrFPVectorTy())
3130 return Error(ID.Loc, "constexpr requires fp operands");
3131 break;
3132 default: llvm_unreachable("Unknown binary operator!");
3133 }
Dan Gohman1b849082009-09-07 23:54:19 +00003134 unsigned Flags = 0;
3135 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3136 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003137 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003138 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003139 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003140 ID.Kind = ValID::t_Constant;
3141 return false;
3142 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003143
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003145 case lltok::kw_and:
3146 case lltok::kw_or:
3147 case lltok::kw_xor: {
3148 unsigned Opc = Lex.getUIntVal();
3149 Constant *Val0, *Val1;
3150 Lex.Lex();
3151 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3152 ParseGlobalTypeAndValue(Val0) ||
3153 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3154 ParseGlobalTypeAndValue(Val1) ||
3155 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3156 return true;
3157 if (Val0->getType() != Val1->getType())
3158 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003159 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 return Error(ID.Loc,
3161 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003162 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003163 ID.Kind = ValID::t_Constant;
3164 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003165 }
3166
Chris Lattnerac161bf2009-01-02 07:01:27 +00003167 case lltok::kw_getelementptr:
3168 case lltok::kw_shufflevector:
3169 case lltok::kw_insertelement:
3170 case lltok::kw_extractelement:
3171 case lltok::kw_select: {
3172 unsigned Opc = Lex.getUIntVal();
3173 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003174 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003175 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003176 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003177
Dan Gohman1639c392009-07-27 21:53:46 +00003178 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003179 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003180
3181 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3182 return true;
3183
3184 LocTy ExplicitTypeLoc = Lex.getLoc();
3185 if (Opc == Instruction::GetElementPtr) {
3186 if (ParseType(Ty) ||
3187 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3188 return true;
3189 }
3190
Peter Collingbourned93620b2016-11-10 22:34:55 +00003191 Optional<unsigned> InRangeOp;
3192 if (ParseGlobalValueVector(
3193 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003194 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3195 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003196
Chris Lattnerac161bf2009-01-02 07:01:27 +00003197 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003198 if (Elts.size() == 0 ||
3199 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003200 return Error(ID.Loc, "base of getelementptr must be a pointer");
3201
3202 Type *BaseType = Elts[0]->getType();
3203 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003204 if (Ty != BasePointerType->getElementType())
3205 return Error(
3206 ExplicitTypeLoc,
3207 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003208
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003209 unsigned GEPWidth =
3210 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3211
Jay Foaded8db7d2011-07-21 14:31:17 +00003212 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003213 for (Constant *Val : Indices) {
3214 Type *ValTy = Val->getType();
3215 if (!ValTy->getScalarType()->isIntegerTy())
3216 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003217 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003218 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003219 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003220 return Error(
3221 ID.Loc,
3222 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003223 // GEPWidth may have been unknown because the base is a scalar,
3224 // but it is known now.
3225 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003226 }
3227 }
3228
Craig Toppere3dcce92015-08-01 22:20:21 +00003229 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003230 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003231 return Error(ID.Loc, "base element of getelementptr must be sized");
3232
David Blaikie4a2e73b2015-04-02 18:55:32 +00003233 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003234 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003235
3236 if (InRangeOp) {
3237 if (*InRangeOp == 0)
3238 return Error(ID.Loc,
3239 "inrange keyword may not appear on pointer operand");
3240 --*InRangeOp;
3241 }
3242
3243 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3244 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003245 } else if (Opc == Instruction::Select) {
3246 if (Elts.size() != 3)
3247 return Error(ID.Loc, "expected three operands to select");
3248 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3249 Elts[2]))
3250 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003251 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003252 } else if (Opc == Instruction::ShuffleVector) {
3253 if (Elts.size() != 3)
3254 return Error(ID.Loc, "expected three operands to shufflevector");
3255 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3256 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003257 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003258 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003259 } else if (Opc == Instruction::ExtractElement) {
3260 if (Elts.size() != 2)
3261 return Error(ID.Loc, "expected two operands to extractelement");
3262 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3263 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003264 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003265 } else {
3266 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3267 if (Elts.size() != 3)
3268 return Error(ID.Loc, "expected three operands to insertelement");
3269 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3270 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003271 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003272 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003273 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003274
Chris Lattnerac161bf2009-01-02 07:01:27 +00003275 ID.Kind = ValID::t_Constant;
3276 return false;
3277 }
3278 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003279
Chris Lattnerac161bf2009-01-02 07:01:27 +00003280 Lex.Lex();
3281 return false;
3282}
3283
3284/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003285bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003286 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003287 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003288 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003289 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003290 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003291 if (V && !(C = dyn_cast<Constant>(V)))
3292 return Error(ID.Loc, "global values must be constants");
3293 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003294}
3295
Victor Hernandez9d75c962010-01-11 22:31:58 +00003296bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003297 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003298 return ParseType(Ty) ||
3299 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003300}
3301
Rafael Espindola83a362c2015-01-06 22:55:16 +00003302bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003303 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003304
3305 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003306 if (!EatIfPresent(lltok::kw_comdat))
3307 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003308
3309 if (EatIfPresent(lltok::lparen)) {
3310 if (Lex.getKind() != lltok::ComdatVar)
3311 return TokError("expected comdat variable");
3312 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3313 Lex.Lex();
3314 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3315 return true;
3316 } else {
3317 if (GlobalName.empty())
3318 return TokError("comdat cannot be unnamed");
3319 C = getComdat(GlobalName, KwLoc);
3320 }
3321
David Majnemerdad0a642014-06-27 18:19:56 +00003322 return false;
3323}
3324
Victor Hernandez9d75c962010-01-11 22:31:58 +00003325/// ParseGlobalValueVector
3326/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003327/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3328bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3329 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003330 // Empty list.
3331 if (Lex.getKind() == lltok::rbrace ||
3332 Lex.getKind() == lltok::rsquare ||
3333 Lex.getKind() == lltok::greater ||
3334 Lex.getKind() == lltok::rparen)
3335 return false;
3336
Peter Collingbourned93620b2016-11-10 22:34:55 +00003337 do {
3338 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3339 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003340
Peter Collingbourned93620b2016-11-10 22:34:55 +00003341 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003342 if (ParseGlobalTypeAndValue(C)) return true;
3343 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003344 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003345
3346 return false;
3347}
3348
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003349bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003350 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003351 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003352 return true;
3353
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003354 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003355 return false;
3356}
3357
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003358/// MDNode:
3359/// ::= !{ ... }
3360/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003361/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003362bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003363 if (Lex.getKind() == lltok::MetadataVar)
3364 return ParseSpecializedMDNode(N);
3365
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003366 return ParseToken(lltok::exclaim, "expected '!' here") ||
3367 ParseMDNodeTail(N);
3368}
3369
3370bool LLParser::ParseMDNodeTail(MDNode *&N) {
3371 // !{ ... }
3372 if (Lex.getKind() == lltok::lbrace)
3373 return ParseMDTuple(N);
3374
3375 // !42
3376 return ParseMDNodeID(N);
3377}
3378
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003379namespace {
3380
3381/// Structure to represent an optional metadata field.
3382template <class FieldTy> struct MDFieldImpl {
3383 typedef MDFieldImpl ImplTy;
3384 FieldTy Val;
3385 bool Seen;
3386
3387 void assign(FieldTy Val) {
3388 Seen = true;
3389 this->Val = std::move(Val);
3390 }
3391
3392 explicit MDFieldImpl(FieldTy Default)
3393 : Val(std::move(Default)), Seen(false) {}
3394};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003395
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003396struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3397 uint64_t Max;
3398
3399 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3400 : ImplTy(Default), Max(Max) {}
3401};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003402
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003403struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003404 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003405};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003406
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003407struct ColumnField : public MDUnsignedField {
3408 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3409};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003410
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003411struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003412 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003413 DwarfTagField(dwarf::Tag DefaultTag)
3414 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003415};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003416
Amjad Abouda9bcf162015-12-10 12:56:35 +00003417struct DwarfMacinfoTypeField : public MDUnsignedField {
3418 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3419 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3420 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3421};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003422
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003423struct DwarfAttEncodingField : public MDUnsignedField {
3424 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3425};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003426
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003427struct DwarfVirtualityField : public MDUnsignedField {
3428 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3429};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003430
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003431struct DwarfLangField : public MDUnsignedField {
3432 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3433};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003434
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003435struct DwarfCCField : public MDUnsignedField {
3436 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3437};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003438
Adrian Prantlb939a252016-03-31 23:56:58 +00003439struct EmissionKindField : public MDUnsignedField {
3440 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3441};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003442
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003443struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3444 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003445};
3446
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003447struct MDSignedField : public MDFieldImpl<int64_t> {
3448 int64_t Min;
3449 int64_t Max;
3450
3451 MDSignedField(int64_t Default = 0)
3452 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3453 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3454 : ImplTy(Default), Min(Min), Max(Max) {}
3455};
3456
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003457struct MDBoolField : public MDFieldImpl<bool> {
3458 MDBoolField(bool Default = false) : ImplTy(Default) {}
3459};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003460
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003461struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003462 bool AllowNull;
3463
3464 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003465};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003466
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003467struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3468 MDConstant() : ImplTy(nullptr) {}
3469};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003470
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003471struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003472 bool AllowEmpty;
3473 MDStringField(bool AllowEmpty = true)
3474 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003475};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003476
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003477struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3478 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3479};
3480
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003481struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3482 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3483 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3484};
3485
Eugene Zelenko1804a772016-08-25 00:45:04 +00003486} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003487
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003488namespace llvm {
3489
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003490template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003491bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003492 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003493 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3494 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003495
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003496 auto &U = Lex.getAPSIntVal();
3497 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003498 return TokError("value for '" + Name + "' too large, limit is " +
3499 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003500 Result.assign(U.getZExtValue());
3501 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003502 Lex.Lex();
3503 return false;
3504}
3505
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003506template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003507bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3508 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3509}
3510template <>
3511bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3512 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3513}
3514
3515template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003516bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3517 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003518 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003519
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003520 if (Lex.getKind() != lltok::DwarfTag)
3521 return TokError("expected DWARF tag");
3522
3523 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3524 if (Tag == dwarf::DW_TAG_invalid)
3525 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003526 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003527
3528 Result.assign(Tag);
3529 Lex.Lex();
3530 return false;
3531}
3532
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003533template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003534bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003535 DwarfMacinfoTypeField &Result) {
3536 if (Lex.getKind() == lltok::APSInt)
3537 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3538
3539 if (Lex.getKind() != lltok::DwarfMacinfo)
3540 return TokError("expected DWARF macinfo type");
3541
3542 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3543 if (Macinfo == dwarf::DW_MACINFO_invalid)
3544 return TokError(
3545 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3546 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3547
3548 Result.assign(Macinfo);
3549 Lex.Lex();
3550 return false;
3551}
3552
3553template <>
3554bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003555 DwarfVirtualityField &Result) {
3556 if (Lex.getKind() == lltok::APSInt)
3557 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3558
3559 if (Lex.getKind() != lltok::DwarfVirtuality)
3560 return TokError("expected DWARF virtuality code");
3561
3562 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003563 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003564 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3565 Lex.getStrVal() + "'");
3566 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3567 Result.assign(Virtuality);
3568 Lex.Lex();
3569 return false;
3570}
3571
3572template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003573bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3574 if (Lex.getKind() == lltok::APSInt)
3575 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3576
3577 if (Lex.getKind() != lltok::DwarfLang)
3578 return TokError("expected DWARF language");
3579
3580 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3581 if (!Lang)
3582 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3583 "'");
3584 assert(Lang <= Result.Max && "Expected valid DWARF language");
3585 Result.assign(Lang);
3586 Lex.Lex();
3587 return false;
3588}
3589
3590template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003591bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3592 if (Lex.getKind() == lltok::APSInt)
3593 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3594
3595 if (Lex.getKind() != lltok::DwarfCC)
3596 return TokError("expected DWARF calling convention");
3597
3598 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3599 if (!CC)
3600 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3601 "'");
3602 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3603 Result.assign(CC);
3604 Lex.Lex();
3605 return false;
3606}
3607
3608template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003609bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3610 if (Lex.getKind() == lltok::APSInt)
3611 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3612
3613 if (Lex.getKind() != lltok::EmissionKind)
3614 return TokError("expected emission kind");
3615
3616 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3617 if (!Kind)
3618 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3619 "'");
3620 assert(*Kind <= Result.Max && "Expected valid emission kind");
3621 Result.assign(*Kind);
3622 Lex.Lex();
3623 return false;
3624}
3625
3626template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003627bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003628 DwarfAttEncodingField &Result) {
3629 if (Lex.getKind() == lltok::APSInt)
3630 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3631
3632 if (Lex.getKind() != lltok::DwarfAttEncoding)
3633 return TokError("expected DWARF type attribute encoding");
3634
3635 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3636 if (!Encoding)
3637 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3638 Lex.getStrVal() + "'");
3639 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3640 Result.assign(Encoding);
3641 Lex.Lex();
3642 return false;
3643}
3644
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003645/// DIFlagField
3646/// ::= uint32
3647/// ::= DIFlagVector
3648/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3649template <>
3650bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003651
3652 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003653 auto parseFlag = [&](DINode::DIFlags &Val) {
3654 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3655 uint32_t TempVal = static_cast<uint32_t>(Val);
3656 bool Res = ParseUInt32(TempVal);
3657 Val = static_cast<DINode::DIFlags>(TempVal);
3658 return Res;
3659 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003660
3661 if (Lex.getKind() != lltok::DIFlag)
3662 return TokError("expected debug info flag");
3663
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003664 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003665 if (!Val)
3666 return TokError(Twine("invalid debug info flag flag '") +
3667 Lex.getStrVal() + "'");
3668 Lex.Lex();
3669 return false;
3670 };
3671
3672 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003673 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003674 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003675 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003676 if (parseFlag(Val))
3677 return true;
3678 Combined |= Val;
3679 } while (EatIfPresent(lltok::bar));
3680
3681 Result.assign(Combined);
3682 return false;
3683}
3684
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003685template <>
3686bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003687 MDSignedField &Result) {
3688 if (Lex.getKind() != lltok::APSInt)
3689 return TokError("expected signed integer");
3690
3691 auto &S = Lex.getAPSIntVal();
3692 if (S < Result.Min)
3693 return TokError("value for '" + Name + "' too small, limit is " +
3694 Twine(Result.Min));
3695 if (S > Result.Max)
3696 return TokError("value for '" + Name + "' too large, limit is " +
3697 Twine(Result.Max));
3698 Result.assign(S.getExtValue());
3699 assert(Result.Val >= Result.Min && "Expected value in range");
3700 assert(Result.Val <= Result.Max && "Expected value in range");
3701 Lex.Lex();
3702 return false;
3703}
3704
3705template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003706bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3707 switch (Lex.getKind()) {
3708 default:
3709 return TokError("expected 'true' or 'false'");
3710 case lltok::kw_true:
3711 Result.assign(true);
3712 break;
3713 case lltok::kw_false:
3714 Result.assign(false);
3715 break;
3716 }
3717 Lex.Lex();
3718 return false;
3719}
3720
3721template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003722bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003723 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003724 if (!Result.AllowNull)
3725 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003726 Lex.Lex();
3727 Result.assign(nullptr);
3728 return false;
3729 }
3730
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003731 Metadata *MD;
3732 if (ParseMetadata(MD, nullptr))
3733 return true;
3734
3735 Result.assign(MD);
3736 return false;
3737}
3738
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003739template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003740bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003741 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003742 std::string S;
3743 if (ParseStringConstant(S))
3744 return true;
3745
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003746 if (!Result.AllowEmpty && S.empty())
3747 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3748
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003749 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003750 return false;
3751}
3752
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003753template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003754bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3755 SmallVector<Metadata *, 4> MDs;
3756 if (ParseMDNodeVector(MDs))
3757 return true;
3758
3759 Result.assign(std::move(MDs));
3760 return false;
3761}
3762
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003763template <>
3764bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3765 ChecksumKindField &Result) {
3766 if (Lex.getKind() != lltok::ChecksumKind)
3767 return TokError(
3768 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3769
3770 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3771
3772 Result.assign(CSKind);
3773 Lex.Lex();
3774 return false;
3775}
3776
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003777} // end namespace llvm
3778
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003779template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003780bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003781 do {
3782 if (Lex.getKind() != lltok::LabelStr)
3783 return TokError("expected field label here");
3784
3785 if (parseField())
3786 return true;
3787 } while (EatIfPresent(lltok::comma));
3788
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003789 return false;
3790}
3791
3792template <class ParserTy>
3793bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3794 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3795 Lex.Lex();
3796
3797 if (ParseToken(lltok::lparen, "expected '(' here"))
3798 return true;
3799 if (Lex.getKind() != lltok::rparen)
3800 if (ParseMDFieldsImplBody(parseField))
3801 return true;
3802
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003803 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003804 return ParseToken(lltok::rparen, "expected ')' here");
3805}
3806
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003807template <class FieldTy>
3808bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3809 if (Result.Seen)
3810 return TokError("field '" + Name + "' cannot be specified more than once");
3811
3812 LocTy Loc = Lex.getLoc();
3813 Lex.Lex();
3814 return ParseMDField(Loc, Name, Result);
3815}
3816
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003817bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3818 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003819
3820#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003821 if (Lex.getStrVal() == #CLASS) \
3822 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003823#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003824
3825 return TokError("expected metadata type");
3826}
3827
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003828#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3829#define NOP_FIELD(NAME, TYPE, INIT)
3830#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3831 if (!NAME.Seen) \
3832 return Error(ClosingLoc, "missing required field '" #NAME "'");
3833#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003834 if (Lex.getStrVal() == #NAME) \
3835 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003836#define PARSE_MD_FIELDS() \
3837 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3838 do { \
3839 LocTy ClosingLoc; \
3840 if (ParseMDFieldsImpl([&]() -> bool { \
3841 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3842 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3843 }, ClosingLoc)) \
3844 return true; \
3845 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3846 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003847#define GET_OR_DISTINCT(CLASS, ARGS) \
3848 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003849
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003850/// ParseDILocationFields:
3851/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3852bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003853#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003854 OPTIONAL(line, LineField, ); \
3855 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003856 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003857 OPTIONAL(inlinedAt, MDField, );
3858 PARSE_MD_FIELDS();
3859#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003860
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003861 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003862 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003863 return false;
3864}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003865
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003866/// ParseGenericDINode:
3867/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3868bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003869#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003870 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003871 OPTIONAL(header, MDStringField, ); \
3872 OPTIONAL(operands, MDFieldList, );
3873 PARSE_MD_FIELDS();
3874#undef VISIT_MD_FIELDS
3875
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003876 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003877 (Context, tag.Val, header.Val, operands.Val));
3878 return false;
3879}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003880
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003881/// ParseDISubrange:
3882/// ::= !DISubrange(count: 30, lowerBound: 2)
3883bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003884#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003885 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003886 OPTIONAL(lowerBound, MDSignedField, );
3887 PARSE_MD_FIELDS();
3888#undef VISIT_MD_FIELDS
3889
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003890 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003891 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003892}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003893
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003894/// ParseDIEnumerator:
3895/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3896bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003897#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003898 REQUIRED(name, MDStringField, ); \
3899 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003900 PARSE_MD_FIELDS();
3901#undef VISIT_MD_FIELDS
3902
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003903 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003904 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003905}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003906
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003907/// ParseDIBasicType:
3908/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3909bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003910#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003911 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003912 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003913 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003914 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003915 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003916 PARSE_MD_FIELDS();
3917#undef VISIT_MD_FIELDS
3918
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003919 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003920 align.Val, encoding.Val));
3921 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003922}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003923
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003924/// ParseDIDerivedType:
3925/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003926/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003927/// align: 32, offset: 0, flags: 0, extraData: !3,
3928/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003929bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003930#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3931 REQUIRED(tag, DwarfTagField, ); \
3932 OPTIONAL(name, MDStringField, ); \
3933 OPTIONAL(file, MDField, ); \
3934 OPTIONAL(line, LineField, ); \
3935 OPTIONAL(scope, MDField, ); \
3936 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003937 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003938 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003939 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003940 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003941 OPTIONAL(extraData, MDField, ); \
3942 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003943 PARSE_MD_FIELDS();
3944#undef VISIT_MD_FIELDS
3945
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003946 Optional<unsigned> DWARFAddressSpace;
3947 if (dwarfAddressSpace.Val != UINT32_MAX)
3948 DWARFAddressSpace = dwarfAddressSpace.Val;
3949
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003950 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003951 (Context, tag.Val, name.Val, file.Val, line.Val,
3952 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003953 offset.Val, DWARFAddressSpace, flags.Val,
3954 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003955 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003956}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003957
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003958bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003959#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3960 REQUIRED(tag, DwarfTagField, ); \
3961 OPTIONAL(name, MDStringField, ); \
3962 OPTIONAL(file, MDField, ); \
3963 OPTIONAL(line, LineField, ); \
3964 OPTIONAL(scope, MDField, ); \
3965 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003966 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003967 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003968 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003969 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003970 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003971 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003972 OPTIONAL(vtableHolder, MDField, ); \
3973 OPTIONAL(templateParams, MDField, ); \
3974 OPTIONAL(identifier, MDStringField, );
3975 PARSE_MD_FIELDS();
3976#undef VISIT_MD_FIELDS
3977
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003978 // If this has an identifier try to build an ODR type.
3979 if (identifier.Val)
3980 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003981 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3982 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3983 elements.Val, runtimeLang.Val, vtableHolder.Val,
3984 templateParams.Val)) {
3985 Result = CT;
3986 return false;
3987 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003988
3989 // Create a new node, and save it in the context if it belongs in the type
3990 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003991 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003992 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003993 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3994 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3995 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3996 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003997}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003998
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003999bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004000#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004001 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004002 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004003 REQUIRED(types, MDField, );
4004 PARSE_MD_FIELDS();
4005#undef VISIT_MD_FIELDS
4006
Reid Klecknerde3d8b52016-06-08 20:34:29 +00004007 Result = GET_OR_DISTINCT(DISubroutineType,
4008 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00004009 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004010}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004011
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004012/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004013/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4014/// checksumkind: CSK_MD5,
4015/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004016bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004017#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4018 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004019 REQUIRED(directory, MDStringField, ); \
4020 OPTIONAL(checksumkind, ChecksumKindField, ); \
4021 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004022 PARSE_MD_FIELDS();
4023#undef VISIT_MD_FIELDS
4024
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004025 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4026 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004027 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004028}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004029
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004030/// ParseDICompileUnit:
4031/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004032/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004033/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004034/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004035/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004036bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004037 if (!IsDistinct)
4038 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4039
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004040#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4041 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004042 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004043 OPTIONAL(producer, MDStringField, ); \
4044 OPTIONAL(isOptimized, MDBoolField, ); \
4045 OPTIONAL(flags, MDStringField, ); \
4046 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4047 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004048 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004049 OPTIONAL(enums, MDField, ); \
4050 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004051 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004052 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004053 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004054 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004055 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4056 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004057 PARSE_MD_FIELDS();
4058#undef VISIT_MD_FIELDS
4059
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004060 Result = DICompileUnit::getDistinct(
4061 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4062 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004063 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004064 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004065 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004066}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004068/// ParseDISubprogram:
4069/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004070/// file: !1, line: 7, type: !2, isLocal: false,
4071/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004072/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004073/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004074/// isOptimized: false, templateParams: !4, declaration: !5,
Adrian Prantl1d12b882017-04-26 22:56:44 +00004075/// variables: !6, thrownTypes: !7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004076bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004077 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004078#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4079 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004080 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004081 OPTIONAL(linkageName, MDStringField, ); \
4082 OPTIONAL(file, MDField, ); \
4083 OPTIONAL(line, LineField, ); \
4084 OPTIONAL(type, MDField, ); \
4085 OPTIONAL(isLocal, MDBoolField, ); \
4086 OPTIONAL(isDefinition, MDBoolField, (true)); \
4087 OPTIONAL(scopeLine, LineField, ); \
4088 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004089 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004090 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004091 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004092 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004093 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004094 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004095 OPTIONAL(templateParams, MDField, ); \
4096 OPTIONAL(declaration, MDField, ); \
Adrian Prantl1d12b882017-04-26 22:56:44 +00004097 OPTIONAL(variables, MDField, ); \
4098 OPTIONAL(thrownTypes, MDField, );
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004099 PARSE_MD_FIELDS();
4100#undef VISIT_MD_FIELDS
4101
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004102 if (isDefinition.Val && !IsDistinct)
4103 return Lex.Error(
4104 Loc,
4105 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4106
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004107 Result = GET_OR_DISTINCT(
Adrian Prantl1d12b882017-04-26 22:56:44 +00004108 DISubprogram,
4109 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4110 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4111 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4112 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4113 declaration.Val, variables.Val, thrownTypes.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004114 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004115}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004116
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004117/// ParseDILexicalBlock:
4118/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4119bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004121 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004122 OPTIONAL(file, MDField, ); \
4123 OPTIONAL(line, LineField, ); \
4124 OPTIONAL(column, ColumnField, );
4125 PARSE_MD_FIELDS();
4126#undef VISIT_MD_FIELDS
4127
4128 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004129 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004130 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004131}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004132
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004133/// ParseDILexicalBlockFile:
4134/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4135bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004136#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004137 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004138 OPTIONAL(file, MDField, ); \
4139 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4140 PARSE_MD_FIELDS();
4141#undef VISIT_MD_FIELDS
4142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004144 (Context, scope.Val, file.Val, discriminator.Val));
4145 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004146}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004147
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004148/// ParseDINamespace:
4149/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4150bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004151#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4152 REQUIRED(scope, MDField, ); \
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004153 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004154 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004155 PARSE_MD_FIELDS();
4156#undef VISIT_MD_FIELDS
4157
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004158 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantlfed4f392017-04-28 22:25:46 +00004159 (Context, scope.Val, name.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004160 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004161}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004162
Amjad Abouda9bcf162015-12-10 12:56:35 +00004163/// ParseDIMacro:
4164/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4165bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4166#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4167 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004168 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004169 REQUIRED(name, MDStringField, ); \
4170 OPTIONAL(value, MDStringField, );
4171 PARSE_MD_FIELDS();
4172#undef VISIT_MD_FIELDS
4173
4174 Result = GET_OR_DISTINCT(DIMacro,
4175 (Context, type.Val, line.Val, name.Val, value.Val));
4176 return false;
4177}
4178
4179/// ParseDIMacroFile:
4180/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4181bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4182#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4183 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004184 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004185 REQUIRED(file, MDField, ); \
4186 OPTIONAL(nodes, MDField, );
4187 PARSE_MD_FIELDS();
4188#undef VISIT_MD_FIELDS
4189
4190 Result = GET_OR_DISTINCT(DIMacroFile,
4191 (Context, type.Val, line.Val, file.Val, nodes.Val));
4192 return false;
4193}
4194
Adrian Prantlab1243f2015-06-29 23:03:47 +00004195/// ParseDIModule:
4196/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4197/// includePath: "/usr/include", isysroot: "/")
4198bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4199#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4200 REQUIRED(scope, MDField, ); \
4201 REQUIRED(name, MDStringField, ); \
4202 OPTIONAL(configMacros, MDStringField, ); \
4203 OPTIONAL(includePath, MDStringField, ); \
4204 OPTIONAL(isysroot, MDStringField, );
4205 PARSE_MD_FIELDS();
4206#undef VISIT_MD_FIELDS
4207
4208 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4209 configMacros.Val, includePath.Val, isysroot.Val));
4210 return false;
4211}
4212
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004213/// ParseDITemplateTypeParameter:
4214/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4215bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004217 OPTIONAL(name, MDStringField, ); \
4218 REQUIRED(type, MDField, );
4219 PARSE_MD_FIELDS();
4220#undef VISIT_MD_FIELDS
4221
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004222 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004223 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004224 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004225}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004226
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004227/// ParseDITemplateValueParameter:
4228/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004229/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004230bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004231#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004232 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004233 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004234 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004235 REQUIRED(value, MDField, );
4236 PARSE_MD_FIELDS();
4237#undef VISIT_MD_FIELDS
4238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004239 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004240 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004241 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004242}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004243
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004244/// ParseDIGlobalVariable:
4245/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004246/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004247/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004248bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004249#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004250 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004251 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004252 OPTIONAL(linkageName, MDStringField, ); \
4253 OPTIONAL(file, MDField, ); \
4254 OPTIONAL(line, LineField, ); \
4255 OPTIONAL(type, MDField, ); \
4256 OPTIONAL(isLocal, MDBoolField, ); \
4257 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004258 OPTIONAL(declaration, MDField, ); \
4259 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004260 PARSE_MD_FIELDS();
4261#undef VISIT_MD_FIELDS
4262
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004263 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004264 (Context, scope.Val, name.Val, linkageName.Val,
4265 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004266 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004267 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004268}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004269
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004270/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004271/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004272/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4273/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004274/// ::= !DILocalVariable(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 Smitha9308c42015-04-29 16:38:44 +00004277bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004278#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004279 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004280 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004281 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004282 OPTIONAL(file, MDField, ); \
4283 OPTIONAL(line, LineField, ); \
4284 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004285 OPTIONAL(flags, DIFlagField, ); \
4286 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004287 PARSE_MD_FIELDS();
4288#undef VISIT_MD_FIELDS
4289
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004290 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004291 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004292 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004293 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004294}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004295
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004296/// ParseDIExpression:
4297/// ::= !DIExpression(0, 7, -1)
4298bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004299 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4300 Lex.Lex();
4301
4302 if (ParseToken(lltok::lparen, "expected '(' here"))
4303 return true;
4304
4305 SmallVector<uint64_t, 8> Elements;
4306 if (Lex.getKind() != lltok::rparen)
4307 do {
4308 if (Lex.getKind() == lltok::DwarfOp) {
4309 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4310 Lex.Lex();
4311 Elements.push_back(Op);
4312 continue;
4313 }
4314 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4315 }
4316
4317 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4318 return TokError("expected unsigned integer");
4319
4320 auto &U = Lex.getAPSIntVal();
4321 if (U.ugt(UINT64_MAX))
4322 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4323 Elements.push_back(U.getZExtValue());
4324 Lex.Lex();
4325 } while (EatIfPresent(lltok::comma));
4326
4327 if (ParseToken(lltok::rparen, "expected ')' here"))
4328 return true;
4329
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004330 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004331 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004332}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004333
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004334/// ParseDIGlobalVariableExpression:
4335/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4336bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4337 bool IsDistinct) {
4338#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4339 REQUIRED(var, MDField, ); \
4340 OPTIONAL(expr, MDField, );
4341 PARSE_MD_FIELDS();
4342#undef VISIT_MD_FIELDS
4343
4344 Result =
4345 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4346 return false;
4347}
4348
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004349/// ParseDIObjCProperty:
4350/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004351/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004352bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004353#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004354 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004355 OPTIONAL(file, MDField, ); \
4356 OPTIONAL(line, LineField, ); \
4357 OPTIONAL(setter, MDStringField, ); \
4358 OPTIONAL(getter, MDStringField, ); \
4359 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4360 OPTIONAL(type, MDField, );
4361 PARSE_MD_FIELDS();
4362#undef VISIT_MD_FIELDS
4363
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004364 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004365 (Context, name.Val, file.Val, line.Val, setter.Val,
4366 getter.Val, attributes.Val, type.Val));
4367 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004368}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004369
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004370/// ParseDIImportedEntity:
4371/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004372/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004373bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004374#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4375 REQUIRED(tag, DwarfTagField, ); \
4376 REQUIRED(scope, MDField, ); \
4377 OPTIONAL(entity, MDField, ); \
4378 OPTIONAL(line, LineField, ); \
4379 OPTIONAL(name, MDStringField, );
4380 PARSE_MD_FIELDS();
4381#undef VISIT_MD_FIELDS
4382
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004383 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004384 entity.Val, line.Val, name.Val));
4385 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004386}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004387
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004388#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004389#undef NOP_FIELD
4390#undef REQUIRE_FIELD
4391#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004392
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004393/// ParseMetadataAsValue
4394/// ::= metadata i32 %local
4395/// ::= metadata i32 @global
4396/// ::= metadata i32 7
4397/// ::= metadata !0
4398/// ::= metadata !{...}
4399/// ::= metadata !"string"
4400bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4401 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004402 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004403 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004404 return true;
4405
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004406 V = MetadataAsValue::get(Context, MD);
4407 return false;
4408}
4409
4410/// ParseValueAsMetadata
4411/// ::= i32 %local
4412/// ::= i32 @global
4413/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004414bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4415 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004416 Type *Ty;
4417 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004418 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004419 return true;
4420 if (Ty->isMetadataTy())
4421 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4422
4423 Value *V;
4424 if (ParseValue(Ty, V, PFS))
4425 return true;
4426
4427 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004428 return false;
4429}
4430
4431/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004432/// ::= i32 %local
4433/// ::= i32 @global
4434/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004435/// ::= !42
4436/// ::= !{...}
4437/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004438/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004439bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004440 if (Lex.getKind() == lltok::MetadataVar) {
4441 MDNode *N;
4442 if (ParseSpecializedMDNode(N))
4443 return true;
4444 MD = N;
4445 return false;
4446 }
4447
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004448 // ValueAsMetadata:
4449 // <type> <value>
4450 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004451 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004452
4453 // '!'.
4454 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4455 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004456
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004457 // MDString:
4458 // ::= '!' STRINGCONSTANT
4459 if (Lex.getKind() == lltok::StringConstant) {
4460 MDString *S;
4461 if (ParseMDString(S))
4462 return true;
4463 MD = S;
4464 return false;
4465 }
4466
Dan Gohman8939ba332010-07-14 18:26:50 +00004467 // MDNode:
4468 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004469 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004470 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004471 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004472 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004473 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004474 return false;
4475}
4476
Victor Hernandez9d75c962010-01-11 22:31:58 +00004477//===----------------------------------------------------------------------===//
4478// Function Parsing.
4479//===----------------------------------------------------------------------===//
4480
Chris Lattner229907c2011-07-18 04:54:35 +00004481bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004482 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004483 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004484 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004485
Chris Lattnerac161bf2009-01-02 07:01:27 +00004486 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004487 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004488 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004489 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004490 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004491 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004492 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004493 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004494 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004495 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004496 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004497 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004498 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4499 (ID.UIntVal >> 1) & 1,
4500 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004501 return false;
4502 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004503 case ValID::t_GlobalName:
4504 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004505 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004506 case ValID::t_GlobalID:
4507 V = GetGlobalVal(ID.UIntVal, 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_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004510 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004511 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004512 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004513 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004514 return false;
4515 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004516 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004517 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4518 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004519
Dan Gohman518cda42011-12-17 00:04:22 +00004520 // The lexer has no type info, so builds all half, float, and double FP
4521 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004522 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004524 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004525 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004526 &Ignored);
4527 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004528 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004529 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004531 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004532
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004533 if (V->getType() != Ty)
4534 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004535 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004536
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 return false;
4538 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004539 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004540 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004541 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 return false;
4543 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004544 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004545 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004546 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004547 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004548 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004549 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004550 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004551 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004552 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004553 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004555 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004556 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004557 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004558 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004559 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004560 case ValID::t_None:
4561 if (!Ty->isTokenTy())
4562 return Error(ID.Loc, "invalid type for none constant");
4563 V = Constant::getNullValue(Ty);
4564 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004566 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004567 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004568
Chris Lattnerac161bf2009-01-02 07:01:27 +00004569 V = ID.ConstantVal;
4570 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004571 case ValID::t_ConstantStruct:
4572 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004573 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004574 if (ST->getNumElements() != ID.UIntVal)
4575 return Error(ID.Loc,
4576 "initializer with struct type has wrong # elements");
4577 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4578 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004580 // Verify that the elements are compatible with the structtype.
4581 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4582 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4583 return Error(ID.Loc, "element " + Twine(i) +
4584 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004585
David Blaikieadbda4b2015-08-03 20:08:41 +00004586 V = ConstantStruct::get(
4587 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004588 } else
4589 return Error(ID.Loc, "constant expression type mismatch");
4590 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004591 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004592 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004593}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004594
Alex Lorenzd2255952015-07-17 22:07:03 +00004595bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4596 C = nullptr;
4597 ValID ID;
4598 auto Loc = Lex.getLoc();
4599 if (ParseValID(ID, /*PFS=*/nullptr))
4600 return true;
4601 switch (ID.Kind) {
4602 case ValID::t_APSInt:
4603 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004604 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004605 case ValID::t_Constant:
4606 case ValID::t_ConstantStruct:
4607 case ValID::t_PackedConstantStruct: {
4608 Value *V;
4609 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4610 return true;
4611 assert(isa<Constant>(V) && "Expected a constant value");
4612 C = cast<Constant>(V);
4613 return false;
4614 }
Eric Christopherb9c56d12017-03-30 22:34:20 +00004615 case ValID::t_Null:
4616 C = Constant::getNullValue(Ty);
4617 return false;
Alex Lorenzd2255952015-07-17 22:07:03 +00004618 default:
4619 return Error(Loc, "expected a constant value");
4620 }
4621}
4622
David Majnemer8a1c45d2015-12-12 05:38:55 +00004623bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004624 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004625 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004626 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627}
4628
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004629bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004630 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004631 return ParseType(Ty) ||
4632 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004633}
4634
Chris Lattner3ed871f2009-10-27 19:13:16 +00004635bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4636 PerFunctionState &PFS) {
4637 Value *V;
4638 Loc = Lex.getLoc();
4639 if (ParseTypeAndValue(V, PFS)) return true;
4640 if (!isa<BasicBlock>(V))
4641 return Error(Loc, "expected a basic block");
4642 BB = cast<BasicBlock>(V);
4643 return false;
4644}
4645
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646/// FunctionHeader
4647/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004648/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004649/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004650bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4651 // Parse the linkage.
4652 LocTy LinkageLoc = Lex.getLoc();
4653 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004654
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004655 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004656 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004657 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004658 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004659 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004660 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004662 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4663 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004664 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004665 return true;
4666
4667 // Verify that the linkage is ok.
4668 switch ((GlobalValue::LinkageTypes)Linkage) {
4669 case GlobalValue::ExternalLinkage:
4670 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004671 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 if (isDefine)
4673 return Error(LinkageLoc, "invalid linkage for function definition");
4674 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004675 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004676 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004677 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004678 case GlobalValue::LinkOnceAnyLinkage:
4679 case GlobalValue::LinkOnceODRLinkage:
4680 case GlobalValue::WeakAnyLinkage:
4681 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682 if (!isDefine)
4683 return Error(LinkageLoc, "invalid linkage for function declaration");
4684 break;
4685 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004686 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004687 return Error(LinkageLoc, "invalid function linkage type");
4688 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004689
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004690 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4691 return Error(LinkageLoc,
4692 "symbol with local linkage must have default visibility");
4693
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004694 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004695 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004696
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004698
4699 std::string FunctionName;
4700 if (Lex.getKind() == lltok::GlobalVar) {
4701 FunctionName = Lex.getStrVal();
4702 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4703 unsigned NameID = Lex.getUIntVal();
4704
4705 if (NameID != NumberedVals.size())
4706 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004707 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004708 } else {
4709 return TokError("expected function name");
4710 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004711
Chris Lattner3822f632009-01-02 08:05:26 +00004712 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004713
Chris Lattner3822f632009-01-02 08:05:26 +00004714 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004716
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004717 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004719 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004720 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004721 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004722 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004724 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004725 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004726 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004727 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004728 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004729 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004730 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004731
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004732 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004733 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004734 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004735 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004736 (EatIfPresent(lltok::kw_section) &&
4737 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004738 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004739 ParseOptionalAlignment(Alignment) ||
4740 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004741 ParseStringConstant(GC)) ||
4742 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004743 ParseGlobalTypeAndValue(Prefix)) ||
4744 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004745 ParseGlobalTypeAndValue(Prologue)) ||
4746 (EatIfPresent(lltok::kw_personality) &&
4747 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004748 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004749
Michael Gottesman41748d72013-06-27 00:25:01 +00004750 if (FuncAttrs.contains(Attribute::Builtin))
4751 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004752
Chris Lattnerac161bf2009-01-02 07:01:27 +00004753 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004754 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004755 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004756 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004758
Chris Lattnerac161bf2009-01-02 07:01:27 +00004759 // Okay, if we got here, the function is syntactically valid. Convert types
4760 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004761 std::vector<Type*> ParamTypeList;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004762 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004763
Chris Lattnerac161bf2009-01-02 07:01:27 +00004764 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004765 ParamTypeList.push_back(ArgList[i].Ty);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004766 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 }
4768
Reid Kleckner7f720332017-04-13 00:58:09 +00004769 AttributeList PAL =
4770 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4771 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772
Bill Wendling749a43d2012-12-30 13:50:49 +00004773 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004774 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4775
Chris Lattner229907c2011-07-18 04:54:35 +00004776 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004777 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004778 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004779
Craig Topper2617dcc2014-04-15 06:32:26 +00004780 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004781 if (!FunctionName.empty()) {
4782 // If this was a definition of a forward reference, remove the definition
4783 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004784 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 if (FRVI != ForwardRefVals.end()) {
4786 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004787 if (!Fn)
4788 return Error(FRVI->second.second, "invalid forward reference to "
4789 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004790 if (Fn->getType() != PFT)
4791 return Error(FRVI->second.second, "invalid forward reference to "
4792 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004793
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 ForwardRefVals.erase(FRVI);
4795 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004796 // Reject redefinitions.
4797 return Error(NameLoc, "invalid redefinition of function '" +
4798 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004799 } else if (M->getNamedValue(FunctionName)) {
4800 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004801 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004802
Dan Gohman399d6ae2009-08-29 23:37:49 +00004803 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004804 // If this is a definition of a forward referenced function, make sure the
4805 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004806 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004807 if (I != ForwardRefValIDs.end()) {
4808 Fn = cast<Function>(I->second.first);
4809 if (Fn->getType() != PFT)
4810 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004811 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 ForwardRefValIDs.erase(I);
4813 }
4814 }
4815
Craig Topper2617dcc2014-04-15 06:32:26 +00004816 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4818 else // Move the forward-reference to the correct spot in the module.
4819 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4820
4821 if (FunctionName.empty())
4822 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004823
Chris Lattnerac161bf2009-01-02 07:01:27 +00004824 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4825 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004826 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 Fn->setCallingConv(CC);
4828 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004829 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 Fn->setAlignment(Alignment);
4831 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004832 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004833 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004834 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004835 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004836 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004837 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004838
Chris Lattnerac161bf2009-01-02 07:01:27 +00004839 // Add all of the arguments we parsed to the function.
4840 Function::arg_iterator ArgIt = Fn->arg_begin();
4841 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4842 // If the argument has a name, insert it into the argument symbol table.
4843 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004844
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 // Set the name, if it conflicted, it will be auto-renamed.
4846 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004847
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004848 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4850 ArgList[i].Name + "'");
4851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004852
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004853 if (isDefine)
4854 return false;
4855
Robin Morisset039781e2014-08-29 21:53:01 +00004856 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004857 ValID ID;
4858 if (FunctionName.empty()) {
4859 ID.Kind = ValID::t_GlobalID;
4860 ID.UIntVal = NumberedVals.size() - 1;
4861 } else {
4862 ID.Kind = ValID::t_GlobalName;
4863 ID.StrVal = FunctionName;
4864 }
4865 auto Blocks = ForwardRefBlockAddresses.find(ID);
4866 if (Blocks != ForwardRefBlockAddresses.end())
4867 return Error(Blocks->first.Loc,
4868 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004869 return false;
4870}
4871
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004872bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4873 ValID ID;
4874 if (FunctionNumber == -1) {
4875 ID.Kind = ValID::t_GlobalName;
4876 ID.StrVal = F.getName();
4877 } else {
4878 ID.Kind = ValID::t_GlobalID;
4879 ID.UIntVal = FunctionNumber;
4880 }
4881
4882 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4883 if (Blocks == P.ForwardRefBlockAddresses.end())
4884 return false;
4885
4886 for (const auto &I : Blocks->second) {
4887 const ValID &BBID = I.first;
4888 GlobalValue *GV = I.second;
4889
4890 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4891 "Expected local id or name");
4892 BasicBlock *BB;
4893 if (BBID.Kind == ValID::t_LocalName)
4894 BB = GetBB(BBID.StrVal, BBID.Loc);
4895 else
4896 BB = GetBB(BBID.UIntVal, BBID.Loc);
4897 if (!BB)
4898 return P.Error(BBID.Loc, "referenced value is not a basic block");
4899
4900 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4901 GV->eraseFromParent();
4902 }
4903
4904 P.ForwardRefBlockAddresses.erase(Blocks);
4905 return false;
4906}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004907
4908/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004909/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004910bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004911 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004912 return TokError("expected '{' in function body");
4913 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004914
Chris Lattner3432c622009-10-28 03:39:23 +00004915 int FunctionNumber = -1;
4916 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004917
Chris Lattner3432c622009-10-28 03:39:23 +00004918 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004919
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004920 // Resolve block addresses and allow basic blocks to be forward-declared
4921 // within this function.
4922 if (PFS.resolveForwardRefBlockAddresses())
4923 return true;
4924 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4925
Chris Lattnerbbddd962010-01-09 19:20:07 +00004926 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004927 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004928 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004929
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004930 while (Lex.getKind() != lltok::rbrace &&
4931 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004933
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004934 while (Lex.getKind() != lltok::rbrace)
4935 if (ParseUseListOrder(&PFS))
4936 return true;
4937
Chris Lattnerac161bf2009-01-02 07:01:27 +00004938 // Eat the }.
4939 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004942 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943}
4944
4945/// ParseBasicBlock
4946/// ::= LabelStr? Instruction*
4947bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4948 // If this basic block starts out with a name, remember it.
4949 std::string Name;
4950 LocTy NameLoc = Lex.getLoc();
4951 if (Lex.getKind() == lltok::LabelStr) {
4952 Name = Lex.getStrVal();
4953 Lex.Lex();
4954 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004955
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004957 if (!BB)
4958 return Error(NameLoc,
4959 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004960
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004962
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 // Parse the instructions in this block until we get a terminator.
4964 Instruction *Inst;
4965 do {
4966 // This instruction may have three possibilities for a name: a) none
4967 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4968 LocTy NameLoc = Lex.getLoc();
4969 int NameID = -1;
4970 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004971
Chris Lattnerac161bf2009-01-02 07:01:27 +00004972 if (Lex.getKind() == lltok::LocalVarID) {
4973 NameID = Lex.getUIntVal();
4974 Lex.Lex();
4975 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4976 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004977 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004978 NameStr = Lex.getStrVal();
4979 Lex.Lex();
4980 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4981 return true;
4982 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004983
Chris Lattner77b89dc2009-12-30 05:23:43 +00004984 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004985 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004986 case InstError: return true;
4987 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004988 BB->getInstList().push_back(Inst);
4989
Chris Lattner77b89dc2009-12-30 05:23:43 +00004990 // With a normal result, we check to see if the instruction is followed by
4991 // a comma and metadata.
4992 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004993 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004994 return true;
4995 break;
4996 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004997 BB->getInstList().push_back(Inst);
4998
Chris Lattner77b89dc2009-12-30 05:23:43 +00004999 // If the instruction parser ate an extra comma at the end of it, it
5000 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00005001 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00005002 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005003 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00005004 }
Devang Patelea8a4b92009-09-17 23:04:48 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 // Set the name on the instruction.
5007 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5008 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005009
Chris Lattnerac161bf2009-01-02 07:01:27 +00005010 return false;
5011}
5012
5013//===----------------------------------------------------------------------===//
5014// Instruction Parsing.
5015//===----------------------------------------------------------------------===//
5016
5017/// ParseInstruction - Parse one of the many different instructions.
5018///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005019int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5020 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 lltok::Kind Token = Lex.getKind();
5022 if (Token == lltok::Eof)
5023 return TokError("found end of file when expecting more instructions");
5024 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005025 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005026 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005027
Chris Lattnerac161bf2009-01-02 07:01:27 +00005028 switch (Token) {
5029 default: return Error(Loc, "expected instruction opcode");
5030 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005031 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5033 case lltok::kw_br: return ParseBr(Inst, PFS);
5034 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005035 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005037 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005038 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5039 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005040 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5041 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005042 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 // Binary Operators.
5044 case lltok::kw_add:
5045 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005046 case lltok::kw_mul:
5047 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005048 bool NUW = EatIfPresent(lltok::kw_nuw);
5049 bool NSW = EatIfPresent(lltok::kw_nsw);
5050 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005051
Chris Lattnera676c0f2011-02-07 16:40:21 +00005052 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005053
Chris Lattnera676c0f2011-02-07 16:40:21 +00005054 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5055 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5056 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005057 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005058 case lltok::kw_fadd:
5059 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005060 case lltok::kw_fmul:
5061 case lltok::kw_fdiv:
5062 case lltok::kw_frem: {
5063 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5064 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5065 if (Res != 0)
5066 return Res;
5067 if (FMF.any())
5068 Inst->setFastMathFlags(FMF);
5069 return 0;
5070 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005071
Chris Lattner35315d02011-02-06 21:44:57 +00005072 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005073 case lltok::kw_udiv:
5074 case lltok::kw_lshr:
5075 case lltok::kw_ashr: {
5076 bool Exact = EatIfPresent(lltok::kw_exact);
5077
5078 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5079 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5080 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005081 }
5082
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005084 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005085 case lltok::kw_and:
5086 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005087 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005088 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5089 case lltok::kw_fcmp: {
5090 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5091 int Res = ParseCompare(Inst, PFS, KeywordVal);
5092 if (Res != 0)
5093 return Res;
5094 if (FMF.any())
5095 Inst->setFastMathFlags(FMF);
5096 return 0;
5097 }
5098
Chris Lattnerac161bf2009-01-02 07:01:27 +00005099 // Casts.
5100 case lltok::kw_trunc:
5101 case lltok::kw_zext:
5102 case lltok::kw_sext:
5103 case lltok::kw_fptrunc:
5104 case lltok::kw_fpext:
5105 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005106 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 case lltok::kw_uitofp:
5108 case lltok::kw_sitofp:
5109 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005110 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005111 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005112 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 // Other.
5114 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005115 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005116 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5117 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5118 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5119 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005120 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005121 // Call.
5122 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5123 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5124 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005125 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005126 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005127 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005128 case lltok::kw_load: return ParseLoad(Inst, PFS);
5129 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005130 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5131 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005132 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005133 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5134 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5135 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5136 }
5137}
5138
5139/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5140bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005141 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005142 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005143 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5145 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5146 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5147 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5148 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5149 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5150 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5151 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5152 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5153 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5154 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5155 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5156 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5157 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5158 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5159 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5160 }
5161 } else {
5162 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005163 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005164 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5165 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5166 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5167 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5168 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5169 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5170 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5171 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5172 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5173 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5174 }
5175 }
5176 Lex.Lex();
5177 return false;
5178}
5179
5180//===----------------------------------------------------------------------===//
5181// Terminator Instructions.
5182//===----------------------------------------------------------------------===//
5183
5184/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005185/// ::= 'ret' void (',' !dbg, !1)*
5186/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005187bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005188 PerFunctionState &PFS) {
5189 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005190 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005191 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005192
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005193 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005194
Chris Lattnerfdd87902009-10-05 05:54:46 +00005195 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005196 if (!ResType->isVoidTy())
5197 return Error(TypeLoc, "value doesn't match function result type '" +
5198 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005199
Owen Anderson55f1c092009-08-13 21:58:54 +00005200 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 return false;
5202 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005203
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 Value *RV;
5205 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005207 if (ResType != RV->getType())
5208 return Error(TypeLoc, "value doesn't match function result type '" +
5209 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005210
Owen Anderson55f1c092009-08-13 21:58:54 +00005211 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005212 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005213}
5214
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215/// ParseBr
5216/// ::= 'br' TypeAndValue
5217/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5218bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5219 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005220 Value *Op0;
5221 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005222 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005223
Chris Lattnerac161bf2009-01-02 07:01:27 +00005224 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5225 Inst = BranchInst::Create(BB);
5226 return false;
5227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005228
Owen Anderson55f1c092009-08-13 21:58:54 +00005229 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005230 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005231
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005233 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005234 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005235 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005236 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005237
Chris Lattner3ed871f2009-10-27 19:13:16 +00005238 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239 return false;
5240}
5241
5242/// ParseSwitch
5243/// Instruction
5244/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5245/// JumpTable
5246/// ::= (TypeAndValue ',' TypeAndValue)*
5247bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5248 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005249 Value *Cond;
5250 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005251 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5252 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005253 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5255 return true;
5256
Duncan Sands19d0b472010-02-16 11:11:14 +00005257 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005258 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 // Parse the jump table pairs.
5261 SmallPtrSet<Value*, 32> SeenCases;
5262 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5263 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005264 Value *Constant;
5265 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005266
Chris Lattnerac161bf2009-01-02 07:01:27 +00005267 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5268 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005269 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005270 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005271
David Blaikie70573dc2014-11-19 07:49:26 +00005272 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005273 return Error(CondLoc, "duplicate case value in switch");
5274 if (!isa<ConstantInt>(Constant))
5275 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005276
Chris Lattner3ed871f2009-10-27 19:13:16 +00005277 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005279
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005281
Chris Lattner3ed871f2009-10-27 19:13:16 +00005282 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5284 SI->addCase(Table[i].first, Table[i].second);
5285 Inst = SI;
5286 return false;
5287}
5288
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005289/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005290/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005291/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5292bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005293 LocTy AddrLoc;
5294 Value *Address;
5295 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005296 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5297 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005298 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005299
Duncan Sands19d0b472010-02-16 11:11:14 +00005300 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005301 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005302
Chris Lattner3ed871f2009-10-27 19:13:16 +00005303 // Parse the destination list.
5304 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005305
Chris Lattner3ed871f2009-10-27 19:13:16 +00005306 if (Lex.getKind() != lltok::rsquare) {
5307 BasicBlock *DestBB;
5308 if (ParseTypeAndBasicBlock(DestBB, PFS))
5309 return true;
5310 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005311
Chris Lattner3ed871f2009-10-27 19:13:16 +00005312 while (EatIfPresent(lltok::comma)) {
5313 if (ParseTypeAndBasicBlock(DestBB, PFS))
5314 return true;
5315 DestList.push_back(DestBB);
5316 }
5317 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005318
Chris Lattner3ed871f2009-10-27 19:13:16 +00005319 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5320 return true;
5321
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005322 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005323 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5324 IBI->addDestination(DestList[i]);
5325 Inst = IBI;
5326 return false;
5327}
5328
Chris Lattnerac161bf2009-01-02 07:01:27 +00005329/// ParseInvoke
5330/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5331/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5332bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5333 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005334 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005335 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005336 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005337 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005338 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005339 LocTy RetTypeLoc;
5340 ValID CalleeID;
5341 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005342 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005343
Chris Lattner3ed871f2009-10-27 19:13:16 +00005344 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005345 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005346 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005347 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005348 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5349 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005350 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005351 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005352 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005353 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005354 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005356
Chris Lattnerac161bf2009-01-02 07:01:27 +00005357 // If RetType is a non-function pointer type, then this is the short syntax
5358 // for the call, which means that RetType is just the return type. Infer the
5359 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005360 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5361 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005362 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005363 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005364 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5365 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005366
Chris Lattnerac161bf2009-01-02 07:01:27 +00005367 if (!FunctionType::isValidReturnType(RetType))
5368 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005369
Owen Anderson4056ca92009-07-29 22:17:13 +00005370 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005371 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005372
David Blaikie41ba2b42015-07-27 23:32:19 +00005373 CalleeID.FTy = Ty;
5374
Chris Lattnerac161bf2009-01-02 07:01:27 +00005375 // Look up the callee.
5376 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005377 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5378 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005379
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005380 // Set up the Attribute for the function.
Reid Kleckner7f720332017-04-13 00:58:09 +00005381 SmallVector<Value *, 8> Args;
5382 SmallVector<AttributeSet, 8> ArgAttrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005383
Chris Lattnerac161bf2009-01-02 07:01:27 +00005384 // Loop through FunctionType's arguments and ensure they are specified
5385 // correctly. Also, gather any parameter attributes.
5386 FunctionType::param_iterator I = Ty->param_begin();
5387 FunctionType::param_iterator E = Ty->param_end();
5388 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005389 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005390 if (I != E) {
5391 ExpectedTy = *I++;
5392 } else if (!Ty->isVarArg()) {
5393 return Error(ArgList[i].Loc, "too many arguments specified");
5394 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005395
Chris Lattnerac161bf2009-01-02 07:01:27 +00005396 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5397 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005398 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399 Args.push_back(ArgList[i].V);
Reid Kleckner7f720332017-04-13 00:58:09 +00005400 ArgAttrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005401 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005402
Chris Lattnerac161bf2009-01-02 07:01:27 +00005403 if (I != E)
5404 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005405
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005406 if (FnAttrs.hasAlignmentAttr())
5407 return Error(CallLoc, "invoke instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00005408
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005409 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00005410 AttributeList PAL =
5411 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5412 AttributeSet::get(Context, RetAttrs), ArgAttrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005413
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005414 InvokeInst *II =
5415 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005416 II->setCallingConv(CC);
5417 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005418 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005419 Inst = II;
5420 return false;
5421}
5422
Bill Wendlingf891bf82011-07-31 06:30:59 +00005423/// ParseResume
5424/// ::= 'resume' TypeAndValue
5425bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5426 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005427 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5428 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005429
Bill Wendlingf891bf82011-07-31 06:30:59 +00005430 ResumeInst *RI = ResumeInst::Create(Exn);
5431 Inst = RI;
5432 return false;
5433}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434
David Majnemer654e1302015-07-31 17:58:14 +00005435bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5436 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005437 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005438 return true;
5439
5440 while (Lex.getKind() != lltok::rsquare) {
5441 // If this isn't the first argument, we need a comma.
5442 if (!Args.empty() &&
5443 ParseToken(lltok::comma, "expected ',' in argument list"))
5444 return true;
5445
5446 // Parse the argument.
5447 LocTy ArgLoc;
5448 Type *ArgTy = nullptr;
5449 if (ParseType(ArgTy, ArgLoc))
5450 return true;
5451
5452 Value *V;
5453 if (ArgTy->isMetadataTy()) {
5454 if (ParseMetadataAsValue(V, PFS))
5455 return true;
5456 } else {
5457 if (ParseValue(ArgTy, V, PFS))
5458 return true;
5459 }
5460 Args.push_back(V);
5461 }
5462
5463 Lex.Lex(); // Lex the ']'.
5464 return false;
5465}
5466
5467/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005468/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005469bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005470 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005471
David Majnemer8a1c45d2015-12-12 05:38:55 +00005472 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5473 return true;
5474
5475 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005476 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005477
5478 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5479 return true;
5480
5481 BasicBlock *UnwindBB = nullptr;
5482 if (Lex.getKind() == lltok::kw_to) {
5483 Lex.Lex();
5484 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5485 return true;
5486 } else {
5487 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5488 return true;
5489 }
5490 }
5491
David Majnemer8a1c45d2015-12-12 05:38:55 +00005492 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005493 return false;
5494}
5495
5496/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005497/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005498bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005499 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005500
David Majnemer8a1c45d2015-12-12 05:38:55 +00005501 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5502 return true;
5503
5504 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005505 return true;
5506
David Majnemer0bc0eef2015-08-15 02:46:08 +00005507 BasicBlock *BB;
5508 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5509 ParseTypeAndBasicBlock(BB, PFS))
5510 return true;
5511
David Majnemer8a1c45d2015-12-12 05:38:55 +00005512 Inst = CatchReturnInst::Create(CatchPad, BB);
5513 return false;
5514}
5515
5516/// ParseCatchSwitch
5517/// ::= 'catchswitch' within Parent
5518bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5519 Value *ParentPad;
5520 LocTy BBLoc;
5521
5522 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5523 return true;
5524
5525 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5526 Lex.getKind() != lltok::LocalVarID)
5527 return TokError("expected scope value for catchswitch");
5528
5529 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5530 return true;
5531
5532 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5533 return true;
5534
5535 SmallVector<BasicBlock *, 32> Table;
5536 do {
5537 BasicBlock *DestBB;
5538 if (ParseTypeAndBasicBlock(DestBB, PFS))
5539 return true;
5540 Table.push_back(DestBB);
5541 } while (EatIfPresent(lltok::comma));
5542
5543 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5544 return true;
5545
5546 if (ParseToken(lltok::kw_unwind,
5547 "expected 'unwind' after catchswitch scope"))
5548 return true;
5549
5550 BasicBlock *UnwindBB = nullptr;
5551 if (EatIfPresent(lltok::kw_to)) {
5552 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5553 return true;
5554 } else {
5555 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5556 return true;
5557 }
5558
5559 auto *CatchSwitch =
5560 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5561 for (BasicBlock *DestBB : Table)
5562 CatchSwitch->addHandler(DestBB);
5563 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005564 return false;
5565}
5566
5567/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005568/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005569bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005570 Value *CatchSwitch = nullptr;
5571
5572 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5573 return true;
5574
5575 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5576 return TokError("expected scope value for catchpad");
5577
5578 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5579 return true;
5580
David Majnemer654e1302015-07-31 17:58:14 +00005581 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005582 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005583 return true;
5584
David Majnemer8a1c45d2015-12-12 05:38:55 +00005585 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005586 return false;
5587}
5588
David Majnemer654e1302015-07-31 17:58:14 +00005589/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005590/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005591bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005592 Value *ParentPad = nullptr;
5593
5594 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5595 return true;
5596
5597 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5598 Lex.getKind() != lltok::LocalVarID)
5599 return TokError("expected scope value for cleanuppad");
5600
5601 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5602 return true;
5603
David Majnemer654e1302015-07-31 17:58:14 +00005604 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005605 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005606 return true;
5607
David Majnemer8a1c45d2015-12-12 05:38:55 +00005608 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005609 return false;
5610}
5611
Chris Lattnerac161bf2009-01-02 07:01:27 +00005612//===----------------------------------------------------------------------===//
5613// Binary Operators.
5614//===----------------------------------------------------------------------===//
5615
5616/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005617/// ::= ArithmeticOps TypeAndValue ',' Value
5618///
5619/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5620/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005621bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005622 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005623 LocTy Loc; Value *LHS, *RHS;
5624 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5625 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5626 ParseValue(LHS->getType(), RHS, PFS))
5627 return true;
5628
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005629 bool Valid;
5630 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005631 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005632 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005633 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5634 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005635 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005636 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5637 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005638 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005639
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005640 if (!Valid)
5641 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005642
Chris Lattnerac161bf2009-01-02 07:01:27 +00005643 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5644 return false;
5645}
5646
5647/// ParseLogical
5648/// ::= ArithmeticOps TypeAndValue ',' Value {
5649bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5650 unsigned Opc) {
5651 LocTy Loc; Value *LHS, *RHS;
5652 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5653 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5654 ParseValue(LHS->getType(), RHS, PFS))
5655 return true;
5656
Duncan Sands9dff9be2010-02-15 16:12:20 +00005657 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005658 return Error(Loc,"instruction requires integer or integer vector operands");
5659
5660 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5661 return false;
5662}
5663
Chris Lattnerac161bf2009-01-02 07:01:27 +00005664/// ParseCompare
5665/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5666/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5668 unsigned Opc) {
5669 // Parse the integer/fp comparison predicate.
5670 LocTy Loc;
5671 unsigned Pred;
5672 Value *LHS, *RHS;
5673 if (ParseCmpPredicate(Pred, Opc) ||
5674 ParseTypeAndValue(LHS, Loc, PFS) ||
5675 ParseToken(lltok::comma, "expected ',' after compare value") ||
5676 ParseValue(LHS->getType(), RHS, PFS))
5677 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005678
Chris Lattnerac161bf2009-01-02 07:01:27 +00005679 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005680 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005682 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005683 } else {
5684 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005685 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005686 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005687 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005688 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 }
5690 return false;
5691}
5692
5693//===----------------------------------------------------------------------===//
5694// Other Instructions.
5695//===----------------------------------------------------------------------===//
5696
5697
5698/// ParseCast
5699/// ::= CastOpc TypeAndValue 'to' Type
5700bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5701 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005702 LocTy Loc;
5703 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005704 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005705 if (ParseTypeAndValue(Op, Loc, PFS) ||
5706 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5707 ParseType(DestTy))
5708 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005709
Chris Lattner89d856e2009-03-01 00:53:13 +00005710 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5711 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005713 getTypeString(Op->getType()) + "' to '" +
5714 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005715 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005716 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5717 return false;
5718}
5719
5720/// ParseSelect
5721/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5722bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5723 LocTy Loc;
5724 Value *Op0, *Op1, *Op2;
5725 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5726 ParseToken(lltok::comma, "expected ',' after select condition") ||
5727 ParseTypeAndValue(Op1, PFS) ||
5728 ParseToken(lltok::comma, "expected ',' after select value") ||
5729 ParseTypeAndValue(Op2, PFS))
5730 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005731
Chris Lattnerac161bf2009-01-02 07:01:27 +00005732 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5733 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005734
Chris Lattnerac161bf2009-01-02 07:01:27 +00005735 Inst = SelectInst::Create(Op0, Op1, Op2);
5736 return false;
5737}
5738
Chris Lattnerb55ab542009-01-05 08:18:44 +00005739/// ParseVA_Arg
5740/// ::= 'va_arg' TypeAndValue ',' Type
5741bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005742 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005743 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005744 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 if (ParseTypeAndValue(Op, PFS) ||
5746 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005747 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005748 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005749
Chris Lattnerb55ab542009-01-05 08:18:44 +00005750 if (!EltTy->isFirstClassType())
5751 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005752
5753 Inst = new VAArgInst(Op, EltTy);
5754 return false;
5755}
5756
5757/// ParseExtractElement
5758/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5759bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5760 LocTy Loc;
5761 Value *Op0, *Op1;
5762 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5763 ParseToken(lltok::comma, "expected ',' after extract value") ||
5764 ParseTypeAndValue(Op1, PFS))
5765 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005766
Chris Lattnerac161bf2009-01-02 07:01:27 +00005767 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5768 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005769
Eric Christopherc9742252009-07-25 02:28:41 +00005770 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005771 return false;
5772}
5773
5774/// ParseInsertElement
5775/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5776bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5777 LocTy Loc;
5778 Value *Op0, *Op1, *Op2;
5779 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5780 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5781 ParseTypeAndValue(Op1, PFS) ||
5782 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5783 ParseTypeAndValue(Op2, PFS))
5784 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005785
Chris Lattnerac161bf2009-01-02 07:01:27 +00005786 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005787 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005788
Chris Lattnerac161bf2009-01-02 07:01:27 +00005789 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5790 return false;
5791}
5792
5793/// ParseShuffleVector
5794/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5795bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5796 LocTy Loc;
5797 Value *Op0, *Op1, *Op2;
5798 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5799 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5800 ParseTypeAndValue(Op1, PFS) ||
5801 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5802 ParseTypeAndValue(Op2, PFS))
5803 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005804
Chris Lattnerac161bf2009-01-02 07:01:27 +00005805 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005806 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005807
Chris Lattnerac161bf2009-01-02 07:01:27 +00005808 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5809 return false;
5810}
5811
5812/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005813/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005814int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005815 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005816 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005817
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005818 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005819 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5820 ParseValue(Ty, Op0, PFS) ||
5821 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005822 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005823 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5824 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005825
Chris Lattnerf4f03422009-12-30 05:27:33 +00005826 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005827 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005828
5829 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005830 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005831
Chris Lattner3822f632009-01-02 08:05:26 +00005832 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005833 break;
5834
Chris Lattnerf4f03422009-12-30 05:27:33 +00005835 if (Lex.getKind() == lltok::MetadataVar) {
5836 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005837 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005838 }
Devang Patel8f842d32009-10-16 18:45:49 +00005839
Chris Lattner3822f632009-01-02 08:05:26 +00005840 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005841 ParseValue(Ty, Op0, PFS) ||
5842 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005843 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005844 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5845 return true;
5846 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005847
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 if (!Ty->isFirstClassType())
5849 return Error(TypeLoc, "phi node must have first class type");
5850
Jay Foad52131342011-03-30 11:28:46 +00005851 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005852 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5853 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5854 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005855 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005856}
5857
Bill Wendlingfae14752011-08-12 20:24:12 +00005858/// ParseLandingPad
5859/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5860/// Clause
5861/// ::= 'catch' TypeAndValue
5862/// ::= 'filter'
5863/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5864bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005865 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005866
David Majnemer7fddecc2015-06-17 20:52:32 +00005867 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005868 return true;
5869
David Majnemer7fddecc2015-06-17 20:52:32 +00005870 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005871 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5872
5873 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5874 LandingPadInst::ClauseType CT;
5875 if (EatIfPresent(lltok::kw_catch))
5876 CT = LandingPadInst::Catch;
5877 else if (EatIfPresent(lltok::kw_filter))
5878 CT = LandingPadInst::Filter;
5879 else
5880 return TokError("expected 'catch' or 'filter' clause type");
5881
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005882 Value *V;
5883 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005884 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005885 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005886
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005887 // A 'catch' type expects a non-array constant. A filter clause expects an
5888 // array constant.
5889 if (CT == LandingPadInst::Catch) {
5890 if (isa<ArrayType>(V->getType()))
5891 Error(VLoc, "'catch' clause has an invalid type");
5892 } else {
5893 if (!isa<ArrayType>(V->getType()))
5894 Error(VLoc, "'filter' clause has an invalid type");
5895 }
5896
Owen Andersonf8f259d2015-03-09 07:13:42 +00005897 Constant *CV = dyn_cast<Constant>(V);
5898 if (!CV)
5899 return Error(VLoc, "clause argument must be a constant");
5900 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005901 }
5902
Owen Andersonf8f259d2015-03-09 07:13:42 +00005903 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005904 return false;
5905}
5906
Chris Lattnerac161bf2009-01-02 07:01:27 +00005907/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005908/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5909/// OptionalAttrs Type Value ParameterList OptionalAttrs
5910/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5911/// OptionalAttrs Type Value ParameterList OptionalAttrs
5912/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5913/// OptionalAttrs Type Value ParameterList OptionalAttrs
5914/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5915/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005916bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005917 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005918 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005919 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005920 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005921 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005922 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005923 LocTy RetTypeLoc;
5924 ValID CalleeID;
5925 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005926 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005927 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005928
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005929 if (TCK != CallInst::TCK_None &&
5930 ParseToken(lltok::kw_call,
5931 "expected 'tail call', 'musttail call', or 'notail call'"))
5932 return true;
5933
5934 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5935
5936 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005937 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005938 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005939 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5940 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005941 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5942 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005944
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005945 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5946 return Error(CallLoc, "fast-math-flags specified for call without "
5947 "floating-point scalar or vector return type");
5948
Chris Lattnerac161bf2009-01-02 07:01:27 +00005949 // If RetType is a non-function pointer type, then this is the short syntax
5950 // for the call, which means that RetType is just the return type. Infer the
5951 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005952 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5953 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005954 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005955 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005956 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5957 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005958
Chris Lattnerac161bf2009-01-02 07:01:27 +00005959 if (!FunctionType::isValidReturnType(RetType))
5960 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005961
Owen Anderson4056ca92009-07-29 22:17:13 +00005962 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005963 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005964
David Blaikie41ba2b42015-07-27 23:32:19 +00005965 CalleeID.FTy = Ty;
5966
Chris Lattnerac161bf2009-01-02 07:01:27 +00005967 // Look up the callee.
5968 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005969 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5970 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005971
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005972 // Set up the Attribute for the function.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00005973 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005974
Chris Lattnerac161bf2009-01-02 07:01:27 +00005975 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Chris Lattnerac161bf2009-01-02 07:01:27 +00005977 // Loop through FunctionType's arguments and ensure they are specified
5978 // correctly. Also, gather any parameter attributes.
5979 FunctionType::param_iterator I = Ty->param_begin();
5980 FunctionType::param_iterator E = Ty->param_end();
5981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005982 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005983 if (I != E) {
5984 ExpectedTy = *I++;
5985 } else if (!Ty->isVarArg()) {
5986 return Error(ArgList[i].Loc, "too many arguments specified");
5987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005988
Chris Lattnerac161bf2009-01-02 07:01:27 +00005989 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5990 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005991 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 Args.push_back(ArgList[i].V);
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005993 Attrs.push_back(ArgList[i].Attrs);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005994 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005995
Chris Lattnerac161bf2009-01-02 07:01:27 +00005996 if (I != E)
5997 return Error(CallLoc, "not enough parameters specified for call");
5998
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00005999 if (FnAttrs.hasAlignmentAttr())
6000 return Error(CallLoc, "call instructions may not have an alignment");
David Majnemer8d22abd2015-02-23 00:01:32 +00006001
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006002 // Finish off the Attribute and check them
Reid Kleckner7f720332017-04-13 00:58:09 +00006003 AttributeList PAL =
6004 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6005 AttributeSet::get(Context, RetAttrs), Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006006
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006007 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006008 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006009 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006010 if (FMF.any())
6011 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006012 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006013 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006014 Inst = CI;
6015 return false;
6016}
6017
6018//===----------------------------------------------------------------------===//
6019// Memory Instructions.
6020//===----------------------------------------------------------------------===//
6021
6022/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006023/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6024/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006025int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006026 Value *Size = nullptr;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006027 LocTy SizeLoc, TyLoc, ASLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 unsigned Alignment = 0;
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006029 unsigned AddrSpace = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006030 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006031
6032 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006033 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006034
David Majnemera3b0eb22015-02-16 08:38:03 +00006035 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006036
David Majnemera3b0eb22015-02-16 08:38:03 +00006037 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6038 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006039
Chris Lattnerb2f39502009-12-30 05:44:30 +00006040 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006041 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006042 if (Lex.getKind() == lltok::kw_align) {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006043 if (ParseOptionalAlignment(Alignment))
6044 return true;
6045 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6046 return true;
6047 } else if (Lex.getKind() == lltok::kw_addrspace) {
6048 ASLoc = Lex.getLoc();
6049 if (ParseOptionalAddrSpace(AddrSpace))
6050 return true;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006051 } else if (Lex.getKind() == lltok::MetadataVar) {
6052 AteExtraComma = true;
6053 } else {
6054 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006055 ParseOptionalCommaAlign(Alignment, AteExtraComma) ||
6056 (!AteExtraComma &&
6057 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)))
David Majnemerc4ab61c2014-03-09 06:41:58 +00006058 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006059 }
6060 }
6061
Dan Gohman2140a742010-05-28 01:14:11 +00006062 if (Size && !Size->getType()->isIntegerTy())
6063 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006064
Matt Arsenault3c1fc762017-04-10 22:27:50 +00006065 const DataLayout &DL = M->getDataLayout();
6066 unsigned AS = DL.getAllocaAddrSpace();
6067 if (AS != AddrSpace) {
6068 // TODO: In the future it should be possible to specify addrspace per-alloca.
6069 return Error(ASLoc, "address space must match datalayout");
6070 }
6071
6072 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006073 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006074 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006075 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006076 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006077}
6078
6079/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006080/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006081/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006082/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006083int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006084 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006085 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006086 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006087 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006088 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006089 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006090
6091 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006092 isAtomic = true;
6093 Lex.Lex();
6094 }
6095
Chris Lattnerbc639292011-11-27 06:56:53 +00006096 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006097 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006098 isVolatile = true;
6099 Lex.Lex();
6100 }
6101
David Blaikie15d9a4c2015-04-06 20:59:48 +00006102 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006103 LocTy ExplicitTypeLoc = Lex.getLoc();
6104 if (ParseType(Ty) ||
6105 ParseToken(lltok::comma, "expected comma after load's type") ||
6106 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006107 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006108 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6109 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006110
David Blaikie15d9a4c2015-04-06 20:59:48 +00006111 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006112 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006113 if (isAtomic && !Alignment)
6114 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006115 if (Ordering == AtomicOrdering::Release ||
6116 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006117 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006118
David Blaikiea79ac142015-02-27 21:17:42 +00006119 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6120 return Error(ExplicitTypeLoc,
6121 "explicit pointee type doesn't match operand's pointee type");
6122
David Blaikie15d9a4c2015-04-06 20:59:48 +00006123 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006124 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006125}
6126
6127/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006128
6129/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6130/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006131/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006132int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006133 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006134 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006135 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006136 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006137 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006138 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006139
6140 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006141 isAtomic = true;
6142 Lex.Lex();
6143 }
6144
Chris Lattnerbc639292011-11-27 06:56:53 +00006145 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006146 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006147 isVolatile = true;
6148 Lex.Lex();
6149 }
6150
Chris Lattnerac161bf2009-01-02 07:01:27 +00006151 if (ParseTypeAndValue(Val, Loc, PFS) ||
6152 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006153 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006154 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006155 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006156 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006157
Duncan Sands19d0b472010-02-16 11:11:14 +00006158 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006159 return Error(PtrLoc, "store operand must be a pointer");
6160 if (!Val->getType()->isFirstClassType())
6161 return Error(Loc, "store operand must be a first class value");
6162 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6163 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006164 if (isAtomic && !Alignment)
6165 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006166 if (Ordering == AtomicOrdering::Acquire ||
6167 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006168 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006169
Eli Friedman59b66882011-08-09 23:02:53 +00006170 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006171 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006172}
6173
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006174/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006175/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6176/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006177int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006178 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6179 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006180 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6181 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006182 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006183 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006184 bool isWeak = false;
6185
6186 if (EatIfPresent(lltok::kw_weak))
6187 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006188
6189 if (EatIfPresent(lltok::kw_volatile))
6190 isVolatile = true;
6191
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006192 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6193 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6194 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6195 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6196 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006197 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6198 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006199 return true;
6200
JF Bastien800f87a2016-04-06 21:19:33 +00006201 if (SuccessOrdering == AtomicOrdering::Unordered ||
6202 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006203 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006204 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6205 return TokError("cmpxchg failure argument shall be no stronger than the "
6206 "success argument");
6207 if (FailureOrdering == AtomicOrdering::Release ||
6208 FailureOrdering == AtomicOrdering::AcquireRelease)
6209 return TokError(
6210 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006211 if (!Ptr->getType()->isPointerTy())
6212 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6213 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6214 return Error(CmpLoc, "compare value and pointer type do not match");
6215 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6216 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006217 if (!New->getType()->isFirstClassType())
6218 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006219 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6220 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006221 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006222 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006223 Inst = CXI;
6224 return AteExtraComma ? InstExtraComma : InstNormal;
6225}
6226
6227/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006228/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6229/// 'singlethread'? AtomicOrdering
6230int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006231 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6232 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006233 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006234 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006235 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006236 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006237
6238 if (EatIfPresent(lltok::kw_volatile))
6239 isVolatile = true;
6240
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006241 switch (Lex.getKind()) {
6242 default: return TokError("expected binary operation in atomicrmw");
6243 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6244 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6245 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6246 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6247 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6248 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6249 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6250 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6251 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6252 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6253 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6254 }
6255 Lex.Lex(); // Eat the operation.
6256
6257 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6258 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6259 ParseTypeAndValue(Val, ValLoc, PFS) ||
6260 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6261 return true;
6262
JF Bastien800f87a2016-04-06 21:19:33 +00006263 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006264 return TokError("atomicrmw cannot be unordered");
6265 if (!Ptr->getType()->isPointerTy())
6266 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6267 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6268 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6269 if (!Val->getType()->isIntegerTy())
6270 return Error(ValLoc, "atomicrmw operand must be an integer");
6271 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6272 if (Size < 8 || (Size & (Size - 1)))
6273 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6274 " integer");
6275
6276 AtomicRMWInst *RMWI =
6277 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6278 RMWI->setVolatile(isVolatile);
6279 Inst = RMWI;
6280 return AteExtraComma ? InstExtraComma : InstNormal;
6281}
6282
Eli Friedmanfee02c62011-07-25 23:16:38 +00006283/// ParseFence
6284/// ::= 'fence' 'singlethread'? AtomicOrdering
6285int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006286 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006287 SynchronizationScope Scope = CrossThread;
6288 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6289 return true;
6290
JF Bastien800f87a2016-04-06 21:19:33 +00006291 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006292 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006293 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006294 return TokError("fence cannot be monotonic");
6295
6296 Inst = new FenceInst(Context, Ordering, Scope);
6297 return InstNormal;
6298}
6299
Chris Lattnerac161bf2009-01-02 07:01:27 +00006300/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006301/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006302int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006303 Value *Ptr = nullptr;
6304 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006305 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006306
Dan Gohman16cbbe42009-07-29 15:58:36 +00006307 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006308
David Blaikie79e6c742015-02-27 19:29:02 +00006309 Type *Ty = nullptr;
6310 LocTy ExplicitTypeLoc = Lex.getLoc();
6311 if (ParseType(Ty) ||
6312 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6313 ParseTypeAndValue(Ptr, Loc, PFS))
6314 return true;
6315
Eli Benderskyd9806682013-04-22 17:03:42 +00006316 Type *BaseType = Ptr->getType();
6317 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6318 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006319 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006320
David Blaikie8d757942015-03-09 23:08:44 +00006321 if (Ty != BasePointerType->getElementType())
6322 return Error(ExplicitTypeLoc,
6323 "explicit pointee type doesn't match operand's pointee type");
6324
Chris Lattnerac161bf2009-01-02 07:01:27 +00006325 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006326 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006327 // GEP returns a vector of pointers if at least one of parameters is a vector.
6328 // All vector parameters should have the same vector width.
6329 unsigned GEPWidth = BaseType->isVectorTy() ?
6330 BaseType->getVectorNumElements() : 0;
6331
Chris Lattner3822f632009-01-02 08:05:26 +00006332 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006333 if (Lex.getKind() == lltok::MetadataVar) {
6334 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006335 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006336 }
Chris Lattner3822f632009-01-02 08:05:26 +00006337 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006338 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006339 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006340
Nadav Rotem3924cb02011-12-05 06:29:09 +00006341 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006342 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6343 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006344 return Error(EltLoc,
6345 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006346 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006347 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006348 Indices.push_back(Val);
6349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006350
Craig Toppere3dcce92015-08-01 22:20:21 +00006351 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006352 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006353 return Error(Loc, "base element of getelementptr must be sized");
6354
David Blaikied33bad32015-04-17 22:32:13 +00006355 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006356 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006357 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006358 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006359 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006360 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006361}
6362
6363/// ParseExtractValue
6364/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006365int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006366 Value *Val; LocTy Loc;
6367 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006368 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006369 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006370 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006371 return true;
6372
Chris Lattner392be582010-02-12 20:49:41 +00006373 if (!Val->getType()->isAggregateType())
6374 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006375
Jay Foad57aa6362011-07-13 10:26:04 +00006376 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006377 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006378 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006379 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006380}
6381
6382/// ParseInsertValue
6383/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006384int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006385 Value *Val0, *Val1; LocTy Loc0, Loc1;
6386 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006387 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006388 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6389 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6390 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006391 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006392 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006393
Chris Lattner392be582010-02-12 20:49:41 +00006394 if (!Val0->getType()->isAggregateType())
6395 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006396
David Majnemer30074532015-02-11 07:43:58 +00006397 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6398 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006399 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006400 if (IndexedType != Val1->getType())
6401 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6402 getTypeString(Val1->getType()) + "' instead of '" +
6403 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006404 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006405 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006406}
Nick Lewycky49f89192009-04-04 07:22:01 +00006407
6408//===----------------------------------------------------------------------===//
6409// Embedded metadata.
6410//===----------------------------------------------------------------------===//
6411
6412/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006413/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006414/// Element
6415/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006416bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006417 if (ParseToken(lltok::lbrace, "expected '{' here"))
6418 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006419
Dan Gohman1e0213a2010-07-13 19:33:27 +00006420 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006421 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006422 return false;
6423
Nick Lewycky49f89192009-04-04 07:22:01 +00006424 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006425 // Null is a special case since it is typeless.
6426 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006427 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006428 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006429 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006430
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006431 Metadata *MD;
6432 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006433 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006434 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006435 } while (EatIfPresent(lltok::comma));
6436
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006437 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006438}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006439
6440//===----------------------------------------------------------------------===//
6441// Use-list order directives.
6442//===----------------------------------------------------------------------===//
6443bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6444 SMLoc Loc) {
6445 if (V->use_empty())
6446 return Error(Loc, "value has no uses");
6447
6448 unsigned NumUses = 0;
6449 SmallDenseMap<const Use *, unsigned, 16> Order;
6450 for (const Use &U : V->uses()) {
6451 if (++NumUses > Indexes.size())
6452 break;
6453 Order[&U] = Indexes[NumUses - 1];
6454 }
6455 if (NumUses < 2)
6456 return Error(Loc, "value only has one use");
6457 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6458 return Error(Loc, "wrong number of indexes, expected " +
6459 Twine(std::distance(V->use_begin(), V->use_end())));
6460
6461 V->sortUseList([&](const Use &L, const Use &R) {
6462 return Order.lookup(&L) < Order.lookup(&R);
6463 });
6464 return false;
6465}
6466
6467/// ParseUseListOrderIndexes
6468/// ::= '{' uint32 (',' uint32)+ '}'
6469bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6470 SMLoc Loc = Lex.getLoc();
6471 if (ParseToken(lltok::lbrace, "expected '{' here"))
6472 return true;
6473 if (Lex.getKind() == lltok::rbrace)
6474 return Lex.Error("expected non-empty list of uselistorder indexes");
6475
6476 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6477 // indexes should be distinct numbers in the range [0, size-1], and should
6478 // not be in order.
6479 unsigned Offset = 0;
6480 unsigned Max = 0;
6481 bool IsOrdered = true;
6482 assert(Indexes.empty() && "Expected empty order vector");
6483 do {
6484 unsigned Index;
6485 if (ParseUInt32(Index))
6486 return true;
6487
6488 // Update consistency checks.
6489 Offset += Index - Indexes.size();
6490 Max = std::max(Max, Index);
6491 IsOrdered &= Index == Indexes.size();
6492
6493 Indexes.push_back(Index);
6494 } while (EatIfPresent(lltok::comma));
6495
6496 if (ParseToken(lltok::rbrace, "expected '}' here"))
6497 return true;
6498
6499 if (Indexes.size() < 2)
6500 return Error(Loc, "expected >= 2 uselistorder indexes");
6501 if (Offset != 0 || Max >= Indexes.size())
6502 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6503 if (IsOrdered)
6504 return Error(Loc, "expected uselistorder indexes to change the order");
6505
6506 return false;
6507}
6508
6509/// ParseUseListOrder
6510/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6511bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6512 SMLoc Loc = Lex.getLoc();
6513 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6514 return true;
6515
6516 Value *V;
6517 SmallVector<unsigned, 16> Indexes;
6518 if (ParseTypeAndValue(V, PFS) ||
6519 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6520 ParseUseListOrderIndexes(Indexes))
6521 return true;
6522
6523 return sortUseListOrder(V, Indexes, Loc);
6524}
6525
6526/// ParseUseListOrderBB
6527/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6528bool LLParser::ParseUseListOrderBB() {
6529 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6530 SMLoc Loc = Lex.getLoc();
6531 Lex.Lex();
6532
6533 ValID Fn, Label;
6534 SmallVector<unsigned, 16> Indexes;
6535 if (ParseValID(Fn) ||
6536 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6537 ParseValID(Label) ||
6538 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6539 ParseUseListOrderIndexes(Indexes))
6540 return true;
6541
6542 // Check the function.
6543 GlobalValue *GV;
6544 if (Fn.Kind == ValID::t_GlobalName)
6545 GV = M->getNamedValue(Fn.StrVal);
6546 else if (Fn.Kind == ValID::t_GlobalID)
6547 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6548 else
6549 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6550 if (!GV)
6551 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6552 auto *F = dyn_cast<Function>(GV);
6553 if (!F)
6554 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6555 if (F->isDeclaration())
6556 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6557
6558 // Check the basic block.
6559 if (Label.Kind == ValID::t_LocalID)
6560 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6561 if (Label.Kind != ValID::t_LocalName)
6562 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006563 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006564 if (!V)
6565 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6566 if (!isa<BasicBlock>(V))
6567 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6568
6569 return sortUseListOrder(V, Indexes, Loc);
6570}