blob: 0da81e42c68ce2ed447b06d7053b7b65ee9b20e9 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000016#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000017#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000018#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000021#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/ValueSymbolTable.h"
Philip Reames1960cfd2016-02-19 00:06:41 +000030#include "llvm/Support/Debug.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000031#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000033#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000034#include "llvm/Support/raw_ostream.h"
35using namespace llvm;
36
Chris Lattner229907c2011-07-18 04:54:35 +000037static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000038 std::string Result;
39 raw_string_ostream Tmp(Result);
40 Tmp << *T;
41 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000042}
43
Chris Lattner3822f632009-01-02 08:05:26 +000044/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000045bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000046 // Prime the lexer.
47 Lex.Lex();
48
Chris Lattnerad6f3352009-01-04 20:44:11 +000049 return ParseTopLevelEntities() ||
50 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000051}
52
Alex Lorenz1de2acd2015-08-21 21:32:39 +000053bool LLParser::parseStandaloneConstantValue(Constant *&C,
54 const SlotMapping *Slots) {
55 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000056 Lex.Lex();
57
58 Type *Ty = nullptr;
59 if (ParseType(Ty) || parseConstantValue(Ty, C))
60 return true;
61 if (Lex.getKind() != lltok::Eof)
62 return Error(Lex.getLoc(), "expected end of string");
63 return false;
64}
65
Quentin Colombetdafed5d2016-03-08 00:37:07 +000066bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
67 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000068 restoreParsingState(Slots);
69 Lex.Lex();
70
Quentin Colombetdafed5d2016-03-08 00:37:07 +000071 Read = 0;
72 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000073 Ty = nullptr;
74 if (ParseType(Ty))
75 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +000076 SMLoc End = Lex.getLoc();
77 Read = End.getPointer() - Start.getPointer();
78
Quentin Colombet81e72b42016-03-07 22:09:05 +000079 return false;
80}
81
Alex Lorenz1de2acd2015-08-21 21:32:39 +000082void LLParser::restoreParsingState(const SlotMapping *Slots) {
83 if (!Slots)
84 return;
85 NumberedVals = Slots->GlobalValues;
86 NumberedMetadata = Slots->MetadataNodes;
87 for (const auto &I : Slots->NamedTypes)
88 NamedTypes.insert(
89 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
90 for (const auto &I : Slots->Types)
91 NumberedTypes.insert(
92 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
93}
94
Chris Lattnerac161bf2009-01-02 07:01:27 +000095/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
96/// module.
97bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000098 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
99 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
100
Bill Wendlingb32b0412013-02-08 06:32:06 +0000101 // Handle any function attribute group forward references.
102 for (std::map<Value*, std::vector<unsigned> >::iterator
103 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
104 I != E; ++I) {
105 Value *V = I->first;
106 std::vector<unsigned> &Vec = I->second;
107 AttrBuilder B;
108
109 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
110 VI != VE; ++VI)
111 B.merge(NumberedAttrBuilders[*VI]);
112
113 if (Function *Fn = dyn_cast<Function>(V)) {
114 AttributeSet AS = Fn->getAttributes();
115 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
116 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
117 AS.getFnAttributes());
118
119 FnAttrs.merge(B);
120
121 // If the alignment was parsed as an attribute, move to the alignment
122 // field.
123 if (FnAttrs.hasAlignmentAttr()) {
124 Fn->setAlignment(FnAttrs.getAlignment());
125 FnAttrs.removeAttribute(Attribute::Alignment);
126 }
127
128 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
129 AttributeSet::get(Context,
130 AttributeSet::FunctionIndex,
131 FnAttrs));
132 Fn->setAttributes(AS);
133 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
134 AttributeSet AS = CI->getAttributes();
135 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
136 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
137 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000138 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000139 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
140 AttributeSet::get(Context,
141 AttributeSet::FunctionIndex,
142 FnAttrs));
143 CI->setAttributes(AS);
144 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
145 AttributeSet AS = II->getAttributes();
146 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
147 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
148 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000149 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000150 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
151 AttributeSet::get(Context,
152 AttributeSet::FunctionIndex,
153 FnAttrs));
154 II->setAttributes(AS);
155 } else {
156 llvm_unreachable("invalid object with forward attribute group reference");
157 }
158 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000159
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000160 // If there are entries in ForwardRefBlockAddresses at this point, the
161 // function was never defined.
162 if (!ForwardRefBlockAddresses.empty())
163 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
164 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000165
David Majnemer19b51052015-02-11 07:43:56 +0000166 for (const auto &NT : NumberedTypes)
167 if (NT.second.second.isValid())
168 return Error(NT.second.second,
169 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170
171 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
172 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
173 if (I->second.second.isValid())
174 return Error(I->second.second,
175 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000176
David Majnemerdad0a642014-06-27 18:19:56 +0000177 if (!ForwardRefComdats.empty())
178 return Error(ForwardRefComdats.begin()->second,
179 "use of undefined comdat '$" +
180 ForwardRefComdats.begin()->first + "'");
181
Chris Lattnerac161bf2009-01-02 07:01:27 +0000182 if (!ForwardRefVals.empty())
183 return Error(ForwardRefVals.begin()->second.second,
184 "use of undefined value '@" + ForwardRefVals.begin()->first +
185 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000186
Chris Lattnerac161bf2009-01-02 07:01:27 +0000187 if (!ForwardRefValIDs.empty())
188 return Error(ForwardRefValIDs.begin()->second.second,
189 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000190 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000191
Devang Pateld2541152009-07-08 19:23:54 +0000192 if (!ForwardRefMDNodes.empty())
193 return Error(ForwardRefMDNodes.begin()->second.second,
194 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000195 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000196
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000197 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000198 for (auto &N : NumberedMetadata) {
199 if (N.second && !N.second->isResolved())
200 N.second->resolveCycles();
201 }
Devang Pateld2541152009-07-08 19:23:54 +0000202
Chris Lattnerac161bf2009-01-02 07:01:27 +0000203 // Look for intrinsic functions and CallInst that need to be upgraded
204 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000205 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000206
Manman Ren8b4306c2013-12-02 21:29:56 +0000207 UpgradeDebugInfo(*M);
208
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000209 if (!Slots)
210 return false;
211 // Initialize the slot mapping.
212 // Because by this point we've parsed and validated everything, we can "steal"
213 // the mapping from LLParser as it doesn't need it anymore.
214 Slots->GlobalValues = std::move(NumberedVals);
215 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000216 for (const auto &I : NamedTypes)
217 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
218 for (const auto &I : NumberedTypes)
219 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000220
Chris Lattnerac161bf2009-01-02 07:01:27 +0000221 return false;
222}
223
224//===----------------------------------------------------------------------===//
225// Top-Level Entities
226//===----------------------------------------------------------------------===//
227
228bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000229 while (1) {
230 switch (Lex.getKind()) {
231 default: return TokError("expected top-level entity");
232 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000233 case lltok::kw_declare: if (ParseDeclare()) return true; break;
234 case lltok::kw_define: if (ParseDefine()) return true; break;
235 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
236 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000237 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000238 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000239 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000240 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000241 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000242 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000243 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000244 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000245
246 // The Global variable production with no name can have many different
247 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000248 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000249 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000250 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000251 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000252 case lltok::kw_internal: // OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000258 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000259 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000260 case lltok::kw_external: // OptionalLinkage
261 case lltok::kw_default: // OptionalVisibility
262 case lltok::kw_hidden: // OptionalVisibility
263 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000264 case lltok::kw_dllimport: // OptionalDLLStorageClass
265 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000266 case lltok::kw_thread_local: // OptionalThreadLocal
267 case lltok::kw_addrspace: // OptionalAddrSpace
268 case lltok::kw_constant: // GlobalType
269 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000270 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000271 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000272 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000273 bool HasLinkage;
274 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000275 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000276 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000277 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000278 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000279 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000280 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000281 return true;
282 break;
283 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000284
285 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000286 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
287 case lltok::kw_uselistorder_bb:
288 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000289 }
290 }
291}
292
293
294/// toplevelentity
295/// ::= 'module' 'asm' STRINGCONSTANT
296bool LLParser::ParseModuleAsm() {
297 assert(Lex.getKind() == lltok::kw_module);
298 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000299
300 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000301 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
302 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000303
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000304 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000305 return false;
306}
307
308/// toplevelentity
309/// ::= 'target' 'triple' '=' STRINGCONSTANT
310/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
311bool LLParser::ParseTargetDefinition() {
312 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000313 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000314 switch (Lex.Lex()) {
315 default: return TokError("unknown target property");
316 case lltok::kw_triple:
317 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000318 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
319 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000321 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000322 return false;
323 case lltok::kw_datalayout:
324 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000325 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
326 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000328 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000329 return false;
330 }
331}
332
Bill Wendling706d3d62012-11-28 08:41:48 +0000333/// toplevelentity
334/// ::= 'deplibs' '=' '[' ']'
335/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
336/// FIXME: Remove in 4.0. Currently parse, but ignore.
337bool LLParser::ParseDepLibs() {
338 assert(Lex.getKind() == lltok::kw_deplibs);
339 Lex.Lex();
340 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
341 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
342 return true;
343
344 if (EatIfPresent(lltok::rsquare))
345 return false;
346
347 do {
348 std::string Str;
349 if (ParseStringConstant(Str)) return true;
350 } while (EatIfPresent(lltok::comma));
351
352 return ParseToken(lltok::rsquare, "expected ']' at end of list");
353}
354
Dan Gohman466876b2009-08-12 23:32:33 +0000355/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000356/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000357bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000358 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000359 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000360 Lex.Lex(); // eat LocalVarID;
361
362 if (ParseToken(lltok::equal, "expected '=' after name") ||
363 ParseToken(lltok::kw_type, "expected 'type' after '='"))
364 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000365
Craig Topper2617dcc2014-04-15 06:32:26 +0000366 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000367 if (ParseStructDefinition(TypeLoc, "",
368 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000369
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000370 if (!isa<StructType>(Result)) {
371 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
372 if (Entry.first)
373 return Error(TypeLoc, "non-struct types may not be recursive");
374 Entry.first = Result;
375 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000376 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000377
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 return false;
379}
380
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000381
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382/// toplevelentity
383/// ::= LocalVar '=' 'type' type
384bool LLParser::ParseNamedType() {
385 std::string Name = Lex.getStrVal();
386 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000387 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000388
Chris Lattner3822f632009-01-02 08:05:26 +0000389 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000390 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000391 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000392
Craig Topper2617dcc2014-04-15 06:32:26 +0000393 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000394 if (ParseStructDefinition(NameLoc, Name,
395 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000396
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000397 if (!isa<StructType>(Result)) {
398 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
399 if (Entry.first)
400 return Error(NameLoc, "non-struct types may not be recursive");
401 Entry.first = Result;
402 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000403 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000406}
407
408
409/// toplevelentity
410/// ::= 'declare' FunctionHeader
411bool LLParser::ParseDeclare() {
412 assert(Lex.getKind() == lltok::kw_declare);
413 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000414
Chris Lattnerac161bf2009-01-02 07:01:27 +0000415 Function *F;
416 return ParseFunctionHeader(F, false);
417}
418
419/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000420/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000421bool LLParser::ParseDefine() {
422 assert(Lex.getKind() == lltok::kw_define);
423 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000424
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000426 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000427 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000428 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429}
430
Chris Lattner3822f632009-01-02 08:05:26 +0000431/// ParseGlobalType
432/// ::= 'constant'
433/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000434bool LLParser::ParseGlobalType(bool &IsConstant) {
435 if (Lex.getKind() == lltok::kw_constant)
436 IsConstant = true;
437 else if (Lex.getKind() == lltok::kw_global)
438 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000439 else {
440 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000441 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000442 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 Lex.Lex();
444 return false;
445}
446
Dan Gohman466876b2009-08-12 23:32:33 +0000447/// ParseUnnamedGlobal:
448/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000449/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
450/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000451/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000452/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000454bool LLParser::ParseUnnamedGlobal() {
455 unsigned VarID = NumberedVals.size();
456 std::string Name;
457 LocTy NameLoc = Lex.getLoc();
458
459 // Handle the GlobalID form.
460 if (Lex.getKind() == lltok::GlobalID) {
461 if (Lex.getUIntVal() != VarID)
462 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000463 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000464 Lex.Lex(); // eat GlobalID;
465
466 if (ParseToken(lltok::equal, "expected '=' after name"))
467 return true;
468 }
469
470 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000471 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000472 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000473 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000474 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000475 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000476 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000477 ParseOptionalThreadLocal(TLM) ||
478 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000479 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000480
Rafael Espindola464fe022014-07-30 22:51:54 +0000481 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000482 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000483 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000484 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000485 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000486}
487
Chris Lattnerac161bf2009-01-02 07:01:27 +0000488/// ParseNamedGlobal:
489/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000490/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
491/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000492bool LLParser::ParseNamedGlobal() {
493 assert(Lex.getKind() == lltok::GlobalVar);
494 LocTy NameLoc = Lex.getLoc();
495 std::string Name = Lex.getStrVal();
496 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000497
Chris Lattnerac161bf2009-01-02 07:01:27 +0000498 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000499 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000500 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000501 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000502 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
503 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000504 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000505 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000506 ParseOptionalThreadLocal(TLM) ||
507 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000508 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000509
Rafael Espindola464fe022014-07-30 22:51:54 +0000510 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000511 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000512 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000513
514 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000515 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000516}
517
David Majnemerdad0a642014-06-27 18:19:56 +0000518bool LLParser::parseComdat() {
519 assert(Lex.getKind() == lltok::ComdatVar);
520 std::string Name = Lex.getStrVal();
521 LocTy NameLoc = Lex.getLoc();
522 Lex.Lex();
523
524 if (ParseToken(lltok::equal, "expected '=' here"))
525 return true;
526
527 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
528 return TokError("expected comdat type");
529
530 Comdat::SelectionKind SK;
531 switch (Lex.getKind()) {
532 default:
533 return TokError("unknown selection kind");
534 case lltok::kw_any:
535 SK = Comdat::Any;
536 break;
537 case lltok::kw_exactmatch:
538 SK = Comdat::ExactMatch;
539 break;
540 case lltok::kw_largest:
541 SK = Comdat::Largest;
542 break;
543 case lltok::kw_noduplicates:
544 SK = Comdat::NoDuplicates;
545 break;
546 case lltok::kw_samesize:
547 SK = Comdat::SameSize;
548 break;
549 }
550 Lex.Lex();
551
552 // See if the comdat was forward referenced, if so, use the comdat.
553 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
554 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
555 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
556 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
557
558 Comdat *C;
559 if (I != ComdatSymTab.end())
560 C = &I->second;
561 else
562 C = M->getOrInsertComdat(Name);
563 C->setSelectionKind(SK);
564
565 return false;
566}
567
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000568// MDString:
569// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000570bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000571 std::string Str;
572 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000573 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000574 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000575 return false;
576}
577
578// MDNode:
579// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000580bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000581 // !{ ..., !42, ... }
582 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000583 if (ParseUInt32(MID))
584 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000585
Chris Lattner8eff0152010-04-01 05:14:45 +0000586 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000587 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000588 Result = NumberedMetadata[MID];
589 return false;
590 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000591
Chris Lattner8eff0152010-04-01 05:14:45 +0000592 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000593 auto &FwdRef = ForwardRefMDNodes[MID];
594 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000595
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000596 Result = FwdRef.first.get();
597 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000598 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000599}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000600
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000601/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000602/// !foo = !{ !1, !2 }
603bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000604 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000605 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000606 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000607
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000608 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000609 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000610 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000611 return true;
612
Dan Gohman2637cc12010-07-21 23:38:33 +0000613 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000614 if (Lex.getKind() != lltok::rbrace)
615 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000616 if (ParseToken(lltok::exclaim, "Expected '!' here"))
617 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000618
Craig Topper2617dcc2014-04-15 06:32:26 +0000619 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000620 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000621 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000622 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000623
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000624 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000625}
626
Devang Patel39e64d42009-07-01 19:21:12 +0000627/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000628/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000629bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000630 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000631 Lex.Lex();
632 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000633
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000634 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000635 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000636 ParseToken(lltok::equal, "expected '=' here"))
637 return true;
638
639 // Detect common error, from old metadata syntax.
640 if (Lex.getKind() == lltok::Type)
641 return TokError("unexpected type in metadata definition");
642
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000643 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000644 if (Lex.getKind() == lltok::MetadataVar) {
645 if (ParseSpecializedMDNode(Init, IsDistinct))
646 return true;
647 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
648 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000649 return true;
650
Chris Lattnerfc58af22009-12-30 04:51:58 +0000651 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000652 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000653 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000654 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000655 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000656
Chris Lattnerfc58af22009-12-30 04:51:58 +0000657 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
658 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000659 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000660 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000661 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000662 }
663
Devang Patel39e64d42009-07-01 19:21:12 +0000664 return false;
665}
666
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000667static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
668 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
669 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
670}
671
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000673/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
674/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000675/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000676///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000678/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000679///
Eric Christopher536f0a92015-05-28 23:07:39 +0000680/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000681///
Rafael Espindola464fe022014-07-30 22:51:54 +0000682bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000683 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000684 GlobalVariable::ThreadLocalMode TLM,
685 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000686 assert(Lex.getKind() == lltok::kw_alias);
687 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000688
Rafael Espindola78527052013-10-06 15:10:43 +0000689 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
690
Rafael Espindolacaa43562013-10-09 16:07:32 +0000691 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000692 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000693
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000694 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000695 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000696 "symbol with local linkage must have default visibility");
697
David Blaikie2f408302015-09-11 03:22:04 +0000698 Type *Ty;
699 LocTy ExplicitTypeLoc = Lex.getLoc();
700 if (ParseType(Ty) ||
701 ParseToken(lltok::comma, "expected comma after alias's type"))
702 return true;
703
Rafael Espindola64c1e182014-06-03 02:41:57 +0000704 Constant *Aliasee;
705 LocTy AliaseeLoc = Lex.getLoc();
706 if (Lex.getKind() != lltok::kw_bitcast &&
707 Lex.getKind() != lltok::kw_getelementptr &&
708 Lex.getKind() != lltok::kw_addrspacecast &&
709 Lex.getKind() != lltok::kw_inttoptr) {
710 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000711 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000713 // The bitcast dest type is not present, it is implied by the dest type.
714 ValID ID;
715 if (ParseValID(ID))
716 return true;
717 if (ID.Kind != ValID::t_Constant)
718 return Error(AliaseeLoc, "invalid aliasee");
719 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000721
Rafael Espindola64c1e182014-06-03 02:41:57 +0000722 Type *AliaseeType = Aliasee->getType();
723 auto *PTy = dyn_cast<PointerType>(AliaseeType);
724 if (!PTy)
725 return Error(AliaseeLoc, "An alias must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000726 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000727
David Blaikie2f408302015-09-11 03:22:04 +0000728 if (Ty != PTy->getElementType())
729 return Error(
730 ExplicitTypeLoc,
731 "explicit pointee type doesn't match operand's pointee type");
732
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000733 GlobalValue *GVal = nullptr;
734
735 // See if the alias was forward referenced, if so, prepare to replace the
736 // forward reference.
737 if (!Name.empty()) {
738 GVal = M->getNamedValue(Name);
739 if (GVal) {
740 if (!ForwardRefVals.erase(Name))
741 return Error(NameLoc, "redefinition of global '@" + Name + "'");
742 }
743 } else {
744 auto I = ForwardRefValIDs.find(NumberedVals.size());
745 if (I != ForwardRefValIDs.end()) {
746 GVal = I->second.first;
747 ForwardRefValIDs.erase(I);
748 }
749 }
750
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000752 std::unique_ptr<GlobalAlias> GA(
David Blaikie16a2f3e2015-09-14 18:01:59 +0000753 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
754 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000755 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000757 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000758 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
Rafael Espindola54fc2982015-06-17 17:53:31 +0000760 if (Name.empty())
761 NumberedVals.push_back(GA.get());
762
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000763 if (GVal) {
764 // Verify that types agree.
765 if (GVal->getType() != GA->getType())
766 return Error(
767 ExplicitTypeLoc,
768 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
Chris Lattnerac161bf2009-01-02 07:01:27 +0000770 // If they agree, just RAUW the old value with the alias and remove the
771 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000772 GVal->replaceAllUsesWith(GA.get());
773 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000775
Chris Lattnerac161bf2009-01-02 07:01:27 +0000776 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000777 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000778 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000779
Rafael Espindolaaa273822014-05-09 21:49:17 +0000780 // The module owns this now
781 GA.release();
782
Chris Lattnerac161bf2009-01-02 07:01:27 +0000783 return false;
784}
785
786/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000787/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000788/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000789/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000790/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000791/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000792/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000793///
Eric Christopher536f0a92015-05-28 23:07:39 +0000794/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000795/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000796///
797bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
798 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000799 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000800 GlobalVariable::ThreadLocalMode TLM,
801 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000802 if (!isValidVisibilityForLinkage(Visibility, Linkage))
803 return Error(NameLoc,
804 "symbol with local linkage must have default visibility");
805
Chris Lattnerac161bf2009-01-02 07:01:27 +0000806 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000807 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000808 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000809 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000810
Craig Topper2617dcc2014-04-15 06:32:26 +0000811 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000812 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000813 ParseOptionalToken(lltok::kw_externally_initialized,
814 IsExternallyInitialized,
815 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000816 ParseGlobalType(IsConstant) ||
817 ParseType(Ty, TyLoc))
818 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000819
Chris Lattnerac161bf2009-01-02 07:01:27 +0000820 // If the linkage is specified and is external, then no initializer is
821 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000822 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000823 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000824 Linkage != GlobalValue::ExternalLinkage)) {
825 if (ParseGlobalValue(Ty, Init))
826 return true;
827 }
828
David Majnemer49b3d9b2015-02-16 08:41:08 +0000829 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000830 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
David Majnemer598bd052014-12-09 05:56:09 +0000832 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833
834 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000835 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000836 GVal = M->getNamedValue(Name);
837 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000838 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000839 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000840 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000841 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000842 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000843 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000844 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000845 ForwardRefValIDs.erase(I);
846 }
847 }
848
David Majnemer598bd052014-12-09 05:56:09 +0000849 GlobalVariable *GV;
850 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000851 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
852 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000853 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000854 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000855 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000856 return Error(TyLoc,
857 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000858
David Majnemer598bd052014-12-09 05:56:09 +0000859 GV = cast<GlobalVariable>(GVal);
860
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 // Move the forward-reference to the correct spot in the module.
862 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
863 }
864
865 if (Name.empty())
866 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000867
Chris Lattnerac161bf2009-01-02 07:01:27 +0000868 // Set the parsed properties on the global.
869 if (Init)
870 GV->setInitializer(Init);
871 GV->setConstant(IsConstant);
872 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
873 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000874 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000875 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000876 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000877 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000878
Chris Lattnerac161bf2009-01-02 07:01:27 +0000879 // Parse attributes on the global.
880 while (Lex.getKind() == lltok::comma) {
881 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Chris Lattnerac161bf2009-01-02 07:01:27 +0000883 if (Lex.getKind() == lltok::kw_section) {
884 Lex.Lex();
885 GV->setSection(Lex.getStrVal());
886 if (ParseToken(lltok::StringConstant, "expected global section string"))
887 return true;
888 } else if (Lex.getKind() == lltok::kw_align) {
889 unsigned Alignment;
890 if (ParseOptionalAlignment(Alignment)) return true;
891 GV->setAlignment(Alignment);
892 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000893 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000894 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000895 return true;
896 if (C)
897 GV->setComdat(C);
898 else
899 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000900 }
901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000902
Chris Lattnerac161bf2009-01-02 07:01:27 +0000903 return false;
904}
905
Bill Wendling63b88192013-02-06 06:52:58 +0000906/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000907/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000908bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000909 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000910 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000911 Lex.Lex();
912
David Majnemerb39e22b2014-12-09 18:33:57 +0000913 if (Lex.getKind() != lltok::AttrGrpID)
914 return TokError("expected attribute group id");
915
Bill Wendling63b88192013-02-06 06:52:58 +0000916 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000917 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000918 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000919 Lex.Lex();
920
921 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000922 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000923 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000924 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000925 ParseToken(lltok::rbrace, "expected end of attribute group"))
926 return true;
927
Bill Wendlingb32b0412013-02-08 06:32:06 +0000928 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000929 return Error(AttrGrpLoc, "attribute group has no attributes");
930
931 return false;
932}
933
Bill Wendling8b0321d2013-02-08 00:52:31 +0000934/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000935/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000936bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
937 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000938 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 bool HaveError = false;
940
941 B.clear();
942
Bill Wendling63b88192013-02-06 06:52:58 +0000943 while (true) {
944 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000945 if (Token == lltok::kw_builtin)
946 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000947 switch (Token) {
948 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000949 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000950 return Error(Lex.getLoc(), "unterminated attribute group");
951 case lltok::rbrace:
952 // Finished.
953 return false;
954
Bill Wendlingb32b0412013-02-08 06:32:06 +0000955 case lltok::AttrGrpID: {
956 // Allow a function to reference an attribute group:
957 //
958 // define void @foo() #1 { ... }
959 if (inAttrGrp)
960 HaveError |=
961 Error(Lex.getLoc(),
962 "cannot have an attribute group reference in an attribute group");
963
964 unsigned AttrGrpNum = Lex.getUIntVal();
965 if (inAttrGrp) break;
966
967 // Save the reference to the attribute group. We'll fill it in later.
968 FwdRefAttrGrps.push_back(AttrGrpNum);
969 break;
970 }
Bill Wendling63b88192013-02-06 06:52:58 +0000971 // Target-dependent attributes:
972 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +0000973 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +0000974 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000975 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000976 }
977
978 // Target-independent attributes:
979 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000980 // As a hack, we allow function alignment to be initially parsed as an
981 // attribute on a function declaration/definition or added to an attribute
982 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000983 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000984 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000985 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000986 if (ParseToken(lltok::equal, "expected '=' here") ||
987 ParseUInt32(Alignment))
988 return true;
989 } else {
990 if (ParseOptionalAlignment(Alignment))
991 return true;
992 }
Bill Wendling63b88192013-02-06 06:52:58 +0000993 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000994 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000995 }
996 case lltok::kw_alignstack: {
997 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000998 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000999 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001000 if (ParseToken(lltok::equal, "expected '=' here") ||
1001 ParseUInt32(Alignment))
1002 return true;
1003 } else {
1004 if (ParseOptionalStackAlignment(Alignment))
1005 return true;
1006 }
Bill Wendling63b88192013-02-06 06:52:58 +00001007 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001008 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001009 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001010 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1011 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1012 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1013 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1014 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001015 case lltok::kw_inaccessiblememonly:
1016 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1017 case lltok::kw_inaccessiblemem_or_argmemonly:
1018 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001019 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1020 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1021 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1022 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1023 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1024 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1025 case lltok::kw_noimplicitfloat:
1026 B.addAttribute(Attribute::NoImplicitFloat); break;
1027 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1028 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1029 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1030 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001031 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001032 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1033 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1034 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1035 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1036 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1037 case lltok::kw_returns_twice:
1038 B.addAttribute(Attribute::ReturnsTwice); break;
1039 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1040 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1041 case lltok::kw_sspstrong:
1042 B.addAttribute(Attribute::StackProtectStrong); break;
1043 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1044 case lltok::kw_sanitize_address:
1045 B.addAttribute(Attribute::SanitizeAddress); break;
1046 case lltok::kw_sanitize_thread:
1047 B.addAttribute(Attribute::SanitizeThread); break;
1048 case lltok::kw_sanitize_memory:
1049 B.addAttribute(Attribute::SanitizeMemory); break;
1050 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001051
1052 // Error handling.
1053 case lltok::kw_inreg:
1054 case lltok::kw_signext:
1055 case lltok::kw_zeroext:
1056 HaveError |=
1057 Error(Lex.getLoc(),
1058 "invalid use of attribute on a function");
1059 break;
1060 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001061 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001062 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001063 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001064 case lltok::kw_nest:
1065 case lltok::kw_noalias:
1066 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001067 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001068 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001069 case lltok::kw_sret:
1070 HaveError |=
1071 Error(Lex.getLoc(),
1072 "invalid use of parameter-only attribute on a function");
1073 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001074 }
1075
1076 Lex.Lex();
1077 }
1078}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001079
1080//===----------------------------------------------------------------------===//
1081// GlobalValue Reference/Resolution Routines.
1082//===----------------------------------------------------------------------===//
1083
Karl Schimpf77729782015-09-03 18:06:44 +00001084static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1085 const std::string &Name) {
1086 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1087 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1088 else
1089 return new GlobalVariable(*M, PTy->getElementType(), false,
1090 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1091 nullptr, GlobalVariable::NotThreadLocal,
1092 PTy->getAddressSpace());
1093}
1094
Chris Lattnerac161bf2009-01-02 07:01:27 +00001095/// GetGlobalVal - Get a value with the specified name or ID, creating a
1096/// forward reference record if needed. This can return null if the value
1097/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001098GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001099 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001100 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001101 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001102 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001103 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001105
Chris Lattnerac161bf2009-01-02 07:01:27 +00001106 // Look this name up in the normal function symbol table.
1107 GlobalValue *Val =
1108 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001109
Chris Lattnerac161bf2009-01-02 07:01:27 +00001110 // If this is a forward reference for the value, see if we already created a
1111 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001112 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001113 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001114 if (I != ForwardRefVals.end())
1115 Val = I->second.first;
1116 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001117
Chris Lattnerac161bf2009-01-02 07:01:27 +00001118 // If we have the value in the symbol table or fwd-ref table, return it.
1119 if (Val) {
1120 if (Val->getType() == Ty) return Val;
1121 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001122 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001123 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001125
Chris Lattnerac161bf2009-01-02 07:01:27 +00001126 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001127 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001128 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1129 return FwdVal;
1130}
1131
Chris Lattner229907c2011-07-18 04:54:35 +00001132GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1133 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001134 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001135 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001136 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001137 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001138
Craig Topper2617dcc2014-04-15 06:32:26 +00001139 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001140
Chris Lattnerac161bf2009-01-02 07:01:27 +00001141 // If this is a forward reference for the value, see if we already created a
1142 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001143 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001144 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001145 if (I != ForwardRefValIDs.end())
1146 Val = I->second.first;
1147 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001148
Chris Lattnerac161bf2009-01-02 07:01:27 +00001149 // If we have the value in the symbol table or fwd-ref table, return it.
1150 if (Val) {
1151 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001152 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001153 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001154 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001156
Chris Lattnerac161bf2009-01-02 07:01:27 +00001157 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001158 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001159 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1160 return FwdVal;
1161}
1162
1163
1164//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001165// Comdat Reference/Resolution Routines.
1166//===----------------------------------------------------------------------===//
1167
1168Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1169 // Look this name up in the comdat symbol table.
1170 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1171 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1172 if (I != ComdatSymTab.end())
1173 return &I->second;
1174
1175 // Otherwise, create a new forward reference for this value and remember it.
1176 Comdat *C = M->getOrInsertComdat(Name);
1177 ForwardRefComdats[Name] = Loc;
1178 return C;
1179}
1180
1181
1182//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001183// Helper Routines.
1184//===----------------------------------------------------------------------===//
1185
1186/// ParseToken - If the current token has the specified kind, eat it and return
1187/// success. Otherwise, emit the specified error and return failure.
1188bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1189 if (Lex.getKind() != T)
1190 return TokError(ErrMsg);
1191 Lex.Lex();
1192 return false;
1193}
1194
Chris Lattner3822f632009-01-02 08:05:26 +00001195/// ParseStringConstant
1196/// ::= StringConstant
1197bool LLParser::ParseStringConstant(std::string &Result) {
1198 if (Lex.getKind() != lltok::StringConstant)
1199 return TokError("expected string constant");
1200 Result = Lex.getStrVal();
1201 Lex.Lex();
1202 return false;
1203}
1204
1205/// ParseUInt32
1206/// ::= uint32
1207bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1209 return TokError("expected integer");
1210 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1211 if (Val64 != unsigned(Val64))
1212 return TokError("expected 32-bit integer (too large)");
1213 Val = Val64;
1214 Lex.Lex();
1215 return false;
1216}
1217
Hal Finkelb0407ba2014-07-18 15:51:28 +00001218/// ParseUInt64
1219/// ::= uint64
1220bool LLParser::ParseUInt64(uint64_t &Val) {
1221 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1222 return TokError("expected integer");
1223 Val = Lex.getAPSIntVal().getLimitedValue();
1224 Lex.Lex();
1225 return false;
1226}
1227
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001228/// ParseTLSModel
1229/// := 'localdynamic'
1230/// := 'initialexec'
1231/// := 'localexec'
1232bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1233 switch (Lex.getKind()) {
1234 default:
1235 return TokError("expected localdynamic, initialexec or localexec");
1236 case lltok::kw_localdynamic:
1237 TLM = GlobalVariable::LocalDynamicTLSModel;
1238 break;
1239 case lltok::kw_initialexec:
1240 TLM = GlobalVariable::InitialExecTLSModel;
1241 break;
1242 case lltok::kw_localexec:
1243 TLM = GlobalVariable::LocalExecTLSModel;
1244 break;
1245 }
1246
1247 Lex.Lex();
1248 return false;
1249}
1250
1251/// ParseOptionalThreadLocal
1252/// := /*empty*/
1253/// := 'thread_local'
1254/// := 'thread_local' '(' tlsmodel ')'
1255bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1256 TLM = GlobalVariable::NotThreadLocal;
1257 if (!EatIfPresent(lltok::kw_thread_local))
1258 return false;
1259
1260 TLM = GlobalVariable::GeneralDynamicTLSModel;
1261 if (Lex.getKind() == lltok::lparen) {
1262 Lex.Lex();
1263 return ParseTLSModel(TLM) ||
1264 ParseToken(lltok::rparen, "expected ')' after thread local model");
1265 }
1266 return false;
1267}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001268
1269/// ParseOptionalAddrSpace
1270/// := /*empty*/
1271/// := 'addrspace' '(' uint32 ')'
1272bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1273 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001274 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001275 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001276 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001277 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001278 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001279}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001280
Artur Pilipenko17376c42015-08-03 14:31:49 +00001281/// ParseStringAttribute
1282/// := StringConstant
1283/// := StringConstant '=' StringConstant
1284bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1285 std::string Attr = Lex.getStrVal();
1286 Lex.Lex();
1287 std::string Val;
1288 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1289 return true;
1290 B.addAttribute(Attr, Val);
1291 return false;
1292}
1293
Bill Wendling34c2eb22012-12-04 23:40:58 +00001294/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1295bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1296 bool HaveError = false;
1297
1298 B.clear();
1299
1300 while (1) {
1301 lltok::Kind Token = Lex.getKind();
1302 switch (Token) {
1303 default: // End of attributes.
1304 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001305 case lltok::StringConstant: {
1306 if (ParseStringAttribute(B))
1307 return true;
1308 continue;
1309 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001310 case lltok::kw_align: {
1311 unsigned Alignment;
1312 if (ParseOptionalAlignment(Alignment))
1313 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001314 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001315 continue;
1316 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001317 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001318 case lltok::kw_dereferenceable: {
1319 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001320 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001321 return true;
1322 B.addDereferenceableAttr(Bytes);
1323 continue;
1324 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001325 case lltok::kw_dereferenceable_or_null: {
1326 uint64_t Bytes;
1327 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1328 return true;
1329 B.addDereferenceableOrNullAttr(Bytes);
1330 continue;
1331 }
Reid Klecknera534a382013-12-19 02:14:12 +00001332 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001333 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1334 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1335 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1336 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001337 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001338 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1339 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001340 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001341 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1342 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1343 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001344
Stephen Lin7577ed52013-04-20 13:16:13 +00001345 case lltok::kw_alignstack:
1346 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001347 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001348 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001349 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001350 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001351 case lltok::kw_minsize:
1352 case lltok::kw_naked:
1353 case lltok::kw_nobuiltin:
1354 case lltok::kw_noduplicate:
1355 case lltok::kw_noimplicitfloat:
1356 case lltok::kw_noinline:
1357 case lltok::kw_nonlazybind:
1358 case lltok::kw_noredzone:
1359 case lltok::kw_noreturn:
1360 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001361 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001362 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001363 case lltok::kw_returns_twice:
1364 case lltok::kw_sanitize_address:
1365 case lltok::kw_sanitize_memory:
1366 case lltok::kw_sanitize_thread:
1367 case lltok::kw_ssp:
1368 case lltok::kw_sspreq:
1369 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001370 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001371 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001372 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1373 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001374 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001375
Bill Wendling34c2eb22012-12-04 23:40:58 +00001376 Lex.Lex();
1377 }
1378}
1379
1380/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1381bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1382 bool HaveError = false;
1383
1384 B.clear();
1385
1386 while (1) {
1387 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001388 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001389 default: // End of attributes.
1390 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001391 case lltok::StringConstant: {
1392 if (ParseStringAttribute(B))
1393 return true;
1394 continue;
1395 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001396 case lltok::kw_dereferenceable: {
1397 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001398 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001399 return true;
1400 B.addDereferenceableAttr(Bytes);
1401 continue;
1402 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001403 case lltok::kw_dereferenceable_or_null: {
1404 uint64_t Bytes;
1405 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1406 return true;
1407 B.addDereferenceableOrNullAttr(Bytes);
1408 continue;
1409 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001410 case lltok::kw_align: {
1411 unsigned Alignment;
1412 if (ParseOptionalAlignment(Alignment))
1413 return true;
1414 B.addAlignmentAttr(Alignment);
1415 continue;
1416 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001417 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1418 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001419 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001420 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1421 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001422
Bill Wendling34c2eb22012-12-04 23:40:58 +00001423 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001424 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001425 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001426 case lltok::kw_nest:
1427 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001428 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001429 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001430 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001431 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001432
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001433 case lltok::kw_alignstack:
1434 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001435 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001436 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001437 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001438 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001439 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001440 case lltok::kw_minsize:
1441 case lltok::kw_naked:
1442 case lltok::kw_nobuiltin:
1443 case lltok::kw_noduplicate:
1444 case lltok::kw_noimplicitfloat:
1445 case lltok::kw_noinline:
1446 case lltok::kw_nonlazybind:
1447 case lltok::kw_noredzone:
1448 case lltok::kw_noreturn:
1449 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001450 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001451 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001452 case lltok::kw_returns_twice:
1453 case lltok::kw_sanitize_address:
1454 case lltok::kw_sanitize_memory:
1455 case lltok::kw_sanitize_thread:
1456 case lltok::kw_ssp:
1457 case lltok::kw_sspreq:
1458 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001459 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001460 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001461 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001462 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001463
1464 case lltok::kw_readnone:
1465 case lltok::kw_readonly:
1466 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001467 }
1468
Chris Lattnerac161bf2009-01-02 07:01:27 +00001469 Lex.Lex();
1470 }
1471}
1472
1473/// ParseOptionalLinkage
1474/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001475/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001476/// ::= 'internal'
1477/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001478/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001479/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001480/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001481/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001482/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001483/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001484/// ::= 'extern_weak'
1485/// ::= 'external'
1486bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1487 HasLinkage = false;
1488 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001489 default: Res=GlobalValue::ExternalLinkage; return false;
1490 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001491 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1492 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1493 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1494 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1495 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001496 case lltok::kw_available_externally:
1497 Res = GlobalValue::AvailableExternallyLinkage;
1498 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001499 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001500 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001501 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1502 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001503 }
1504 Lex.Lex();
1505 HasLinkage = true;
1506 return false;
1507}
1508
1509/// ParseOptionalVisibility
1510/// ::= /*empty*/
1511/// ::= 'default'
1512/// ::= 'hidden'
1513/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001514///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001515bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1516 switch (Lex.getKind()) {
1517 default: Res = GlobalValue::DefaultVisibility; return false;
1518 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1519 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1520 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1521 }
1522 Lex.Lex();
1523 return false;
1524}
1525
Nico Rieck7157bb72014-01-14 15:22:47 +00001526/// ParseOptionalDLLStorageClass
1527/// ::= /*empty*/
1528/// ::= 'dllimport'
1529/// ::= 'dllexport'
1530///
1531bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1532 switch (Lex.getKind()) {
1533 default: Res = GlobalValue::DefaultStorageClass; return false;
1534 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1535 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1536 }
1537 Lex.Lex();
1538 return false;
1539}
1540
Chris Lattnerac161bf2009-01-02 07:01:27 +00001541/// ParseOptionalCallingConv
1542/// ::= /*empty*/
1543/// ::= 'ccc'
1544/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001545/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001546/// ::= 'coldcc'
1547/// ::= 'x86_stdcallcc'
1548/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001549/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001550/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001551/// ::= 'arm_apcscc'
1552/// ::= 'arm_aapcscc'
1553/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001554/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001555/// ::= 'avr_intrcc'
1556/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001557/// ::= 'ptx_kernel'
1558/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001559/// ::= 'spir_func'
1560/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001561/// ::= 'x86_64_sysvcc'
1562/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001563/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001564/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001565/// ::= 'preserve_mostcc'
1566/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001567/// ::= 'ghccc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001568/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001569/// ::= 'hhvmcc'
1570/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001571/// ::= 'cxx_fast_tlscc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001572/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001573///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001574bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001575 switch (Lex.getKind()) {
1576 default: CC = CallingConv::C; return false;
1577 case lltok::kw_ccc: CC = CallingConv::C; break;
1578 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1579 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1580 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1581 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001582 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001583 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001584 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1585 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1586 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001587 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001588 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1589 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001590 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1591 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001592 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1593 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001594 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001595 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1596 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001597 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001598 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001599 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1600 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001601 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001602 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001603 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1604 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001605 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001606 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001607 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001608 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001609 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001611
Chris Lattnerac161bf2009-01-02 07:01:27 +00001612 Lex.Lex();
1613 return false;
1614}
1615
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001616/// ParseMetadataAttachment
1617/// ::= !dbg !42
1618bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1619 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1620
1621 std::string Name = Lex.getStrVal();
1622 Kind = M->getMDKindID(Name);
1623 Lex.Lex();
1624
1625 return ParseMDNode(MD);
1626}
1627
Chris Lattner5c427632009-12-30 05:31:19 +00001628/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001629/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001630bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001631 do {
1632 if (Lex.getKind() != lltok::MetadataVar)
1633 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001634
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001635 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001636 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001637 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001638 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001639
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001640 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001641 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001642 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001643
Chris Lattner596760d2009-12-29 21:25:40 +00001644 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001645 } while (EatIfPresent(lltok::comma));
1646 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001647}
1648
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001649/// ParseOptionalFunctionMetadata
1650/// ::= (!dbg !57)*
1651bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1652 while (Lex.getKind() == lltok::MetadataVar) {
1653 unsigned MDK;
1654 MDNode *N;
1655 if (ParseMetadataAttachment(MDK, N))
1656 return true;
1657
1658 F.setMetadata(MDK, N);
1659 }
1660 return false;
1661}
1662
Chris Lattnerac161bf2009-01-02 07:01:27 +00001663/// ParseOptionalAlignment
1664/// ::= /* empty */
1665/// ::= 'align' 4
1666bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1667 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001668 if (!EatIfPresent(lltok::kw_align))
1669 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001670 LocTy AlignLoc = Lex.getLoc();
1671 if (ParseUInt32(Alignment)) return true;
1672 if (!isPowerOf2_32(Alignment))
1673 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001674 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001675 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001676 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001677}
1678
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001679/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001680/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001681/// ::= AttrKind '(' 4 ')'
1682///
1683/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1684bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1685 uint64_t &Bytes) {
1686 assert((AttrKind == lltok::kw_dereferenceable ||
1687 AttrKind == lltok::kw_dereferenceable_or_null) &&
1688 "contract!");
1689
Hal Finkelb0407ba2014-07-18 15:51:28 +00001690 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001691 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001692 return false;
1693 LocTy ParenLoc = Lex.getLoc();
1694 if (!EatIfPresent(lltok::lparen))
1695 return Error(ParenLoc, "expected '('");
1696 LocTy DerefLoc = Lex.getLoc();
1697 if (ParseUInt64(Bytes)) return true;
1698 ParenLoc = Lex.getLoc();
1699 if (!EatIfPresent(lltok::rparen))
1700 return Error(ParenLoc, "expected ')'");
1701 if (!Bytes)
1702 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1703 return false;
1704}
1705
Chris Lattnerb2f39502009-12-30 05:44:30 +00001706/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001707/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001708/// ::= ',' align 4
1709///
1710/// This returns with AteExtraComma set to true if it ate an excess comma at the
1711/// end.
1712bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1713 bool &AteExtraComma) {
1714 AteExtraComma = false;
1715 while (EatIfPresent(lltok::comma)) {
1716 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001717 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001718 AteExtraComma = true;
1719 return false;
1720 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001721
Chris Lattner95b0ff42010-04-23 00:50:50 +00001722 if (Lex.getKind() != lltok::kw_align)
1723 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001724
Chris Lattner95b0ff42010-04-23 00:50:50 +00001725 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001726 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001727
Devang Patelea8a4b92009-09-17 23:04:48 +00001728 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001729}
1730
Eli Friedmanfee02c62011-07-25 23:16:38 +00001731/// ParseScopeAndOrdering
1732/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1733/// else: ::=
1734///
1735/// This sets Scope and Ordering to the parsed values.
1736bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1737 AtomicOrdering &Ordering) {
1738 if (!isAtomic)
1739 return false;
1740
1741 Scope = CrossThread;
1742 if (EatIfPresent(lltok::kw_singlethread))
1743 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001744
1745 return ParseOrdering(Ordering);
1746}
1747
1748/// ParseOrdering
1749/// ::= AtomicOrdering
1750///
1751/// This sets Ordering to the parsed value.
1752bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001753 switch (Lex.getKind()) {
1754 default: return TokError("Expected ordering on atomic instruction");
1755 case lltok::kw_unordered: Ordering = Unordered; break;
1756 case lltok::kw_monotonic: Ordering = Monotonic; break;
1757 case lltok::kw_acquire: Ordering = Acquire; break;
1758 case lltok::kw_release: Ordering = Release; break;
1759 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1760 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1761 }
1762 Lex.Lex();
1763 return false;
1764}
1765
Charles Davisbe5557e2010-02-12 00:31:15 +00001766/// ParseOptionalStackAlignment
1767/// ::= /* empty */
1768/// ::= 'alignstack' '(' 4 ')'
1769bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1770 Alignment = 0;
1771 if (!EatIfPresent(lltok::kw_alignstack))
1772 return false;
1773 LocTy ParenLoc = Lex.getLoc();
1774 if (!EatIfPresent(lltok::lparen))
1775 return Error(ParenLoc, "expected '('");
1776 LocTy AlignLoc = Lex.getLoc();
1777 if (ParseUInt32(Alignment)) return true;
1778 ParenLoc = Lex.getLoc();
1779 if (!EatIfPresent(lltok::rparen))
1780 return Error(ParenLoc, "expected ')'");
1781 if (!isPowerOf2_32(Alignment))
1782 return Error(AlignLoc, "stack alignment is not a power of two");
1783 return false;
1784}
Devang Patelea8a4b92009-09-17 23:04:48 +00001785
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001786/// ParseIndexList - This parses the index list for an insert/extractvalue
1787/// instruction. This sets AteExtraComma in the case where we eat an extra
1788/// comma at the end of the line and find that it is followed by metadata.
1789/// Clients that don't allow metadata can call the version of this function that
1790/// only takes one argument.
1791///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001792/// ParseIndexList
1793/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001794///
1795bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1796 bool &AteExtraComma) {
1797 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001798
Chris Lattnerac161bf2009-01-02 07:01:27 +00001799 if (Lex.getKind() != lltok::comma)
1800 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001801
Chris Lattner3822f632009-01-02 08:05:26 +00001802 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001803 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001804 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001805 AteExtraComma = true;
1806 return false;
1807 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001808 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001809 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 Indices.push_back(Idx);
1811 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001812
Chris Lattnerac161bf2009-01-02 07:01:27 +00001813 return false;
1814}
1815
1816//===----------------------------------------------------------------------===//
1817// Type Parsing.
1818//===----------------------------------------------------------------------===//
1819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001821bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001822 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001823 switch (Lex.getKind()) {
1824 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001825 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001826 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001827 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001829 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001830 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001832 // Type ::= StructType
1833 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001834 return true;
1835 break;
1836 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001837 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001838 Lex.Lex(); // eat the lsquare.
1839 if (ParseArrayVectorType(Result, false))
1840 return true;
1841 break;
1842 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001843 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001844 Lex.Lex();
1845 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001846 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001847 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001848 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001849 } else if (ParseArrayVectorType(Result, true))
1850 return true;
1851 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001852 case lltok::LocalVar: {
1853 // Type ::= %foo
1854 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001855
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001856 // If the type hasn't been defined yet, create a forward definition and
1857 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001858 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001859 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001860 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001861 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001862 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001863 Lex.Lex();
1864 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001865 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001866
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001867 case lltok::LocalVarID: {
1868 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001869 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001870
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001871 // If the type hasn't been defined yet, create a forward definition and
1872 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001873 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001874 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001875 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001876 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001877 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001878 Lex.Lex();
1879 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001880 }
1881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001882
1883 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001884 while (1) {
1885 switch (Lex.getKind()) {
1886 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001887 default:
1888 if (!AllowVoid && Result->isVoidTy())
1889 return Error(TypeLoc, "void type only allowed for function results");
1890 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001891
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001894 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001895 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001896 if (Result->isVoidTy())
1897 return TokError("pointers to void are invalid - use i8* instead");
1898 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001899 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001900 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001901 Lex.Lex();
1902 break;
1903
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001905 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001906 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001907 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001908 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001909 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001911 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 unsigned AddrSpace;
1913 if (ParseOptionalAddrSpace(AddrSpace) ||
1914 ParseToken(lltok::star, "expected '*' in address space"))
1915 return true;
1916
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001918 break;
1919 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001920
Chris Lattnerac161bf2009-01-02 07:01:27 +00001921 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1922 case lltok::lparen:
1923 if (ParseFunctionType(Result))
1924 return true;
1925 break;
1926 }
1927 }
1928}
1929
1930/// ParseParameterList
1931/// ::= '(' ')'
1932/// ::= '(' Arg (',' Arg)* ')'
1933/// Arg
1934/// ::= Type OptionalAttributes Value OptionalAttributes
1935bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001936 PerFunctionState &PFS, bool IsMustTailCall,
1937 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001938 if (ParseToken(lltok::lparen, "expected '(' in call"))
1939 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001940
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001941 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 while (Lex.getKind() != lltok::rparen) {
1943 // If this isn't the first argument, we need a comma.
1944 if (!ArgList.empty() &&
1945 ParseToken(lltok::comma, "expected ',' in argument list"))
1946 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001947
Reid Kleckner83498642014-08-26 00:33:28 +00001948 // Parse an ellipsis if this is a musttail call in a variadic function.
1949 if (Lex.getKind() == lltok::dotdotdot) {
1950 const char *Msg = "unexpected ellipsis in argument list for ";
1951 if (!IsMustTailCall)
1952 return TokError(Twine(Msg) + "non-musttail call");
1953 if (!InVarArgsFunc)
1954 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1955 Lex.Lex(); // Lex the '...', it is purely for readability.
1956 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1957 }
1958
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 // Parse the argument.
1960 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001961 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001962 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001963 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001964 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001965 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001966
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001967 if (ArgTy->isMetadataTy()) {
1968 if (ParseMetadataAsValue(V, PFS))
1969 return true;
1970 } else {
1971 // Otherwise, handle normal operands.
1972 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1973 return true;
1974 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001975 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1976 AttrIndex++,
1977 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 }
1979
Reid Kleckner83498642014-08-26 00:33:28 +00001980 if (IsMustTailCall && InVarArgsFunc)
1981 return TokError("expected '...' at end of argument list for musttail call "
1982 "in varargs function");
1983
Chris Lattnerac161bf2009-01-02 07:01:27 +00001984 Lex.Lex(); // Lex the ')'.
1985 return false;
1986}
1987
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001988/// ParseOptionalOperandBundles
1989/// ::= /*empty*/
1990/// ::= '[' OperandBundle [, OperandBundle ]* ']'
1991///
1992/// OperandBundle
1993/// ::= bundle-tag '(' ')'
1994/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
1995///
1996/// bundle-tag ::= String Constant
1997bool LLParser::ParseOptionalOperandBundles(
1998 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
1999 LocTy BeginLoc = Lex.getLoc();
2000 if (!EatIfPresent(lltok::lsquare))
2001 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002002
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002003 while (Lex.getKind() != lltok::rsquare) {
2004 // If this isn't the first operand bundle, we need a comma.
2005 if (!BundleList.empty() &&
2006 ParseToken(lltok::comma, "expected ',' in input list"))
2007 return true;
2008
2009 std::string Tag;
2010 if (ParseStringConstant(Tag))
2011 return true;
2012
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002013 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2014 return true;
2015
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002016 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002017 while (Lex.getKind() != lltok::rparen) {
2018 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002019 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002020 ParseToken(lltok::comma, "expected ',' in input list"))
2021 return true;
2022
2023 Type *Ty = nullptr;
2024 Value *Input = nullptr;
2025 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2026 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002027 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002028 }
2029
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002030 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2031
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002032 Lex.Lex(); // Lex the ')'.
2033 }
2034
2035 if (BundleList.empty())
2036 return Error(BeginLoc, "operand bundle set must not be empty");
2037
2038 Lex.Lex(); // Lex the ']'.
2039 return false;
2040}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002041
Chris Lattner2ed06b42009-01-05 18:34:07 +00002042/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002043/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002044/// ::= '(' ArgTypeListI ')'
2045/// ArgTypeListI
2046/// ::= /*empty*/
2047/// ::= '...'
2048/// ::= ArgTypeList ',' '...'
2049/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002050///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002051bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2052 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002053 isVarArg = false;
2054 assert(Lex.getKind() == lltok::lparen);
2055 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002056
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 if (Lex.getKind() == lltok::rparen) {
2058 // empty
2059 } else if (Lex.getKind() == lltok::dotdotdot) {
2060 isVarArg = true;
2061 Lex.Lex();
2062 } else {
2063 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002064 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002065 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002066 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002067
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002068 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002069 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002070
Chris Lattnerfdd87902009-10-05 05:54:46 +00002071 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002072 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Chris Lattnerdef19492011-06-17 06:36:20 +00002074 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075 Name = Lex.getStrVal();
2076 Lex.Lex();
2077 }
Chris Lattner3822f632009-01-02 08:05:26 +00002078
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002079 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002080 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002081
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002082 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002083 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2084 AttrIndex++, Attrs),
2085 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Chris Lattner3822f632009-01-02 08:05:26 +00002087 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002089 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002090 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002091 break;
2092 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002093
Chris Lattnerac161bf2009-01-02 07:01:27 +00002094 // Otherwise must be an argument type.
2095 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002096 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002097
Chris Lattnerfdd87902009-10-05 05:54:46 +00002098 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002099 return Error(TypeLoc, "argument can not have void type");
2100
Chris Lattnerdef19492011-06-17 06:36:20 +00002101 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 Name = Lex.getStrVal();
2103 Lex.Lex();
2104 } else {
2105 Name = "";
2106 }
Chris Lattner3822f632009-01-02 08:05:26 +00002107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002108 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002109 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002111 ArgList.emplace_back(
2112 TypeLoc, ArgTy,
2113 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2114 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 }
2116 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002117
Chris Lattner3822f632009-01-02 08:05:26 +00002118 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattnerac161bf2009-01-02 07:01:27 +00002121/// ParseFunctionType
2122/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002123bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002124 assert(Lex.getKind() == lltok::lparen);
2125
Chris Lattnerce473c72009-01-05 08:04:33 +00002126 if (!FunctionType::isValidReturnType(Result))
2127 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002129 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002130 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002131 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002132 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002133
Chris Lattnerac161bf2009-01-02 07:01:27 +00002134 // Reject names on the arguments lists.
2135 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2136 if (!ArgList[i].Name.empty())
2137 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002138 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002139 return Error(ArgList[i].Loc,
2140 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002141 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002142
Jay Foadb804a2b2011-07-12 14:06:48 +00002143 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002145 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002146
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002147 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002148 return false;
2149}
2150
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002151/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2152/// other structs.
2153bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2154 SmallVector<Type*, 8> Elts;
2155 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002156
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002157 Result = StructType::get(Context, Elts, Packed);
2158 return false;
2159}
2160
2161/// ParseStructDefinition - Parse a struct in a 'type' definition.
2162bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2163 std::pair<Type*, LocTy> &Entry,
2164 Type *&ResultTy) {
2165 // If the type was already defined, diagnose the redefinition.
2166 if (Entry.first && !Entry.second.isValid())
2167 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002168
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002169 // If we have opaque, just return without filling in the definition for the
2170 // struct. This counts as a definition as far as the .ll file goes.
2171 if (EatIfPresent(lltok::kw_opaque)) {
2172 // This type is being defined, so clear the location to indicate this.
2173 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002174
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002175 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002176 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002177 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002178 ResultTy = Entry.first;
2179 return false;
2180 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002181
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002182 // If the type starts with '<', then it is either a packed struct or a vector.
2183 bool isPacked = EatIfPresent(lltok::less);
2184
2185 // If we don't have a struct, then we have a random type alias, which we
2186 // accept for compatibility with old files. These types are not allowed to be
2187 // forward referenced and not allowed to be recursive.
2188 if (Lex.getKind() != lltok::lbrace) {
2189 if (Entry.first)
2190 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002191
Craig Topper2617dcc2014-04-15 06:32:26 +00002192 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002193 if (isPacked)
2194 return ParseArrayVectorType(ResultTy, true);
2195 return ParseType(ResultTy);
2196 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002197
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002198 // This type is being defined, so clear the location to indicate this.
2199 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002200
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002201 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002202 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002203 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002204
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002205 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002206
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002207 SmallVector<Type*, 8> Body;
2208 if (ParseStructBody(Body) ||
2209 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2210 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002212 STy->setBody(Body, isPacked);
2213 ResultTy = STy;
2214 return false;
2215}
2216
2217
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002219/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002221/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002222/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002223/// ::= '<' '{' Type (',' Type)* '}' '>'
2224bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002225 assert(Lex.getKind() == lltok::lbrace);
2226 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002228 // Handle the empty struct.
2229 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002231
Chris Lattnerf880ca22009-03-09 04:49:14 +00002232 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002233 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002234 if (ParseType(Ty)) return true;
2235 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002237 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002238 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002239
Chris Lattner3822f632009-01-02 08:05:26 +00002240 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002241 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002242 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002244 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002245 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002247 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002250 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251}
2252
2253/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2254/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002255/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256/// ::= '[' APSINTVAL 'x' Types ']'
2257/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002258bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2260 Lex.getAPSIntVal().getBitWidth() > 64)
2261 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002262
Chris Lattnerac161bf2009-01-02 07:01:27 +00002263 LocTy SizeLoc = Lex.getLoc();
2264 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002265 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266
Chris Lattner3822f632009-01-02 08:05:26 +00002267 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2268 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002269
2270 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002271 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002272 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002273
Chris Lattner3822f632009-01-02 08:05:26 +00002274 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2275 "expected end of sequential type"))
2276 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattnerac161bf2009-01-02 07:01:27 +00002278 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002279 if (Size == 0)
2280 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281 if ((unsigned)Size != Size)
2282 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002283 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002284 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002285 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002286 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002287 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002288 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 }
2291 return false;
2292}
2293
2294//===----------------------------------------------------------------------===//
2295// Function Semantic Analysis.
2296//===----------------------------------------------------------------------===//
2297
Chris Lattner3432c622009-10-28 03:39:23 +00002298LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2299 int functionNumber)
2300 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301
2302 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002303 for (Argument &A : F.args())
2304 if (!A.hasName())
2305 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002306}
2307
2308LLParser::PerFunctionState::~PerFunctionState() {
2309 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
David Blaikie9ebdc692015-09-21 21:07:50 +00002311 for (const auto &P : ForwardRefVals) {
2312 if (isa<BasicBlock>(P.second.first))
2313 continue;
2314 P.second.first->replaceAllUsesWith(
2315 UndefValue::get(P.second.first->getType()));
2316 delete P.second.first;
2317 }
2318
2319 for (const auto &P : ForwardRefValIDs) {
2320 if (isa<BasicBlock>(P.second.first))
2321 continue;
2322 P.second.first->replaceAllUsesWith(
2323 UndefValue::get(P.second.first->getType()));
2324 delete P.second.first;
2325 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002326}
2327
Chris Lattner3432c622009-10-28 03:39:23 +00002328bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002329 if (!ForwardRefVals.empty())
2330 return P.Error(ForwardRefVals.begin()->second.second,
2331 "use of undefined value '%" + ForwardRefVals.begin()->first +
2332 "'");
2333 if (!ForwardRefValIDs.empty())
2334 return P.Error(ForwardRefValIDs.begin()->second.second,
2335 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002336 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002337 return false;
2338}
2339
2340
2341/// GetVal - Get a value with the specified name or ID, creating a
2342/// forward reference record if needed. This can return null if the value
2343/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002344Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002345 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002346 // Look this name up in the normal function symbol table.
2347 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002348
Chris Lattnerac161bf2009-01-02 07:01:27 +00002349 // If this is a forward reference for the value, see if we already created a
2350 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002351 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002352 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002353 if (I != ForwardRefVals.end())
2354 Val = I->second.first;
2355 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002356
Chris Lattnerac161bf2009-01-02 07:01:27 +00002357 // If we have the value in the symbol table or fwd-ref table, return it.
2358 if (Val) {
2359 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002360 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002361 P.Error(Loc, "'%" + Name + "' is not a basic block");
2362 else
2363 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002364 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002365 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002366 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002367
Chris Lattnerac161bf2009-01-02 07:01:27 +00002368 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002369 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002371 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002372 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 // Otherwise, create a new forward reference for this value and remember it.
2375 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002376 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002377 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002378 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002379 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381
Chris Lattnerac161bf2009-01-02 07:01:27 +00002382 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2383 return FwdVal;
2384}
2385
David Majnemer8a1c45d2015-12-12 05:38:55 +00002386Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002387 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002388 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002389
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390 // If this is a forward reference for the value, see if we already created a
2391 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002392 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002393 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002394 if (I != ForwardRefValIDs.end())
2395 Val = I->second.first;
2396 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002397
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 // If we have the value in the symbol table or fwd-ref table, return it.
2399 if (Val) {
2400 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002401 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002402 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002403 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002404 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002405 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002406 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002408
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002409 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002411 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002412 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002413
Chris Lattnerac161bf2009-01-02 07:01:27 +00002414 // Otherwise, create a new forward reference for this value and remember it.
2415 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002416 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002417 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002418 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002419 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002420 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattnerac161bf2009-01-02 07:01:27 +00002422 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2423 return FwdVal;
2424}
2425
2426/// SetInstName - After an instruction is parsed and inserted into its
2427/// basic block, this installs its name.
2428bool LLParser::PerFunctionState::SetInstName(int NameID,
2429 const std::string &NameStr,
2430 LocTy NameLoc, Instruction *Inst) {
2431 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002432 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002433 if (NameID != -1 || !NameStr.empty())
2434 return P.Error(NameLoc, "instructions returning void cannot have a name");
2435 return false;
2436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Chris Lattnerac161bf2009-01-02 07:01:27 +00002438 // If this was a numbered instruction, verify that the instruction is the
2439 // expected value and resolve any forward references.
2440 if (NameStr.empty()) {
2441 // If neither a name nor an ID was specified, just use the next ID.
2442 if (NameID == -1)
2443 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 if (unsigned(NameID) != NumberedVals.size())
2446 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002447 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
David Blaikie9ebdc692015-09-21 21:07:50 +00002449 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002450 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002451 Value *Sentinel = FI->second.first;
2452 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002454 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002455
2456 Sentinel->replaceAllUsesWith(Inst);
2457 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 ForwardRefValIDs.erase(FI);
2459 }
2460
2461 NumberedVals.push_back(Inst);
2462 return false;
2463 }
2464
2465 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002466 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002467 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002468 Value *Sentinel = FI->second.first;
2469 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002470 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002471 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002472
2473 Sentinel->replaceAllUsesWith(Inst);
2474 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002475 ForwardRefVals.erase(FI);
2476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002477
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 // Set the name on the instruction.
2479 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002481 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002483 NameStr + "'");
2484 return false;
2485}
2486
2487/// GetBB - Get a basic block with the specified name or ID, creating a
2488/// forward reference record if needed.
2489BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2490 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002491 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2492 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002493}
2494
2495BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002496 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2497 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002498}
2499
2500/// DefineBB - Define the specified basic block, which is either named or
2501/// unnamed. If there is an error, this returns null otherwise it returns
2502/// the block being defined.
2503BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2504 LocTy Loc) {
2505 BasicBlock *BB;
2506 if (Name.empty())
2507 BB = GetBB(NumberedVals.size(), Loc);
2508 else
2509 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002510 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002511
Chris Lattnerac161bf2009-01-02 07:01:27 +00002512 // Move the block to the end of the function. Forward ref'd blocks are
2513 // inserted wherever they happen to be referenced.
2514 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 // Remove the block from forward ref sets.
2517 if (Name.empty()) {
2518 ForwardRefValIDs.erase(NumberedVals.size());
2519 NumberedVals.push_back(BB);
2520 } else {
2521 // BB forward references are already in the function symbol table.
2522 ForwardRefVals.erase(Name);
2523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002524
Chris Lattnerac161bf2009-01-02 07:01:27 +00002525 return BB;
2526}
2527
2528//===----------------------------------------------------------------------===//
2529// Constants.
2530//===----------------------------------------------------------------------===//
2531
2532/// ParseValID - Parse an abstract value that doesn't necessarily have a
2533/// type implied. For example, if we parse "4" we don't know what integer type
2534/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002535/// sanity. PFS is used to convert function-local operands of metadata (since
2536/// metadata operands are not just parsed here but also converted to values).
2537/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002538bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002539 ID.Loc = Lex.getLoc();
2540 switch (Lex.getKind()) {
2541 default: return TokError("expected value token");
2542 case lltok::GlobalID: // @42
2543 ID.UIntVal = Lex.getUIntVal();
2544 ID.Kind = ValID::t_GlobalID;
2545 break;
2546 case lltok::GlobalVar: // @foo
2547 ID.StrVal = Lex.getStrVal();
2548 ID.Kind = ValID::t_GlobalName;
2549 break;
2550 case lltok::LocalVarID: // %42
2551 ID.UIntVal = Lex.getUIntVal();
2552 ID.Kind = ValID::t_LocalID;
2553 break;
2554 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002555 ID.StrVal = Lex.getStrVal();
2556 ID.Kind = ValID::t_LocalName;
2557 break;
2558 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002559 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002560 ID.Kind = ValID::t_APSInt;
2561 break;
2562 case lltok::APFloat:
2563 ID.APFloatVal = Lex.getAPFloatVal();
2564 ID.Kind = ValID::t_APFloat;
2565 break;
2566 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002567 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 ID.Kind = ValID::t_Constant;
2569 break;
2570 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002571 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 ID.Kind = ValID::t_Constant;
2573 break;
2574 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2575 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2576 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002577 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002578
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 case lltok::lbrace: {
2580 // ValID ::= '{' ConstVector '}'
2581 Lex.Lex();
2582 SmallVector<Constant*, 16> Elts;
2583 if (ParseGlobalValueVector(Elts) ||
2584 ParseToken(lltok::rbrace, "expected end of struct constant"))
2585 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002586
David Blaikieadbda4b2015-08-03 20:08:41 +00002587 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002588 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002589 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2590 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002591 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002592 return false;
2593 }
2594 case lltok::less: {
2595 // ValID ::= '<' ConstVector '>' --> Vector.
2596 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2597 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002598 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002599
Chris Lattnerac161bf2009-01-02 07:01:27 +00002600 SmallVector<Constant*, 16> Elts;
2601 LocTy FirstEltLoc = Lex.getLoc();
2602 if (ParseGlobalValueVector(Elts) ||
2603 (isPackedStruct &&
2604 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2605 ParseToken(lltok::greater, "expected end of constant"))
2606 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002607
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002609 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2610 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2611 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002612 ID.UIntVal = Elts.size();
2613 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002614 return false;
2615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002616
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 if (Elts.empty())
2618 return Error(ID.Loc, "constant vector must not be empty");
2619
Duncan Sands9dff9be2010-02-15 16:12:20 +00002620 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002621 !Elts[0]->getType()->isFloatingPointTy() &&
2622 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002624 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002625
Chris Lattnerac161bf2009-01-02 07:01:27 +00002626 // Verify that all the vector elements have the same type.
2627 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2628 if (Elts[i]->getType() != Elts[0]->getType())
2629 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002630 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002631 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattner69229312011-02-15 00:14:00 +00002633 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002634 ID.Kind = ValID::t_Constant;
2635 return false;
2636 }
2637 case lltok::lsquare: { // Array Constant
2638 Lex.Lex();
2639 SmallVector<Constant*, 16> Elts;
2640 LocTy FirstEltLoc = Lex.getLoc();
2641 if (ParseGlobalValueVector(Elts) ||
2642 ParseToken(lltok::rsquare, "expected end of array constant"))
2643 return true;
2644
2645 // Handle empty element.
2646 if (Elts.empty()) {
2647 // Use undef instead of an array because it's inconvenient to determine
2648 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002649 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 return false;
2651 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002654 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002655 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Owen Anderson4056ca92009-07-29 22:17:13 +00002657 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002658
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002660 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 if (Elts[i]->getType() != Elts[0]->getType())
2662 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002663 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002664 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Jay Foad83be3612011-06-22 09:24:39 +00002667 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 ID.Kind = ValID::t_Constant;
2669 return false;
2670 }
2671 case lltok::kw_c: // c "foo"
2672 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002673 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2674 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2676 ID.Kind = ValID::t_Constant;
2677 return false;
2678
2679 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002680 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2681 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002682 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 Lex.Lex();
2684 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002685 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002686 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002687 ParseStringConstant(ID.StrVal) ||
2688 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002689 ParseToken(lltok::StringConstant, "expected constraint string"))
2690 return true;
2691 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002692 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002693 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002694 ID.Kind = ValID::t_InlineAsm;
2695 return false;
2696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002697
Chris Lattner3432c622009-10-28 03:39:23 +00002698 case lltok::kw_blockaddress: {
2699 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2700 Lex.Lex();
2701
2702 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002703
Chris Lattner3432c622009-10-28 03:39:23 +00002704 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2705 ParseValID(Fn) ||
2706 ParseToken(lltok::comma, "expected comma in block address expression")||
2707 ParseValID(Label) ||
2708 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2709 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002710
Chris Lattner3432c622009-10-28 03:39:23 +00002711 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2712 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002713 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002714 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002715
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002716 // Try to find the function (but skip it if it's forward-referenced).
2717 GlobalValue *GV = nullptr;
2718 if (Fn.Kind == ValID::t_GlobalID) {
2719 if (Fn.UIntVal < NumberedVals.size())
2720 GV = NumberedVals[Fn.UIntVal];
2721 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2722 GV = M->getNamedValue(Fn.StrVal);
2723 }
2724 Function *F = nullptr;
2725 if (GV) {
2726 // Confirm that it's actually a function with a definition.
2727 if (!isa<Function>(GV))
2728 return Error(Fn.Loc, "expected function name in blockaddress");
2729 F = cast<Function>(GV);
2730 if (F->isDeclaration())
2731 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2732 }
2733
2734 if (!F) {
2735 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002736 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002737 ForwardRefBlockAddresses.insert(std::make_pair(
2738 std::move(Fn),
2739 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002740 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2741 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002742 if (!FwdRef)
2743 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2744 GlobalValue::InternalLinkage, nullptr, "");
2745 ID.ConstantVal = FwdRef;
2746 ID.Kind = ValID::t_Constant;
2747 return false;
2748 }
2749
2750 // We found the function; now find the basic block. Don't use PFS, since we
2751 // might be inside a constant expression.
2752 BasicBlock *BB;
2753 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2754 if (Label.Kind == ValID::t_LocalID)
2755 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2756 else
2757 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2758 if (!BB)
2759 return Error(Label.Loc, "referenced value is not a basic block");
2760 } else {
2761 if (Label.Kind == ValID::t_LocalID)
2762 return Error(Label.Loc, "cannot take address of numeric label after "
2763 "the function is defined");
2764 BB = dyn_cast_or_null<BasicBlock>(
2765 F->getValueSymbolTable().lookup(Label.StrVal));
2766 if (!BB)
2767 return Error(Label.Loc, "referenced value is not a basic block");
2768 }
2769
2770 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002771 ID.Kind = ValID::t_Constant;
2772 return false;
2773 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 case lltok::kw_trunc:
2776 case lltok::kw_zext:
2777 case lltok::kw_sext:
2778 case lltok::kw_fptrunc:
2779 case lltok::kw_fpext:
2780 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002781 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002782 case lltok::kw_uitofp:
2783 case lltok::kw_sitofp:
2784 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002785 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002786 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002787 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002789 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002790 Constant *SrcVal;
2791 Lex.Lex();
2792 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2793 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002794 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002795 ParseType(DestTy) ||
2796 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2797 return true;
2798 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2799 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002800 getTypeString(SrcVal->getType()) + "' to '" +
2801 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002802 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002803 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002804 ID.Kind = ValID::t_Constant;
2805 return false;
2806 }
2807 case lltok::kw_extractvalue: {
2808 Lex.Lex();
2809 Constant *Val;
2810 SmallVector<unsigned, 4> Indices;
2811 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2812 ParseGlobalTypeAndValue(Val) ||
2813 ParseIndexList(Indices) ||
2814 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2815 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002816
Chris Lattner392be582010-02-12 20:49:41 +00002817 if (!Val->getType()->isAggregateType())
2818 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002819 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002820 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002821 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002822 ID.Kind = ValID::t_Constant;
2823 return false;
2824 }
2825 case lltok::kw_insertvalue: {
2826 Lex.Lex();
2827 Constant *Val0, *Val1;
2828 SmallVector<unsigned, 4> Indices;
2829 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2830 ParseGlobalTypeAndValue(Val0) ||
2831 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2832 ParseGlobalTypeAndValue(Val1) ||
2833 ParseIndexList(Indices) ||
2834 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2835 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002836 if (!Val0->getType()->isAggregateType())
2837 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002838 Type *IndexedType =
2839 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2840 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002842 if (IndexedType != Val1->getType())
2843 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2844 getTypeString(Val1->getType()) +
2845 "' instead of '" + getTypeString(IndexedType) +
2846 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002847 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 ID.Kind = ValID::t_Constant;
2849 return false;
2850 }
2851 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002852 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 unsigned PredVal, Opc = Lex.getUIntVal();
2854 Constant *Val0, *Val1;
2855 Lex.Lex();
2856 if (ParseCmpPredicate(PredVal, Opc) ||
2857 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2858 ParseGlobalTypeAndValue(Val0) ||
2859 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2860 ParseGlobalTypeAndValue(Val1) ||
2861 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2862 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
Chris Lattnerac161bf2009-01-02 07:01:27 +00002864 if (Val0->getType() != Val1->getType())
2865 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002866
Chris Lattnerac161bf2009-01-02 07:01:27 +00002867 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattnerac161bf2009-01-02 07:01:27 +00002869 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002870 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002871 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002872 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002873 } else {
2874 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002875 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002876 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002877 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002878 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002879 }
2880 ID.Kind = ValID::t_Constant;
2881 return false;
2882 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002883
Chris Lattnerac161bf2009-01-02 07:01:27 +00002884 // Binary Operators.
2885 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002886 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002887 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002888 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002889 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002890 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002891 case lltok::kw_udiv:
2892 case lltok::kw_sdiv:
2893 case lltok::kw_fdiv:
2894 case lltok::kw_urem:
2895 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002896 case lltok::kw_frem:
2897 case lltok::kw_shl:
2898 case lltok::kw_lshr:
2899 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002900 bool NUW = false;
2901 bool NSW = false;
2902 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002903 unsigned Opc = Lex.getUIntVal();
2904 Constant *Val0, *Val1;
2905 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002906 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002907 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2908 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002909 if (EatIfPresent(lltok::kw_nuw))
2910 NUW = true;
2911 if (EatIfPresent(lltok::kw_nsw)) {
2912 NSW = true;
2913 if (EatIfPresent(lltok::kw_nuw))
2914 NUW = true;
2915 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002916 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2917 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002918 if (EatIfPresent(lltok::kw_exact))
2919 Exact = true;
2920 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002921 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2922 ParseGlobalTypeAndValue(Val0) ||
2923 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2924 ParseGlobalTypeAndValue(Val1) ||
2925 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2926 return true;
2927 if (Val0->getType() != Val1->getType())
2928 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002929 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002930 if (NUW)
2931 return Error(ModifierLoc, "nuw only applies to integer operations");
2932 if (NSW)
2933 return Error(ModifierLoc, "nsw only applies to integer operations");
2934 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002935 // Check that the type is valid for the operator.
2936 switch (Opc) {
2937 case Instruction::Add:
2938 case Instruction::Sub:
2939 case Instruction::Mul:
2940 case Instruction::UDiv:
2941 case Instruction::SDiv:
2942 case Instruction::URem:
2943 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002944 case Instruction::Shl:
2945 case Instruction::AShr:
2946 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002947 if (!Val0->getType()->isIntOrIntVectorTy())
2948 return Error(ID.Loc, "constexpr requires integer operands");
2949 break;
2950 case Instruction::FAdd:
2951 case Instruction::FSub:
2952 case Instruction::FMul:
2953 case Instruction::FDiv:
2954 case Instruction::FRem:
2955 if (!Val0->getType()->isFPOrFPVectorTy())
2956 return Error(ID.Loc, "constexpr requires fp operands");
2957 break;
2958 default: llvm_unreachable("Unknown binary operator!");
2959 }
Dan Gohman1b849082009-09-07 23:54:19 +00002960 unsigned Flags = 0;
2961 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2962 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002963 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002964 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002965 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002966 ID.Kind = ValID::t_Constant;
2967 return false;
2968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002969
Chris Lattnerac161bf2009-01-02 07:01:27 +00002970 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002971 case lltok::kw_and:
2972 case lltok::kw_or:
2973 case lltok::kw_xor: {
2974 unsigned Opc = Lex.getUIntVal();
2975 Constant *Val0, *Val1;
2976 Lex.Lex();
2977 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2978 ParseGlobalTypeAndValue(Val0) ||
2979 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2980 ParseGlobalTypeAndValue(Val1) ||
2981 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2982 return true;
2983 if (Val0->getType() != Val1->getType())
2984 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002985 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002986 return Error(ID.Loc,
2987 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002988 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002989 ID.Kind = ValID::t_Constant;
2990 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002991 }
2992
Chris Lattnerac161bf2009-01-02 07:01:27 +00002993 case lltok::kw_getelementptr:
2994 case lltok::kw_shufflevector:
2995 case lltok::kw_insertelement:
2996 case lltok::kw_extractelement:
2997 case lltok::kw_select: {
2998 unsigned Opc = Lex.getUIntVal();
2999 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003000 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003001 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003002 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003003
Dan Gohman1639c392009-07-27 21:53:46 +00003004 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003005 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003006
3007 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3008 return true;
3009
3010 LocTy ExplicitTypeLoc = Lex.getLoc();
3011 if (Opc == Instruction::GetElementPtr) {
3012 if (ParseType(Ty) ||
3013 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3014 return true;
3015 }
3016
3017 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003018 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3019 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003020
Chris Lattnerac161bf2009-01-02 07:01:27 +00003021 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003022 if (Elts.size() == 0 ||
3023 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003024 return Error(ID.Loc, "base of getelementptr must be a pointer");
3025
3026 Type *BaseType = Elts[0]->getType();
3027 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003028 if (Ty != BasePointerType->getElementType())
3029 return Error(
3030 ExplicitTypeLoc,
3031 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003032
Jay Foaded8db7d2011-07-21 14:31:17 +00003033 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003034 for (Constant *Val : Indices) {
3035 Type *ValTy = Val->getType();
3036 if (!ValTy->getScalarType()->isIntegerTy())
3037 return Error(ID.Loc, "getelementptr index must be an integer");
3038 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3039 return Error(ID.Loc, "getelementptr index type missmatch");
3040 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003041 unsigned ValNumEl = ValTy->getVectorNumElements();
3042 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00003043 if (ValNumEl != PtrNumEl)
3044 return Error(
3045 ID.Loc,
3046 "getelementptr vector index has a wrong number of elements");
3047 }
3048 }
3049
Craig Toppere3dcce92015-08-01 22:20:21 +00003050 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003051 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003052 return Error(ID.Loc, "base element of getelementptr must be sized");
3053
David Blaikie4a2e73b2015-04-02 18:55:32 +00003054 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003055 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003056 ID.ConstantVal =
3057 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003058 } else if (Opc == Instruction::Select) {
3059 if (Elts.size() != 3)
3060 return Error(ID.Loc, "expected three operands to select");
3061 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3062 Elts[2]))
3063 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003064 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003065 } else if (Opc == Instruction::ShuffleVector) {
3066 if (Elts.size() != 3)
3067 return Error(ID.Loc, "expected three operands to shufflevector");
3068 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3069 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003070 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003071 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 } else if (Opc == Instruction::ExtractElement) {
3073 if (Elts.size() != 2)
3074 return Error(ID.Loc, "expected two operands to extractelement");
3075 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3076 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003077 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 } else {
3079 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3080 if (Elts.size() != 3)
3081 return Error(ID.Loc, "expected three operands to insertelement");
3082 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3083 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003084 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003085 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003087
Chris Lattnerac161bf2009-01-02 07:01:27 +00003088 ID.Kind = ValID::t_Constant;
3089 return false;
3090 }
3091 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003092
Chris Lattnerac161bf2009-01-02 07:01:27 +00003093 Lex.Lex();
3094 return false;
3095}
3096
3097/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003098bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003099 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003100 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003101 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003102 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003103 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003104 if (V && !(C = dyn_cast<Constant>(V)))
3105 return Error(ID.Loc, "global values must be constants");
3106 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003107}
3108
Victor Hernandez9d75c962010-01-11 22:31:58 +00003109bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003110 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003111 return ParseType(Ty) ||
3112 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003113}
3114
Rafael Espindola83a362c2015-01-06 22:55:16 +00003115bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003116 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003117
3118 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003119 if (!EatIfPresent(lltok::kw_comdat))
3120 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003121
3122 if (EatIfPresent(lltok::lparen)) {
3123 if (Lex.getKind() != lltok::ComdatVar)
3124 return TokError("expected comdat variable");
3125 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3126 Lex.Lex();
3127 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3128 return true;
3129 } else {
3130 if (GlobalName.empty())
3131 return TokError("comdat cannot be unnamed");
3132 C = getComdat(GlobalName, KwLoc);
3133 }
3134
David Majnemerdad0a642014-06-27 18:19:56 +00003135 return false;
3136}
3137
Victor Hernandez9d75c962010-01-11 22:31:58 +00003138/// ParseGlobalValueVector
3139/// ::= /*empty*/
3140/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003141bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003142 // Empty list.
3143 if (Lex.getKind() == lltok::rbrace ||
3144 Lex.getKind() == lltok::rsquare ||
3145 Lex.getKind() == lltok::greater ||
3146 Lex.getKind() == lltok::rparen)
3147 return false;
3148
3149 Constant *C;
3150 if (ParseGlobalTypeAndValue(C)) return true;
3151 Elts.push_back(C);
3152
3153 while (EatIfPresent(lltok::comma)) {
3154 if (ParseGlobalTypeAndValue(C)) return true;
3155 Elts.push_back(C);
3156 }
3157
3158 return false;
3159}
3160
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003161bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003162 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003163 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003164 return true;
3165
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003166 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003167 return false;
3168}
3169
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003170/// MDNode:
3171/// ::= !{ ... }
3172/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003173/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003174bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003175 if (Lex.getKind() == lltok::MetadataVar)
3176 return ParseSpecializedMDNode(N);
3177
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003178 return ParseToken(lltok::exclaim, "expected '!' here") ||
3179 ParseMDNodeTail(N);
3180}
3181
3182bool LLParser::ParseMDNodeTail(MDNode *&N) {
3183 // !{ ... }
3184 if (Lex.getKind() == lltok::lbrace)
3185 return ParseMDTuple(N);
3186
3187 // !42
3188 return ParseMDNodeID(N);
3189}
3190
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003191namespace {
3192
3193/// Structure to represent an optional metadata field.
3194template <class FieldTy> struct MDFieldImpl {
3195 typedef MDFieldImpl ImplTy;
3196 FieldTy Val;
3197 bool Seen;
3198
3199 void assign(FieldTy Val) {
3200 Seen = true;
3201 this->Val = std::move(Val);
3202 }
3203
3204 explicit MDFieldImpl(FieldTy Default)
3205 : Val(std::move(Default)), Seen(false) {}
3206};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003207
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003208struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3209 uint64_t Max;
3210
3211 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3212 : ImplTy(Default), Max(Max) {}
3213};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003214struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003215 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003216};
3217struct ColumnField : public MDUnsignedField {
3218 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3219};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003220struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003221 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003222 DwarfTagField(dwarf::Tag DefaultTag)
3223 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003224};
Amjad Abouda9bcf162015-12-10 12:56:35 +00003225struct DwarfMacinfoTypeField : public MDUnsignedField {
3226 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3227 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3228 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3229};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003230struct DwarfAttEncodingField : public MDUnsignedField {
3231 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3232};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003233struct DwarfVirtualityField : public MDUnsignedField {
3234 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3235};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003236struct DwarfLangField : public MDUnsignedField {
3237 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3238};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003239
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003240struct DIFlagField : public MDUnsignedField {
3241 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3242};
3243
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003244struct MDSignedField : public MDFieldImpl<int64_t> {
3245 int64_t Min;
3246 int64_t Max;
3247
3248 MDSignedField(int64_t Default = 0)
3249 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3250 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3251 : ImplTy(Default), Min(Min), Max(Max) {}
3252};
3253
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003254struct MDBoolField : public MDFieldImpl<bool> {
3255 MDBoolField(bool Default = false) : ImplTy(Default) {}
3256};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003257struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003258 bool AllowNull;
3259
3260 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003261};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003262struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3263 MDConstant() : ImplTy(nullptr) {}
3264};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003265struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003266 bool AllowEmpty;
3267 MDStringField(bool AllowEmpty = true)
3268 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003269};
3270struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3271 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3272};
3273
3274} // end namespace
3275
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003276namespace llvm {
3277
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003278template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003279bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003280 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003281 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3282 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003283
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003284 auto &U = Lex.getAPSIntVal();
3285 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003286 return TokError("value for '" + Name + "' too large, limit is " +
3287 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003288 Result.assign(U.getZExtValue());
3289 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003290 Lex.Lex();
3291 return false;
3292}
3293
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003294template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003295bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3296 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3297}
3298template <>
3299bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3300 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3301}
3302
3303template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003304bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3305 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003306 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003307
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003308 if (Lex.getKind() != lltok::DwarfTag)
3309 return TokError("expected DWARF tag");
3310
3311 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3312 if (Tag == dwarf::DW_TAG_invalid)
3313 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003314 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003315
3316 Result.assign(Tag);
3317 Lex.Lex();
3318 return false;
3319}
3320
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003321template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003322bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003323 DwarfMacinfoTypeField &Result) {
3324 if (Lex.getKind() == lltok::APSInt)
3325 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3326
3327 if (Lex.getKind() != lltok::DwarfMacinfo)
3328 return TokError("expected DWARF macinfo type");
3329
3330 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3331 if (Macinfo == dwarf::DW_MACINFO_invalid)
3332 return TokError(
3333 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3334 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3335
3336 Result.assign(Macinfo);
3337 Lex.Lex();
3338 return false;
3339}
3340
3341template <>
3342bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003343 DwarfVirtualityField &Result) {
3344 if (Lex.getKind() == lltok::APSInt)
3345 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3346
3347 if (Lex.getKind() != lltok::DwarfVirtuality)
3348 return TokError("expected DWARF virtuality code");
3349
3350 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3351 if (!Virtuality)
3352 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3353 Lex.getStrVal() + "'");
3354 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3355 Result.assign(Virtuality);
3356 Lex.Lex();
3357 return false;
3358}
3359
3360template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003361bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3362 if (Lex.getKind() == lltok::APSInt)
3363 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3364
3365 if (Lex.getKind() != lltok::DwarfLang)
3366 return TokError("expected DWARF language");
3367
3368 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3369 if (!Lang)
3370 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3371 "'");
3372 assert(Lang <= Result.Max && "Expected valid DWARF language");
3373 Result.assign(Lang);
3374 Lex.Lex();
3375 return false;
3376}
3377
3378template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003379bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003380 DwarfAttEncodingField &Result) {
3381 if (Lex.getKind() == lltok::APSInt)
3382 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3383
3384 if (Lex.getKind() != lltok::DwarfAttEncoding)
3385 return TokError("expected DWARF type attribute encoding");
3386
3387 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3388 if (!Encoding)
3389 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3390 Lex.getStrVal() + "'");
3391 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3392 Result.assign(Encoding);
3393 Lex.Lex();
3394 return false;
3395}
3396
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003397/// DIFlagField
3398/// ::= uint32
3399/// ::= DIFlagVector
3400/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3401template <>
3402bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3403 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3404
3405 // Parser for a single flag.
3406 auto parseFlag = [&](unsigned &Val) {
3407 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3408 return ParseUInt32(Val);
3409
3410 if (Lex.getKind() != lltok::DIFlag)
3411 return TokError("expected debug info flag");
3412
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003413 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003414 if (!Val)
3415 return TokError(Twine("invalid debug info flag flag '") +
3416 Lex.getStrVal() + "'");
3417 Lex.Lex();
3418 return false;
3419 };
3420
3421 // Parse the flags and combine them together.
3422 unsigned Combined = 0;
3423 do {
3424 unsigned Val;
3425 if (parseFlag(Val))
3426 return true;
3427 Combined |= Val;
3428 } while (EatIfPresent(lltok::bar));
3429
3430 Result.assign(Combined);
3431 return false;
3432}
3433
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003434template <>
3435bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003436 MDSignedField &Result) {
3437 if (Lex.getKind() != lltok::APSInt)
3438 return TokError("expected signed integer");
3439
3440 auto &S = Lex.getAPSIntVal();
3441 if (S < Result.Min)
3442 return TokError("value for '" + Name + "' too small, limit is " +
3443 Twine(Result.Min));
3444 if (S > Result.Max)
3445 return TokError("value for '" + Name + "' too large, limit is " +
3446 Twine(Result.Max));
3447 Result.assign(S.getExtValue());
3448 assert(Result.Val >= Result.Min && "Expected value in range");
3449 assert(Result.Val <= Result.Max && "Expected value in range");
3450 Lex.Lex();
3451 return false;
3452}
3453
3454template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003455bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3456 switch (Lex.getKind()) {
3457 default:
3458 return TokError("expected 'true' or 'false'");
3459 case lltok::kw_true:
3460 Result.assign(true);
3461 break;
3462 case lltok::kw_false:
3463 Result.assign(false);
3464 break;
3465 }
3466 Lex.Lex();
3467 return false;
3468}
3469
3470template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003471bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003472 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003473 if (!Result.AllowNull)
3474 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003475 Lex.Lex();
3476 Result.assign(nullptr);
3477 return false;
3478 }
3479
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003480 Metadata *MD;
3481 if (ParseMetadata(MD, nullptr))
3482 return true;
3483
3484 Result.assign(MD);
3485 return false;
3486}
3487
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003488template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003489bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3490 Metadata *MD;
3491 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3492 return true;
3493
3494 Result.assign(cast<ConstantAsMetadata>(MD));
3495 return false;
3496}
3497
3498template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003499bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003500 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003501 std::string S;
3502 if (ParseStringConstant(S))
3503 return true;
3504
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003505 if (!Result.AllowEmpty && S.empty())
3506 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3507
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003508 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003509 return false;
3510}
3511
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003512template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003513bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3514 SmallVector<Metadata *, 4> MDs;
3515 if (ParseMDNodeVector(MDs))
3516 return true;
3517
3518 Result.assign(std::move(MDs));
3519 return false;
3520}
3521
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003522} // end namespace llvm
3523
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003524template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003525bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003526 do {
3527 if (Lex.getKind() != lltok::LabelStr)
3528 return TokError("expected field label here");
3529
3530 if (parseField())
3531 return true;
3532 } while (EatIfPresent(lltok::comma));
3533
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003534 return false;
3535}
3536
3537template <class ParserTy>
3538bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3539 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3540 Lex.Lex();
3541
3542 if (ParseToken(lltok::lparen, "expected '(' here"))
3543 return true;
3544 if (Lex.getKind() != lltok::rparen)
3545 if (ParseMDFieldsImplBody(parseField))
3546 return true;
3547
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003548 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003549 return ParseToken(lltok::rparen, "expected ')' here");
3550}
3551
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003552template <class FieldTy>
3553bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3554 if (Result.Seen)
3555 return TokError("field '" + Name + "' cannot be specified more than once");
3556
3557 LocTy Loc = Lex.getLoc();
3558 Lex.Lex();
3559 return ParseMDField(Loc, Name, Result);
3560}
3561
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003562bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3563 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003564
3565#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003566 if (Lex.getStrVal() == #CLASS) \
3567 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003568#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003569
3570 return TokError("expected metadata type");
3571}
3572
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003573#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3574#define NOP_FIELD(NAME, TYPE, INIT)
3575#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3576 if (!NAME.Seen) \
3577 return Error(ClosingLoc, "missing required field '" #NAME "'");
3578#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003579 if (Lex.getStrVal() == #NAME) \
3580 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003581#define PARSE_MD_FIELDS() \
3582 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3583 do { \
3584 LocTy ClosingLoc; \
3585 if (ParseMDFieldsImpl([&]() -> bool { \
3586 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3587 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3588 }, ClosingLoc)) \
3589 return true; \
3590 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3591 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003592#define GET_OR_DISTINCT(CLASS, ARGS) \
3593 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003594
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003595/// ParseDILocationFields:
3596/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3597bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003598#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003599 OPTIONAL(line, LineField, ); \
3600 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003601 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003602 OPTIONAL(inlinedAt, MDField, );
3603 PARSE_MD_FIELDS();
3604#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003605
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003606 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003607 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003608 return false;
3609}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003610
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003611/// ParseGenericDINode:
3612/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3613bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003614#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003615 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003616 OPTIONAL(header, MDStringField, ); \
3617 OPTIONAL(operands, MDFieldList, );
3618 PARSE_MD_FIELDS();
3619#undef VISIT_MD_FIELDS
3620
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003621 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003622 (Context, tag.Val, header.Val, operands.Val));
3623 return false;
3624}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003625
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003626/// ParseDISubrange:
3627/// ::= !DISubrange(count: 30, lowerBound: 2)
3628bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003630 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003631 OPTIONAL(lowerBound, MDSignedField, );
3632 PARSE_MD_FIELDS();
3633#undef VISIT_MD_FIELDS
3634
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003635 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003636 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003637}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003638
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003639/// ParseDIEnumerator:
3640/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3641bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003642#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003643 REQUIRED(name, MDStringField, ); \
3644 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003645 PARSE_MD_FIELDS();
3646#undef VISIT_MD_FIELDS
3647
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003648 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003649 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003650}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003651
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003652/// ParseDIBasicType:
3653/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3654bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003655#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003656 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003657 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003658 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3659 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003660 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003661 PARSE_MD_FIELDS();
3662#undef VISIT_MD_FIELDS
3663
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003664 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003665 align.Val, encoding.Val));
3666 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003667}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003668
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003669/// ParseDIDerivedType:
3670/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003671/// line: 7, scope: !1, baseType: !2, size: 32,
3672/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003673bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003674#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3675 REQUIRED(tag, DwarfTagField, ); \
3676 OPTIONAL(name, MDStringField, ); \
3677 OPTIONAL(file, MDField, ); \
3678 OPTIONAL(line, LineField, ); \
3679 OPTIONAL(scope, MDField, ); \
3680 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003681 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3682 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3683 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003684 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003685 OPTIONAL(extraData, MDField, );
3686 PARSE_MD_FIELDS();
3687#undef VISIT_MD_FIELDS
3688
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003689 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003690 (Context, tag.Val, name.Val, file.Val, line.Val,
3691 scope.Val, baseType.Val, size.Val, align.Val,
3692 offset.Val, flags.Val, extraData.Val));
3693 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003694}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003695
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003696bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3698 REQUIRED(tag, DwarfTagField, ); \
3699 OPTIONAL(name, MDStringField, ); \
3700 OPTIONAL(file, MDField, ); \
3701 OPTIONAL(line, LineField, ); \
3702 OPTIONAL(scope, MDField, ); \
3703 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003704 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3705 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3706 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003707 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003708 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003709 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003710 OPTIONAL(vtableHolder, MDField, ); \
3711 OPTIONAL(templateParams, MDField, ); \
3712 OPTIONAL(identifier, MDStringField, );
3713 PARSE_MD_FIELDS();
3714#undef VISIT_MD_FIELDS
3715
3716 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003717 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003718 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3719 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3720 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3721 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003722}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003723
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003724bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003725#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003726 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003727 REQUIRED(types, MDField, );
3728 PARSE_MD_FIELDS();
3729#undef VISIT_MD_FIELDS
3730
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003731 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003732 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003733}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003734
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003735/// ParseDIFileType:
3736/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3737bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003738#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3739 REQUIRED(filename, MDStringField, ); \
3740 REQUIRED(directory, MDStringField, );
3741 PARSE_MD_FIELDS();
3742#undef VISIT_MD_FIELDS
3743
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003744 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003745 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003746}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003747
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003748/// ParseDICompileUnit:
3749/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003750/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3751/// splitDebugFilename: "abc.debug", emissionKind: 1,
3752/// enums: !1, retainedTypes: !2, subprograms: !3,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003753/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003754bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003755 if (!IsDistinct)
3756 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3757
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003758#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3759 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003760 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003761 OPTIONAL(producer, MDStringField, ); \
3762 OPTIONAL(isOptimized, MDBoolField, ); \
3763 OPTIONAL(flags, MDStringField, ); \
3764 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3765 OPTIONAL(splitDebugFilename, MDStringField, ); \
3766 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3767 OPTIONAL(enums, MDField, ); \
3768 OPTIONAL(retainedTypes, MDField, ); \
3769 OPTIONAL(subprograms, MDField, ); \
3770 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003771 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00003772 OPTIONAL(macros, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003773 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003774 PARSE_MD_FIELDS();
3775#undef VISIT_MD_FIELDS
3776
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00003777 Result = DICompileUnit::getDistinct(
3778 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3779 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003780 retainedTypes.Val, subprograms.Val, globals.Val, imports.Val, macros.Val,
3781 dwoId.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003782 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003783}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003784
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003785/// ParseDISubprogram:
3786/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003787/// file: !1, line: 7, type: !2, isLocal: false,
3788/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003789/// virtuality: DW_VIRTUALTIY_pure_virtual,
3790/// virtualIndex: 10, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00003791/// isOptimized: false, templateParams: !4, declaration: !5,
3792/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003793bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003794 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003795#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3796 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003797 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003798 OPTIONAL(linkageName, MDStringField, ); \
3799 OPTIONAL(file, MDField, ); \
3800 OPTIONAL(line, LineField, ); \
3801 OPTIONAL(type, MDField, ); \
3802 OPTIONAL(isLocal, MDBoolField, ); \
3803 OPTIONAL(isDefinition, MDBoolField, (true)); \
3804 OPTIONAL(scopeLine, LineField, ); \
3805 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003806 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003807 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003808 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003809 OPTIONAL(isOptimized, MDBoolField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003810 OPTIONAL(templateParams, MDField, ); \
3811 OPTIONAL(declaration, MDField, ); \
3812 OPTIONAL(variables, MDField, );
3813 PARSE_MD_FIELDS();
3814#undef VISIT_MD_FIELDS
3815
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00003816 if (isDefinition.Val && !IsDistinct)
3817 return Lex.Error(
3818 Loc,
3819 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
3820
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003821 Result = GET_OR_DISTINCT(
Peter Collingbourned4bff302015-11-05 22:03:56 +00003822 DISubprogram,
3823 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
3824 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
3825 containingType.Val, virtuality.Val, virtualIndex.Val, flags.Val,
3826 isOptimized.Val, templateParams.Val, declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003827 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003828}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003829
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003830/// ParseDILexicalBlock:
3831/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3832bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003833#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003834 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003835 OPTIONAL(file, MDField, ); \
3836 OPTIONAL(line, LineField, ); \
3837 OPTIONAL(column, ColumnField, );
3838 PARSE_MD_FIELDS();
3839#undef VISIT_MD_FIELDS
3840
3841 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003842 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003843 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003844}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003845
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003846/// ParseDILexicalBlockFile:
3847/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3848bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003849#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003850 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003851 OPTIONAL(file, MDField, ); \
3852 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3853 PARSE_MD_FIELDS();
3854#undef VISIT_MD_FIELDS
3855
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003856 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003857 (Context, scope.Val, file.Val, discriminator.Val));
3858 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003859}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003860
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003861/// ParseDINamespace:
3862/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3863bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3865 REQUIRED(scope, MDField, ); \
3866 OPTIONAL(file, MDField, ); \
3867 OPTIONAL(name, MDStringField, ); \
3868 OPTIONAL(line, LineField, );
3869 PARSE_MD_FIELDS();
3870#undef VISIT_MD_FIELDS
3871
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003872 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003873 (Context, scope.Val, file.Val, name.Val, line.Val));
3874 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003875}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003876
Amjad Abouda9bcf162015-12-10 12:56:35 +00003877/// ParseDIMacro:
3878/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
3879bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
3880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3881 REQUIRED(type, DwarfMacinfoTypeField, ); \
3882 REQUIRED(line, LineField, ); \
3883 REQUIRED(name, MDStringField, ); \
3884 OPTIONAL(value, MDStringField, );
3885 PARSE_MD_FIELDS();
3886#undef VISIT_MD_FIELDS
3887
3888 Result = GET_OR_DISTINCT(DIMacro,
3889 (Context, type.Val, line.Val, name.Val, value.Val));
3890 return false;
3891}
3892
3893/// ParseDIMacroFile:
3894/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
3895bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
3896#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3897 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
3898 REQUIRED(line, LineField, ); \
3899 REQUIRED(file, MDField, ); \
3900 OPTIONAL(nodes, MDField, );
3901 PARSE_MD_FIELDS();
3902#undef VISIT_MD_FIELDS
3903
3904 Result = GET_OR_DISTINCT(DIMacroFile,
3905 (Context, type.Val, line.Val, file.Val, nodes.Val));
3906 return false;
3907}
3908
3909
Adrian Prantlab1243f2015-06-29 23:03:47 +00003910/// ParseDIModule:
3911/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3912/// includePath: "/usr/include", isysroot: "/")
3913bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3914#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3915 REQUIRED(scope, MDField, ); \
3916 REQUIRED(name, MDStringField, ); \
3917 OPTIONAL(configMacros, MDStringField, ); \
3918 OPTIONAL(includePath, MDStringField, ); \
3919 OPTIONAL(isysroot, MDStringField, );
3920 PARSE_MD_FIELDS();
3921#undef VISIT_MD_FIELDS
3922
3923 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3924 configMacros.Val, includePath.Val, isysroot.Val));
3925 return false;
3926}
3927
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003928/// ParseDITemplateTypeParameter:
3929/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3930bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003931#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003932 OPTIONAL(name, MDStringField, ); \
3933 REQUIRED(type, MDField, );
3934 PARSE_MD_FIELDS();
3935#undef VISIT_MD_FIELDS
3936
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003937 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003938 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003939 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003940}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003941
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003942/// ParseDITemplateValueParameter:
3943/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003944/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003945bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003946#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003947 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003948 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003949 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003950 REQUIRED(value, MDField, );
3951 PARSE_MD_FIELDS();
3952#undef VISIT_MD_FIELDS
3953
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003954 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003955 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003956 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003957}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003958
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003959/// ParseDIGlobalVariable:
3960/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003961/// file: !1, line: 7, type: !2, isLocal: false,
3962/// isDefinition: true, variable: i32* @foo,
3963/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003964bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003965#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003966 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003967 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003968 OPTIONAL(linkageName, MDStringField, ); \
3969 OPTIONAL(file, MDField, ); \
3970 OPTIONAL(line, LineField, ); \
3971 OPTIONAL(type, MDField, ); \
3972 OPTIONAL(isLocal, MDBoolField, ); \
3973 OPTIONAL(isDefinition, MDBoolField, (true)); \
3974 OPTIONAL(variable, MDConstant, ); \
3975 OPTIONAL(declaration, MDField, );
3976 PARSE_MD_FIELDS();
3977#undef VISIT_MD_FIELDS
3978
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003979 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003980 (Context, scope.Val, name.Val, linkageName.Val,
3981 file.Val, line.Val, type.Val, isLocal.Val,
3982 isDefinition.Val, variable.Val, declaration.Val));
3983 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003984}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003985
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003986/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003987/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3988/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3989/// ::= !DILocalVariable(scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003990/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003991bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003992#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003993 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003994 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00003995 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003996 OPTIONAL(file, MDField, ); \
3997 OPTIONAL(line, LineField, ); \
3998 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003999 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004000 PARSE_MD_FIELDS();
4001#undef VISIT_MD_FIELDS
4002
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004003 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004004 (Context, scope.Val, name.Val, file.Val, line.Val,
4005 type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004006 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004007}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004008
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004009/// ParseDIExpression:
4010/// ::= !DIExpression(0, 7, -1)
4011bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004012 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4013 Lex.Lex();
4014
4015 if (ParseToken(lltok::lparen, "expected '(' here"))
4016 return true;
4017
4018 SmallVector<uint64_t, 8> Elements;
4019 if (Lex.getKind() != lltok::rparen)
4020 do {
4021 if (Lex.getKind() == lltok::DwarfOp) {
4022 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4023 Lex.Lex();
4024 Elements.push_back(Op);
4025 continue;
4026 }
4027 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4028 }
4029
4030 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4031 return TokError("expected unsigned integer");
4032
4033 auto &U = Lex.getAPSIntVal();
4034 if (U.ugt(UINT64_MAX))
4035 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4036 Elements.push_back(U.getZExtValue());
4037 Lex.Lex();
4038 } while (EatIfPresent(lltok::comma));
4039
4040 if (ParseToken(lltok::rparen, "expected ')' here"))
4041 return true;
4042
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004043 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004044 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004045}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004046
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004047/// ParseDIObjCProperty:
4048/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004049/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004050bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004051#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004052 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004053 OPTIONAL(file, MDField, ); \
4054 OPTIONAL(line, LineField, ); \
4055 OPTIONAL(setter, MDStringField, ); \
4056 OPTIONAL(getter, MDStringField, ); \
4057 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4058 OPTIONAL(type, MDField, );
4059 PARSE_MD_FIELDS();
4060#undef VISIT_MD_FIELDS
4061
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004062 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004063 (Context, name.Val, file.Val, line.Val, setter.Val,
4064 getter.Val, attributes.Val, type.Val));
4065 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004066}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004068/// ParseDIImportedEntity:
4069/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004070/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004071bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004072#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4073 REQUIRED(tag, DwarfTagField, ); \
4074 REQUIRED(scope, MDField, ); \
4075 OPTIONAL(entity, MDField, ); \
4076 OPTIONAL(line, LineField, ); \
4077 OPTIONAL(name, MDStringField, );
4078 PARSE_MD_FIELDS();
4079#undef VISIT_MD_FIELDS
4080
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004081 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004082 entity.Val, line.Val, name.Val));
4083 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004084}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004085
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004086#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004087#undef NOP_FIELD
4088#undef REQUIRE_FIELD
4089#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004090
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004091/// ParseMetadataAsValue
4092/// ::= metadata i32 %local
4093/// ::= metadata i32 @global
4094/// ::= metadata i32 7
4095/// ::= metadata !0
4096/// ::= metadata !{...}
4097/// ::= metadata !"string"
4098bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4099 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004100 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004101 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004102 return true;
4103
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004104 V = MetadataAsValue::get(Context, MD);
4105 return false;
4106}
4107
4108/// ParseValueAsMetadata
4109/// ::= i32 %local
4110/// ::= i32 @global
4111/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004112bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4113 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004114 Type *Ty;
4115 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004116 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004117 return true;
4118 if (Ty->isMetadataTy())
4119 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4120
4121 Value *V;
4122 if (ParseValue(Ty, V, PFS))
4123 return true;
4124
4125 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004126 return false;
4127}
4128
4129/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004130/// ::= i32 %local
4131/// ::= i32 @global
4132/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004133/// ::= !42
4134/// ::= !{...}
4135/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004136/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004137bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004138 if (Lex.getKind() == lltok::MetadataVar) {
4139 MDNode *N;
4140 if (ParseSpecializedMDNode(N))
4141 return true;
4142 MD = N;
4143 return false;
4144 }
4145
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004146 // ValueAsMetadata:
4147 // <type> <value>
4148 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004149 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004150
4151 // '!'.
4152 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4153 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004154
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004155 // MDString:
4156 // ::= '!' STRINGCONSTANT
4157 if (Lex.getKind() == lltok::StringConstant) {
4158 MDString *S;
4159 if (ParseMDString(S))
4160 return true;
4161 MD = S;
4162 return false;
4163 }
4164
Dan Gohman8939ba332010-07-14 18:26:50 +00004165 // MDNode:
4166 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004167 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004168 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004169 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004170 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004171 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004172 return false;
4173}
4174
Victor Hernandez9d75c962010-01-11 22:31:58 +00004175
4176//===----------------------------------------------------------------------===//
4177// Function Parsing.
4178//===----------------------------------------------------------------------===//
4179
Chris Lattner229907c2011-07-18 04:54:35 +00004180bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004181 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004182 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004183 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004184
Chris Lattnerac161bf2009-01-02 07:01:27 +00004185 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004186 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004187 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004188 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004189 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004191 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004192 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004193 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004194 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004195 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004196 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004197 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4198 (ID.UIntVal >> 1) & 1,
4199 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004200 return false;
4201 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004202 case ValID::t_GlobalName:
4203 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004204 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004205 case ValID::t_GlobalID:
4206 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004207 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004208 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004209 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004211 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004212 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004213 return false;
4214 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004215 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004216 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4217 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004218
Dan Gohman518cda42011-12-17 00:04:22 +00004219 // The lexer has no type info, so builds all half, float, and double FP
4220 // constants as double. Fix this here. Long double does not need this.
4221 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004223 if (Ty->isHalfTy())
4224 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4225 &Ignored);
4226 else if (Ty->isFloatTy())
4227 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4228 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004229 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004230 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004231
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004232 if (V->getType() != Ty)
4233 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004234 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004235
Chris Lattnerac161bf2009-01-02 07:01:27 +00004236 return false;
4237 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004238 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004239 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004240 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004241 return false;
4242 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004243 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004244 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004245 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004246 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004247 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004248 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004249 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004250 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004251 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004252 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004253 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004254 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004255 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004256 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004257 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004258 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004259 case ValID::t_None:
4260 if (!Ty->isTokenTy())
4261 return Error(ID.Loc, "invalid type for none constant");
4262 V = Constant::getNullValue(Ty);
4263 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004264 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004265 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004267
Chris Lattnerac161bf2009-01-02 07:01:27 +00004268 V = ID.ConstantVal;
4269 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004270 case ValID::t_ConstantStruct:
4271 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004272 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004273 if (ST->getNumElements() != ID.UIntVal)
4274 return Error(ID.Loc,
4275 "initializer with struct type has wrong # elements");
4276 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4277 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004278
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004279 // Verify that the elements are compatible with the structtype.
4280 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4281 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4282 return Error(ID.Loc, "element " + Twine(i) +
4283 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004284
David Blaikieadbda4b2015-08-03 20:08:41 +00004285 V = ConstantStruct::get(
4286 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004287 } else
4288 return Error(ID.Loc, "constant expression type mismatch");
4289 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004290 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004291 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004292}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004293
Alex Lorenzd2255952015-07-17 22:07:03 +00004294bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4295 C = nullptr;
4296 ValID ID;
4297 auto Loc = Lex.getLoc();
4298 if (ParseValID(ID, /*PFS=*/nullptr))
4299 return true;
4300 switch (ID.Kind) {
4301 case ValID::t_APSInt:
4302 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004303 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004304 case ValID::t_Constant:
4305 case ValID::t_ConstantStruct:
4306 case ValID::t_PackedConstantStruct: {
4307 Value *V;
4308 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4309 return true;
4310 assert(isa<Constant>(V) && "Expected a constant value");
4311 C = cast<Constant>(V);
4312 return false;
4313 }
4314 default:
4315 return Error(Loc, "expected a constant value");
4316 }
4317}
4318
David Majnemer8a1c45d2015-12-12 05:38:55 +00004319bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004320 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004321 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004322 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323}
4324
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004325bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004326 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004327 return ParseType(Ty) ||
4328 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004329}
4330
Chris Lattner3ed871f2009-10-27 19:13:16 +00004331bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4332 PerFunctionState &PFS) {
4333 Value *V;
4334 Loc = Lex.getLoc();
4335 if (ParseTypeAndValue(V, PFS)) return true;
4336 if (!isa<BasicBlock>(V))
4337 return Error(Loc, "expected a basic block");
4338 BB = cast<BasicBlock>(V);
4339 return false;
4340}
4341
4342
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343/// FunctionHeader
4344/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004345/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004346/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004347bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4348 // Parse the linkage.
4349 LocTy LinkageLoc = Lex.getLoc();
4350 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004351
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004352 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004353 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004354 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004355 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004356 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004357 LocTy RetTypeLoc = Lex.getLoc();
4358 if (ParseOptionalLinkage(Linkage) ||
4359 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004360 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004362 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004363 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364 return true;
4365
4366 // Verify that the linkage is ok.
4367 switch ((GlobalValue::LinkageTypes)Linkage) {
4368 case GlobalValue::ExternalLinkage:
4369 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004370 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004371 if (isDefine)
4372 return Error(LinkageLoc, "invalid linkage for function definition");
4373 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004374 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004375 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004376 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004377 case GlobalValue::LinkOnceAnyLinkage:
4378 case GlobalValue::LinkOnceODRLinkage:
4379 case GlobalValue::WeakAnyLinkage:
4380 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004381 if (!isDefine)
4382 return Error(LinkageLoc, "invalid linkage for function declaration");
4383 break;
4384 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004385 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 return Error(LinkageLoc, "invalid function linkage type");
4387 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004388
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004389 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4390 return Error(LinkageLoc,
4391 "symbol with local linkage must have default visibility");
4392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004393 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004394 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004395
Chris Lattnerac161bf2009-01-02 07:01:27 +00004396 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004397
4398 std::string FunctionName;
4399 if (Lex.getKind() == lltok::GlobalVar) {
4400 FunctionName = Lex.getStrVal();
4401 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4402 unsigned NameID = Lex.getUIntVal();
4403
4404 if (NameID != NumberedVals.size())
4405 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004406 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004407 } else {
4408 return TokError("expected function name");
4409 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004410
Chris Lattner3822f632009-01-02 08:05:26 +00004411 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004412
Chris Lattner3822f632009-01-02 08:05:26 +00004413 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004415
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004416 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004417 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004418 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004419 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004420 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004421 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004422 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004423 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004424 bool UnnamedAddr;
4425 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004426 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004427 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004428 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004429 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004431 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004432 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4433 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004434 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004435 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004436 (EatIfPresent(lltok::kw_section) &&
4437 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004438 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004439 ParseOptionalAlignment(Alignment) ||
4440 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004441 ParseStringConstant(GC)) ||
4442 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004443 ParseGlobalTypeAndValue(Prefix)) ||
4444 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004445 ParseGlobalTypeAndValue(Prologue)) ||
4446 (EatIfPresent(lltok::kw_personality) &&
4447 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004448 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004449
Michael Gottesman41748d72013-06-27 00:25:01 +00004450 if (FuncAttrs.contains(Attribute::Builtin))
4451 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004452
Chris Lattnerac161bf2009-01-02 07:01:27 +00004453 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004454 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004455 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004456 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004458
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459 // Okay, if we got here, the function is syntactically valid. Convert types
4460 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004461 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004462 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004464 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004465 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4466 AttributeSet::ReturnIndex,
4467 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004468
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004470 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004471 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4472 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004473 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4474 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004475 }
4476
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004477 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004478 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4479 AttributeSet::FunctionIndex,
4480 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004481
Bill Wendlinge94d8432012-12-07 23:16:57 +00004482 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004483
Bill Wendling749a43d2012-12-30 13:50:49 +00004484 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004485 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4486
Chris Lattner229907c2011-07-18 04:54:35 +00004487 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004488 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004489 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490
Craig Topper2617dcc2014-04-15 06:32:26 +00004491 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 if (!FunctionName.empty()) {
4493 // If this was a definition of a forward reference, remove the definition
4494 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004495 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 if (FRVI != ForwardRefVals.end()) {
4497 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004498 if (!Fn)
4499 return Error(FRVI->second.second, "invalid forward reference to "
4500 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004501 if (Fn->getType() != PFT)
4502 return Error(FRVI->second.second, "invalid forward reference to "
4503 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004504
Chris Lattnerac161bf2009-01-02 07:01:27 +00004505 ForwardRefVals.erase(FRVI);
4506 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004507 // Reject redefinitions.
4508 return Error(NameLoc, "invalid redefinition of function '" +
4509 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004510 } else if (M->getNamedValue(FunctionName)) {
4511 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004512 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004513
Dan Gohman399d6ae2009-08-29 23:37:49 +00004514 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 // If this is a definition of a forward referenced function, make sure the
4516 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004517 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004518 if (I != ForwardRefValIDs.end()) {
4519 Fn = cast<Function>(I->second.first);
4520 if (Fn->getType() != PFT)
4521 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004522 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004523 ForwardRefValIDs.erase(I);
4524 }
4525 }
4526
Craig Topper2617dcc2014-04-15 06:32:26 +00004527 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004528 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4529 else // Move the forward-reference to the correct spot in the module.
4530 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4531
4532 if (FunctionName.empty())
4533 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004534
Chris Lattnerac161bf2009-01-02 07:01:27 +00004535 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4536 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004537 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 Fn->setCallingConv(CC);
4539 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004540 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004541 Fn->setAlignment(Alignment);
4542 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004543 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004544 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004545 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004546 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004547 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004548 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004549
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 // Add all of the arguments we parsed to the function.
4551 Function::arg_iterator ArgIt = Fn->arg_begin();
4552 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4553 // If the argument has a name, insert it into the argument symbol table.
4554 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004555
Chris Lattnerac161bf2009-01-02 07:01:27 +00004556 // Set the name, if it conflicted, it will be auto-renamed.
4557 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004558
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004559 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004560 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4561 ArgList[i].Name + "'");
4562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004563
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004564 if (isDefine)
4565 return false;
4566
Robin Morisset039781e2014-08-29 21:53:01 +00004567 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004568 ValID ID;
4569 if (FunctionName.empty()) {
4570 ID.Kind = ValID::t_GlobalID;
4571 ID.UIntVal = NumberedVals.size() - 1;
4572 } else {
4573 ID.Kind = ValID::t_GlobalName;
4574 ID.StrVal = FunctionName;
4575 }
4576 auto Blocks = ForwardRefBlockAddresses.find(ID);
4577 if (Blocks != ForwardRefBlockAddresses.end())
4578 return Error(Blocks->first.Loc,
4579 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004580 return false;
4581}
4582
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004583bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4584 ValID ID;
4585 if (FunctionNumber == -1) {
4586 ID.Kind = ValID::t_GlobalName;
4587 ID.StrVal = F.getName();
4588 } else {
4589 ID.Kind = ValID::t_GlobalID;
4590 ID.UIntVal = FunctionNumber;
4591 }
4592
4593 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4594 if (Blocks == P.ForwardRefBlockAddresses.end())
4595 return false;
4596
4597 for (const auto &I : Blocks->second) {
4598 const ValID &BBID = I.first;
4599 GlobalValue *GV = I.second;
4600
4601 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4602 "Expected local id or name");
4603 BasicBlock *BB;
4604 if (BBID.Kind == ValID::t_LocalName)
4605 BB = GetBB(BBID.StrVal, BBID.Loc);
4606 else
4607 BB = GetBB(BBID.UIntVal, BBID.Loc);
4608 if (!BB)
4609 return P.Error(BBID.Loc, "referenced value is not a basic block");
4610
4611 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4612 GV->eraseFromParent();
4613 }
4614
4615 P.ForwardRefBlockAddresses.erase(Blocks);
4616 return false;
4617}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618
4619/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004620/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004621bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004622 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004623 return TokError("expected '{' in function body");
4624 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004625
Chris Lattner3432c622009-10-28 03:39:23 +00004626 int FunctionNumber = -1;
4627 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004628
Chris Lattner3432c622009-10-28 03:39:23 +00004629 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004631 // Resolve block addresses and allow basic blocks to be forward-declared
4632 // within this function.
4633 if (PFS.resolveForwardRefBlockAddresses())
4634 return true;
4635 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4636
Chris Lattnerbbddd962010-01-09 19:20:07 +00004637 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004638 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004639 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004640
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004641 while (Lex.getKind() != lltok::rbrace &&
4642 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004644
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004645 while (Lex.getKind() != lltok::rbrace)
4646 if (ParseUseListOrder(&PFS))
4647 return true;
4648
Chris Lattnerac161bf2009-01-02 07:01:27 +00004649 // Eat the }.
4650 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004651
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004653 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654}
4655
4656/// ParseBasicBlock
4657/// ::= LabelStr? Instruction*
4658bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4659 // If this basic block starts out with a name, remember it.
4660 std::string Name;
4661 LocTy NameLoc = Lex.getLoc();
4662 if (Lex.getKind() == lltok::LabelStr) {
4663 Name = Lex.getStrVal();
4664 Lex.Lex();
4665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004666
Chris Lattnerac161bf2009-01-02 07:01:27 +00004667 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004668 if (!BB)
4669 return Error(NameLoc,
4670 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004673
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 // Parse the instructions in this block until we get a terminator.
4675 Instruction *Inst;
4676 do {
4677 // This instruction may have three possibilities for a name: a) none
4678 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4679 LocTy NameLoc = Lex.getLoc();
4680 int NameID = -1;
4681 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004682
Chris Lattnerac161bf2009-01-02 07:01:27 +00004683 if (Lex.getKind() == lltok::LocalVarID) {
4684 NameID = Lex.getUIntVal();
4685 Lex.Lex();
4686 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4687 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004688 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004689 NameStr = Lex.getStrVal();
4690 Lex.Lex();
4691 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4692 return true;
4693 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004694
Chris Lattner77b89dc2009-12-30 05:23:43 +00004695 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004696 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004697 case InstError: return true;
4698 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004699 BB->getInstList().push_back(Inst);
4700
Chris Lattner77b89dc2009-12-30 05:23:43 +00004701 // With a normal result, we check to see if the instruction is followed by
4702 // a comma and metadata.
4703 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004704 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004705 return true;
4706 break;
4707 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004708 BB->getInstList().push_back(Inst);
4709
Chris Lattner77b89dc2009-12-30 05:23:43 +00004710 // If the instruction parser ate an extra comma at the end of it, it
4711 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004712 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004713 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004714 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004715 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004716
Chris Lattnerac161bf2009-01-02 07:01:27 +00004717 // Set the name on the instruction.
4718 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4719 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004720
Chris Lattnerac161bf2009-01-02 07:01:27 +00004721 return false;
4722}
4723
4724//===----------------------------------------------------------------------===//
4725// Instruction Parsing.
4726//===----------------------------------------------------------------------===//
4727
4728/// ParseInstruction - Parse one of the many different instructions.
4729///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004730int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4731 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 lltok::Kind Token = Lex.getKind();
4733 if (Token == lltok::Eof)
4734 return TokError("found end of file when expecting more instructions");
4735 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004736 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004737 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004738
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 switch (Token) {
4740 default: return Error(Loc, "expected instruction opcode");
4741 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004742 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004743 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4744 case lltok::kw_br: return ParseBr(Inst, PFS);
4745 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004746 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004747 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004748 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00004749 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4750 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004751 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4752 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00004753 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004754 // Binary Operators.
4755 case lltok::kw_add:
4756 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004757 case lltok::kw_mul:
4758 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004759 bool NUW = EatIfPresent(lltok::kw_nuw);
4760 bool NSW = EatIfPresent(lltok::kw_nsw);
4761 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004762
Chris Lattnera676c0f2011-02-07 16:40:21 +00004763 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004764
Chris Lattnera676c0f2011-02-07 16:40:21 +00004765 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4766 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4767 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004768 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004769 case lltok::kw_fadd:
4770 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004771 case lltok::kw_fmul:
4772 case lltok::kw_fdiv:
4773 case lltok::kw_frem: {
4774 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4775 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4776 if (Res != 0)
4777 return Res;
4778 if (FMF.any())
4779 Inst->setFastMathFlags(FMF);
4780 return 0;
4781 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004782
Chris Lattner35315d02011-02-06 21:44:57 +00004783 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004784 case lltok::kw_udiv:
4785 case lltok::kw_lshr:
4786 case lltok::kw_ashr: {
4787 bool Exact = EatIfPresent(lltok::kw_exact);
4788
4789 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4790 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4791 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004792 }
4793
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004795 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 case lltok::kw_and:
4797 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004798 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004799 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4800 case lltok::kw_fcmp: {
4801 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4802 int Res = ParseCompare(Inst, PFS, KeywordVal);
4803 if (Res != 0)
4804 return Res;
4805 if (FMF.any())
4806 Inst->setFastMathFlags(FMF);
4807 return 0;
4808 }
4809
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 // Casts.
4811 case lltok::kw_trunc:
4812 case lltok::kw_zext:
4813 case lltok::kw_sext:
4814 case lltok::kw_fptrunc:
4815 case lltok::kw_fpext:
4816 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004817 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004818 case lltok::kw_uitofp:
4819 case lltok::kw_sitofp:
4820 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004821 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004823 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004824 // Other.
4825 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004826 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004827 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4828 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4829 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4830 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004831 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004832 // Call.
4833 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4834 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4835 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004836 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004837 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004838 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004839 case lltok::kw_load: return ParseLoad(Inst, PFS);
4840 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004841 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4842 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004843 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004844 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4845 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4846 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4847 }
4848}
4849
4850/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4851bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004852 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004853 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004854 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004855 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4856 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4857 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4858 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4859 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4860 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4861 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4862 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4863 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4864 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4865 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4866 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4867 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4868 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4869 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4870 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4871 }
4872 } else {
4873 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004874 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004875 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4876 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4877 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4878 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4879 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4880 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4881 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4882 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4883 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4884 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4885 }
4886 }
4887 Lex.Lex();
4888 return false;
4889}
4890
4891//===----------------------------------------------------------------------===//
4892// Terminator Instructions.
4893//===----------------------------------------------------------------------===//
4894
4895/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004896/// ::= 'ret' void (',' !dbg, !1)*
4897/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004898bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004899 PerFunctionState &PFS) {
4900 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004901 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004902 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004903
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004904 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004905
Chris Lattnerfdd87902009-10-05 05:54:46 +00004906 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004907 if (!ResType->isVoidTy())
4908 return Error(TypeLoc, "value doesn't match function result type '" +
4909 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004910
Owen Anderson55f1c092009-08-13 21:58:54 +00004911 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004912 return false;
4913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004914
Chris Lattnerac161bf2009-01-02 07:01:27 +00004915 Value *RV;
4916 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004917
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004918 if (ResType != RV->getType())
4919 return Error(TypeLoc, "value doesn't match function result type '" +
4920 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004921
Owen Anderson55f1c092009-08-13 21:58:54 +00004922 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004923 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004924}
4925
4926
4927/// ParseBr
4928/// ::= 'br' TypeAndValue
4929/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4930bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4931 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004932 Value *Op0;
4933 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004935
Chris Lattnerac161bf2009-01-02 07:01:27 +00004936 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4937 Inst = BranchInst::Create(BB);
4938 return false;
4939 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004940
Owen Anderson55f1c092009-08-13 21:58:54 +00004941 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004942 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004943
Chris Lattnerac161bf2009-01-02 07:01:27 +00004944 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004945 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004946 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004947 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004948 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004949
Chris Lattner3ed871f2009-10-27 19:13:16 +00004950 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004951 return false;
4952}
4953
4954/// ParseSwitch
4955/// Instruction
4956/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4957/// JumpTable
4958/// ::= (TypeAndValue ',' TypeAndValue)*
4959bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4960 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004961 Value *Cond;
4962 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4964 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004965 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004966 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4967 return true;
4968
Duncan Sands19d0b472010-02-16 11:11:14 +00004969 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004970 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004971
Chris Lattnerac161bf2009-01-02 07:01:27 +00004972 // Parse the jump table pairs.
4973 SmallPtrSet<Value*, 32> SeenCases;
4974 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4975 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004976 Value *Constant;
4977 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004978
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4980 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004981 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004982 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004983
David Blaikie70573dc2014-11-19 07:49:26 +00004984 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004985 return Error(CondLoc, "duplicate case value in switch");
4986 if (!isa<ConstantInt>(Constant))
4987 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004988
Chris Lattner3ed871f2009-10-27 19:13:16 +00004989 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004991
Chris Lattnerac161bf2009-01-02 07:01:27 +00004992 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004993
Chris Lattner3ed871f2009-10-27 19:13:16 +00004994 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004995 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4996 SI->addCase(Table[i].first, Table[i].second);
4997 Inst = SI;
4998 return false;
4999}
5000
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005001/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005002/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005003/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5004bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005005 LocTy AddrLoc;
5006 Value *Address;
5007 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005008 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5009 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005010 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005011
Duncan Sands19d0b472010-02-16 11:11:14 +00005012 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005013 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005014
Chris Lattner3ed871f2009-10-27 19:13:16 +00005015 // Parse the destination list.
5016 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005017
Chris Lattner3ed871f2009-10-27 19:13:16 +00005018 if (Lex.getKind() != lltok::rsquare) {
5019 BasicBlock *DestBB;
5020 if (ParseTypeAndBasicBlock(DestBB, PFS))
5021 return true;
5022 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005023
Chris Lattner3ed871f2009-10-27 19:13:16 +00005024 while (EatIfPresent(lltok::comma)) {
5025 if (ParseTypeAndBasicBlock(DestBB, PFS))
5026 return true;
5027 DestList.push_back(DestBB);
5028 }
5029 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005030
Chris Lattner3ed871f2009-10-27 19:13:16 +00005031 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5032 return true;
5033
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005034 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005035 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5036 IBI->addDestination(DestList[i]);
5037 Inst = IBI;
5038 return false;
5039}
5040
5041
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042/// ParseInvoke
5043/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5044/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5045bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5046 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005047 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005048 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005049 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005050 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005051 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005052 LocTy RetTypeLoc;
5053 ValID CalleeID;
5054 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005055 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005056
Chris Lattner3ed871f2009-10-27 19:13:16 +00005057 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005058 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005059 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005060 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005061 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5062 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005063 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005065 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005066 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005067 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005068 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005069
Chris Lattnerac161bf2009-01-02 07:01:27 +00005070 // If RetType is a non-function pointer type, then this is the short syntax
5071 // for the call, which means that RetType is just the return type. Infer the
5072 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005073 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5074 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005076 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005077 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5078 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005079
Chris Lattnerac161bf2009-01-02 07:01:27 +00005080 if (!FunctionType::isValidReturnType(RetType))
5081 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005082
Owen Anderson4056ca92009-07-29 22:17:13 +00005083 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005084 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005085
David Blaikie41ba2b42015-07-27 23:32:19 +00005086 CalleeID.FTy = Ty;
5087
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 // Look up the callee.
5089 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005090 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5091 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005092
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005093 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005094 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005095 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005096 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5097 AttributeSet::ReturnIndex,
5098 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005099
Chris Lattnerac161bf2009-01-02 07:01:27 +00005100 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005101
Chris Lattnerac161bf2009-01-02 07:01:27 +00005102 // Loop through FunctionType's arguments and ensure they are specified
5103 // correctly. Also, gather any parameter attributes.
5104 FunctionType::param_iterator I = Ty->param_begin();
5105 FunctionType::param_iterator E = Ty->param_end();
5106 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005107 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005108 if (I != E) {
5109 ExpectedTy = *I++;
5110 } else if (!Ty->isVarArg()) {
5111 return Error(ArgList[i].Loc, "too many arguments specified");
5112 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005113
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5115 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005116 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005118 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5119 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005120 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5121 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005123
Chris Lattnerac161bf2009-01-02 07:01:27 +00005124 if (I != E)
5125 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005126
David Majnemer8d22abd2015-02-23 00:01:32 +00005127 if (FnAttrs.hasAttributes()) {
5128 if (FnAttrs.hasAlignmentAttr())
5129 return Error(CallLoc, "invoke instructions may not have an alignment");
5130
Bill Wendlingf5075a42013-01-27 02:24:02 +00005131 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5132 AttributeSet::FunctionIndex,
5133 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005134 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005135
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005136 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005137 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005138
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005139 InvokeInst *II =
5140 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005141 II->setCallingConv(CC);
5142 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005143 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005144 Inst = II;
5145 return false;
5146}
5147
Bill Wendlingf891bf82011-07-31 06:30:59 +00005148/// ParseResume
5149/// ::= 'resume' TypeAndValue
5150bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5151 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005152 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5153 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005154
Bill Wendlingf891bf82011-07-31 06:30:59 +00005155 ResumeInst *RI = ResumeInst::Create(Exn);
5156 Inst = RI;
5157 return false;
5158}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159
David Majnemer654e1302015-07-31 17:58:14 +00005160bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5161 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005162 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005163 return true;
5164
5165 while (Lex.getKind() != lltok::rsquare) {
5166 // If this isn't the first argument, we need a comma.
5167 if (!Args.empty() &&
5168 ParseToken(lltok::comma, "expected ',' in argument list"))
5169 return true;
5170
5171 // Parse the argument.
5172 LocTy ArgLoc;
5173 Type *ArgTy = nullptr;
5174 if (ParseType(ArgTy, ArgLoc))
5175 return true;
5176
5177 Value *V;
5178 if (ArgTy->isMetadataTy()) {
5179 if (ParseMetadataAsValue(V, PFS))
5180 return true;
5181 } else {
5182 if (ParseValue(ArgTy, V, PFS))
5183 return true;
5184 }
5185 Args.push_back(V);
5186 }
5187
5188 Lex.Lex(); // Lex the ']'.
5189 return false;
5190}
5191
5192/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005193/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005194bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005195 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005196
David Majnemer8a1c45d2015-12-12 05:38:55 +00005197 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5198 return true;
5199
5200 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005201 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005202
5203 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5204 return true;
5205
5206 BasicBlock *UnwindBB = nullptr;
5207 if (Lex.getKind() == lltok::kw_to) {
5208 Lex.Lex();
5209 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5210 return true;
5211 } else {
5212 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5213 return true;
5214 }
5215 }
5216
David Majnemer8a1c45d2015-12-12 05:38:55 +00005217 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005218 return false;
5219}
5220
5221/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005222/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005223bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005224 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005225
David Majnemer8a1c45d2015-12-12 05:38:55 +00005226 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5227 return true;
5228
5229 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005230 return true;
5231
David Majnemer0bc0eef2015-08-15 02:46:08 +00005232 BasicBlock *BB;
5233 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5234 ParseTypeAndBasicBlock(BB, PFS))
5235 return true;
5236
David Majnemer8a1c45d2015-12-12 05:38:55 +00005237 Inst = CatchReturnInst::Create(CatchPad, BB);
5238 return false;
5239}
5240
5241/// ParseCatchSwitch
5242/// ::= 'catchswitch' within Parent
5243bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5244 Value *ParentPad;
5245 LocTy BBLoc;
5246
5247 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5248 return true;
5249
5250 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5251 Lex.getKind() != lltok::LocalVarID)
5252 return TokError("expected scope value for catchswitch");
5253
5254 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5255 return true;
5256
5257 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5258 return true;
5259
5260 SmallVector<BasicBlock *, 32> Table;
5261 do {
5262 BasicBlock *DestBB;
5263 if (ParseTypeAndBasicBlock(DestBB, PFS))
5264 return true;
5265 Table.push_back(DestBB);
5266 } while (EatIfPresent(lltok::comma));
5267
5268 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5269 return true;
5270
5271 if (ParseToken(lltok::kw_unwind,
5272 "expected 'unwind' after catchswitch scope"))
5273 return true;
5274
5275 BasicBlock *UnwindBB = nullptr;
5276 if (EatIfPresent(lltok::kw_to)) {
5277 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5278 return true;
5279 } else {
5280 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5281 return true;
5282 }
5283
5284 auto *CatchSwitch =
5285 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5286 for (BasicBlock *DestBB : Table)
5287 CatchSwitch->addHandler(DestBB);
5288 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005289 return false;
5290}
5291
5292/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005293/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005294bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005295 Value *CatchSwitch = nullptr;
5296
5297 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5298 return true;
5299
5300 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5301 return TokError("expected scope value for catchpad");
5302
5303 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5304 return true;
5305
David Majnemer654e1302015-07-31 17:58:14 +00005306 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005307 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005308 return true;
5309
David Majnemer8a1c45d2015-12-12 05:38:55 +00005310 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005311 return false;
5312}
5313
David Majnemer654e1302015-07-31 17:58:14 +00005314/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005315/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005316bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005317 Value *ParentPad = nullptr;
5318
5319 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5320 return true;
5321
5322 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5323 Lex.getKind() != lltok::LocalVarID)
5324 return TokError("expected scope value for cleanuppad");
5325
5326 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5327 return true;
5328
David Majnemer654e1302015-07-31 17:58:14 +00005329 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005330 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005331 return true;
5332
David Majnemer8a1c45d2015-12-12 05:38:55 +00005333 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005334 return false;
5335}
5336
Chris Lattnerac161bf2009-01-02 07:01:27 +00005337//===----------------------------------------------------------------------===//
5338// Binary Operators.
5339//===----------------------------------------------------------------------===//
5340
5341/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005342/// ::= ArithmeticOps TypeAndValue ',' Value
5343///
5344/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5345/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005346bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005347 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348 LocTy Loc; Value *LHS, *RHS;
5349 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5350 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5351 ParseValue(LHS->getType(), RHS, PFS))
5352 return true;
5353
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005354 bool Valid;
5355 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005356 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005357 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005358 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5359 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005360 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005361 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5362 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005364
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005365 if (!Valid)
5366 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005367
Chris Lattnerac161bf2009-01-02 07:01:27 +00005368 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5369 return false;
5370}
5371
5372/// ParseLogical
5373/// ::= ArithmeticOps TypeAndValue ',' Value {
5374bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5375 unsigned Opc) {
5376 LocTy Loc; Value *LHS, *RHS;
5377 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5378 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5379 ParseValue(LHS->getType(), RHS, PFS))
5380 return true;
5381
Duncan Sands9dff9be2010-02-15 16:12:20 +00005382 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005383 return Error(Loc,"instruction requires integer or integer vector operands");
5384
5385 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5386 return false;
5387}
5388
5389
5390/// ParseCompare
5391/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5392/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005393bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5394 unsigned Opc) {
5395 // Parse the integer/fp comparison predicate.
5396 LocTy Loc;
5397 unsigned Pred;
5398 Value *LHS, *RHS;
5399 if (ParseCmpPredicate(Pred, Opc) ||
5400 ParseTypeAndValue(LHS, Loc, PFS) ||
5401 ParseToken(lltok::comma, "expected ',' after compare value") ||
5402 ParseValue(LHS->getType(), RHS, PFS))
5403 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005404
Chris Lattnerac161bf2009-01-02 07:01:27 +00005405 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005406 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005407 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005408 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005409 } else {
5410 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005411 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005412 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005413 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005414 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005415 }
5416 return false;
5417}
5418
5419//===----------------------------------------------------------------------===//
5420// Other Instructions.
5421//===----------------------------------------------------------------------===//
5422
5423
5424/// ParseCast
5425/// ::= CastOpc TypeAndValue 'to' Type
5426bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5427 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005428 LocTy Loc;
5429 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005430 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005431 if (ParseTypeAndValue(Op, Loc, PFS) ||
5432 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5433 ParseType(DestTy))
5434 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005435
Chris Lattner89d856e2009-03-01 00:53:13 +00005436 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5437 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005438 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005439 getTypeString(Op->getType()) + "' to '" +
5440 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005441 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005442 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5443 return false;
5444}
5445
5446/// ParseSelect
5447/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5448bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5449 LocTy Loc;
5450 Value *Op0, *Op1, *Op2;
5451 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5452 ParseToken(lltok::comma, "expected ',' after select condition") ||
5453 ParseTypeAndValue(Op1, PFS) ||
5454 ParseToken(lltok::comma, "expected ',' after select value") ||
5455 ParseTypeAndValue(Op2, PFS))
5456 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005457
Chris Lattnerac161bf2009-01-02 07:01:27 +00005458 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5459 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005460
Chris Lattnerac161bf2009-01-02 07:01:27 +00005461 Inst = SelectInst::Create(Op0, Op1, Op2);
5462 return false;
5463}
5464
Chris Lattnerb55ab542009-01-05 08:18:44 +00005465/// ParseVA_Arg
5466/// ::= 'va_arg' TypeAndValue ',' Type
5467bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005468 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005469 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005470 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005471 if (ParseTypeAndValue(Op, PFS) ||
5472 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005473 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005474 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005475
Chris Lattnerb55ab542009-01-05 08:18:44 +00005476 if (!EltTy->isFirstClassType())
5477 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005478
5479 Inst = new VAArgInst(Op, EltTy);
5480 return false;
5481}
5482
5483/// ParseExtractElement
5484/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5485bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5486 LocTy Loc;
5487 Value *Op0, *Op1;
5488 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5489 ParseToken(lltok::comma, "expected ',' after extract value") ||
5490 ParseTypeAndValue(Op1, PFS))
5491 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005492
Chris Lattnerac161bf2009-01-02 07:01:27 +00005493 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5494 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005495
Eric Christopherc9742252009-07-25 02:28:41 +00005496 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005497 return false;
5498}
5499
5500/// ParseInsertElement
5501/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5502bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5503 LocTy Loc;
5504 Value *Op0, *Op1, *Op2;
5505 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5506 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5507 ParseTypeAndValue(Op1, PFS) ||
5508 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5509 ParseTypeAndValue(Op2, PFS))
5510 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005511
Chris Lattnerac161bf2009-01-02 07:01:27 +00005512 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005513 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005514
Chris Lattnerac161bf2009-01-02 07:01:27 +00005515 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5516 return false;
5517}
5518
5519/// ParseShuffleVector
5520/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5521bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5522 LocTy Loc;
5523 Value *Op0, *Op1, *Op2;
5524 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5525 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5526 ParseTypeAndValue(Op1, PFS) ||
5527 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5528 ParseTypeAndValue(Op2, PFS))
5529 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005530
Chris Lattnerac161bf2009-01-02 07:01:27 +00005531 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005532 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005533
Chris Lattnerac161bf2009-01-02 07:01:27 +00005534 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5535 return false;
5536}
5537
5538/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005539/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005540int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005541 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005542 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005543
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005544 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005545 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5546 ParseValue(Ty, Op0, PFS) ||
5547 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005548 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5550 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005551
Chris Lattnerf4f03422009-12-30 05:27:33 +00005552 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005553 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5554 while (1) {
5555 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005556
Chris Lattner3822f632009-01-02 08:05:26 +00005557 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005558 break;
5559
Chris Lattnerf4f03422009-12-30 05:27:33 +00005560 if (Lex.getKind() == lltok::MetadataVar) {
5561 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005562 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005563 }
Devang Patel8f842d32009-10-16 18:45:49 +00005564
Chris Lattner3822f632009-01-02 08:05:26 +00005565 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005566 ParseValue(Ty, Op0, PFS) ||
5567 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005568 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005569 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5570 return true;
5571 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005572
Chris Lattnerac161bf2009-01-02 07:01:27 +00005573 if (!Ty->isFirstClassType())
5574 return Error(TypeLoc, "phi node must have first class type");
5575
Jay Foad52131342011-03-30 11:28:46 +00005576 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005577 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5578 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5579 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005580 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005581}
5582
Bill Wendlingfae14752011-08-12 20:24:12 +00005583/// ParseLandingPad
5584/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5585/// Clause
5586/// ::= 'catch' TypeAndValue
5587/// ::= 'filter'
5588/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5589bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005590 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005591
David Majnemer7fddecc2015-06-17 20:52:32 +00005592 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005593 return true;
5594
David Majnemer7fddecc2015-06-17 20:52:32 +00005595 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005596 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5597
5598 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5599 LandingPadInst::ClauseType CT;
5600 if (EatIfPresent(lltok::kw_catch))
5601 CT = LandingPadInst::Catch;
5602 else if (EatIfPresent(lltok::kw_filter))
5603 CT = LandingPadInst::Filter;
5604 else
5605 return TokError("expected 'catch' or 'filter' clause type");
5606
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005607 Value *V;
5608 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005609 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005610 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005611
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005612 // A 'catch' type expects a non-array constant. A filter clause expects an
5613 // array constant.
5614 if (CT == LandingPadInst::Catch) {
5615 if (isa<ArrayType>(V->getType()))
5616 Error(VLoc, "'catch' clause has an invalid type");
5617 } else {
5618 if (!isa<ArrayType>(V->getType()))
5619 Error(VLoc, "'filter' clause has an invalid type");
5620 }
5621
Owen Andersonf8f259d2015-03-09 07:13:42 +00005622 Constant *CV = dyn_cast<Constant>(V);
5623 if (!CV)
5624 return Error(VLoc, "clause argument must be a constant");
5625 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005626 }
5627
Owen Andersonf8f259d2015-03-09 07:13:42 +00005628 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005629 return false;
5630}
5631
Chris Lattnerac161bf2009-01-02 07:01:27 +00005632/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005633/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5634/// OptionalAttrs Type Value ParameterList OptionalAttrs
5635/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5636/// OptionalAttrs Type Value ParameterList OptionalAttrs
5637/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5638/// OptionalAttrs Type Value ParameterList OptionalAttrs
5639/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5640/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005641bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005642 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005643 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005644 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005645 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005646 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005647 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648 LocTy RetTypeLoc;
5649 ValID CalleeID;
5650 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005651 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005652 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005653
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005654 if (TCK != CallInst::TCK_None &&
5655 ParseToken(lltok::kw_call,
5656 "expected 'tail call', 'musttail call', or 'notail call'"))
5657 return true;
5658
5659 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5660
5661 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005662 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005663 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005664 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5665 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005666 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5667 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005668 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005669
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005670 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5671 return Error(CallLoc, "fast-math-flags specified for call without "
5672 "floating-point scalar or vector return type");
5673
Chris Lattnerac161bf2009-01-02 07:01:27 +00005674 // If RetType is a non-function pointer type, then this is the short syntax
5675 // for the call, which means that RetType is just the return type. Infer the
5676 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005677 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5678 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005679 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005680 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005681 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5682 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005683
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 if (!FunctionType::isValidReturnType(RetType))
5685 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005686
Owen Anderson4056ca92009-07-29 22:17:13 +00005687 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005688 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005689
David Blaikie41ba2b42015-07-27 23:32:19 +00005690 CalleeID.FTy = Ty;
5691
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 // Look up the callee.
5693 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005694 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5695 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005696
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005697 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005698 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005699 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005700 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5701 AttributeSet::ReturnIndex,
5702 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005703
Chris Lattnerac161bf2009-01-02 07:01:27 +00005704 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005705
Chris Lattnerac161bf2009-01-02 07:01:27 +00005706 // Loop through FunctionType's arguments and ensure they are specified
5707 // correctly. Also, gather any parameter attributes.
5708 FunctionType::param_iterator I = Ty->param_begin();
5709 FunctionType::param_iterator E = Ty->param_end();
5710 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005711 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005712 if (I != E) {
5713 ExpectedTy = *I++;
5714 } else if (!Ty->isVarArg()) {
5715 return Error(ArgList[i].Loc, "too many arguments specified");
5716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005717
Chris Lattnerac161bf2009-01-02 07:01:27 +00005718 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5719 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005720 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005721 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005722 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5723 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005724 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5725 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005726 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005727
Chris Lattnerac161bf2009-01-02 07:01:27 +00005728 if (I != E)
5729 return Error(CallLoc, "not enough parameters specified for call");
5730
David Majnemer8d22abd2015-02-23 00:01:32 +00005731 if (FnAttrs.hasAttributes()) {
5732 if (FnAttrs.hasAlignmentAttr())
5733 return Error(CallLoc, "call instructions may not have an alignment");
5734
Bill Wendlingf5075a42013-01-27 02:24:02 +00005735 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5736 AttributeSet::FunctionIndex,
5737 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005738 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005739
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005740 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005741 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005742
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005743 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00005744 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005745 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005746 if (FMF.any())
5747 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005748 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005749 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005750 Inst = CI;
5751 return false;
5752}
5753
5754//===----------------------------------------------------------------------===//
5755// Memory Instructions.
5756//===----------------------------------------------------------------------===//
5757
5758/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005759/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005760int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005761 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005762 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005763 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005764 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005765
5766 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5767
David Majnemera3b0eb22015-02-16 08:38:03 +00005768 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005769
David Majnemera3b0eb22015-02-16 08:38:03 +00005770 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5771 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005772
Chris Lattnerb2f39502009-12-30 05:44:30 +00005773 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005774 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005775 if (Lex.getKind() == lltok::kw_align) {
5776 if (ParseOptionalAlignment(Alignment)) return true;
5777 } else if (Lex.getKind() == lltok::MetadataVar) {
5778 AteExtraComma = true;
5779 } else {
5780 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5781 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5782 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005783 }
5784 }
5785
Dan Gohman2140a742010-05-28 01:14:11 +00005786 if (Size && !Size->getType()->isIntegerTy())
5787 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005788
Reid Kleckner436c42e2014-01-17 23:58:17 +00005789 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5790 AI->setUsedWithInAlloca(IsInAlloca);
5791 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005792 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005793}
5794
5795/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005796/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005797/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005798/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005799int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005800 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005801 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005802 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005803 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005804 AtomicOrdering Ordering = NotAtomic;
5805 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005806
5807 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005808 isAtomic = true;
5809 Lex.Lex();
5810 }
5811
Chris Lattnerbc639292011-11-27 06:56:53 +00005812 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005813 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005814 isVolatile = true;
5815 Lex.Lex();
5816 }
5817
David Blaikie15d9a4c2015-04-06 20:59:48 +00005818 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005819 LocTy ExplicitTypeLoc = Lex.getLoc();
5820 if (ParseType(Ty) ||
5821 ParseToken(lltok::comma, "expected comma after load's type") ||
5822 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005823 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005824 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5825 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005826
David Blaikie15d9a4c2015-04-06 20:59:48 +00005827 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005829 if (isAtomic && !Alignment)
5830 return Error(Loc, "atomic load must have explicit non-zero alignment");
5831 if (Ordering == Release || Ordering == AcquireRelease)
5832 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005833
David Blaikiea79ac142015-02-27 21:17:42 +00005834 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5835 return Error(ExplicitTypeLoc,
5836 "explicit pointee type doesn't match operand's pointee type");
5837
David Blaikie15d9a4c2015-04-06 20:59:48 +00005838 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005839 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005840}
5841
5842/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005843
5844/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5845/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005846/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005847int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005848 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005849 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005850 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005851 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005852 AtomicOrdering Ordering = NotAtomic;
5853 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005854
5855 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005856 isAtomic = true;
5857 Lex.Lex();
5858 }
5859
Chris Lattnerbc639292011-11-27 06:56:53 +00005860 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005861 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005862 isVolatile = true;
5863 Lex.Lex();
5864 }
5865
Chris Lattnerac161bf2009-01-02 07:01:27 +00005866 if (ParseTypeAndValue(Val, Loc, PFS) ||
5867 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005868 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005869 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005870 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005871 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005872
Duncan Sands19d0b472010-02-16 11:11:14 +00005873 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005874 return Error(PtrLoc, "store operand must be a pointer");
5875 if (!Val->getType()->isFirstClassType())
5876 return Error(Loc, "store operand must be a first class value");
5877 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5878 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005879 if (isAtomic && !Alignment)
5880 return Error(Loc, "atomic store must have explicit non-zero alignment");
5881 if (Ordering == Acquire || Ordering == AcquireRelease)
5882 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005883
Eli Friedman59b66882011-08-09 23:02:53 +00005884 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005885 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005886}
5887
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005888/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005889/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5890/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005891int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005892 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5893 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005894 AtomicOrdering SuccessOrdering = NotAtomic;
5895 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005896 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005897 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005898 bool isWeak = false;
5899
5900 if (EatIfPresent(lltok::kw_weak))
5901 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005902
5903 if (EatIfPresent(lltok::kw_volatile))
5904 isVolatile = true;
5905
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005906 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5907 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5908 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5909 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5910 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005911 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5912 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005913 return true;
5914
Tim Northovere94a5182014-03-11 10:48:52 +00005915 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005916 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005917 if (SuccessOrdering < FailureOrdering)
5918 return TokError("cmpxchg must be at least as ordered on success as failure");
5919 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5920 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005921 if (!Ptr->getType()->isPointerTy())
5922 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5923 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5924 return Error(CmpLoc, "compare value and pointer type do not match");
5925 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5926 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00005927 if (!New->getType()->isFirstClassType())
5928 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00005929 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5930 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005931 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005932 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005933 Inst = CXI;
5934 return AteExtraComma ? InstExtraComma : InstNormal;
5935}
5936
5937/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005938/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5939/// 'singlethread'? AtomicOrdering
5940int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005941 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5942 bool AteExtraComma = false;
5943 AtomicOrdering Ordering = NotAtomic;
5944 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005945 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005946 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005947
5948 if (EatIfPresent(lltok::kw_volatile))
5949 isVolatile = true;
5950
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005951 switch (Lex.getKind()) {
5952 default: return TokError("expected binary operation in atomicrmw");
5953 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5954 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5955 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5956 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5957 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5958 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5959 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5960 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5961 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5962 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5963 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5964 }
5965 Lex.Lex(); // Eat the operation.
5966
5967 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5968 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5969 ParseTypeAndValue(Val, ValLoc, PFS) ||
5970 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5971 return true;
5972
5973 if (Ordering == Unordered)
5974 return TokError("atomicrmw cannot be unordered");
5975 if (!Ptr->getType()->isPointerTy())
5976 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5977 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5978 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5979 if (!Val->getType()->isIntegerTy())
5980 return Error(ValLoc, "atomicrmw operand must be an integer");
5981 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5982 if (Size < 8 || (Size & (Size - 1)))
5983 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5984 " integer");
5985
5986 AtomicRMWInst *RMWI =
5987 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5988 RMWI->setVolatile(isVolatile);
5989 Inst = RMWI;
5990 return AteExtraComma ? InstExtraComma : InstNormal;
5991}
5992
Eli Friedmanfee02c62011-07-25 23:16:38 +00005993/// ParseFence
5994/// ::= 'fence' 'singlethread'? AtomicOrdering
5995int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5996 AtomicOrdering Ordering = NotAtomic;
5997 SynchronizationScope Scope = CrossThread;
5998 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5999 return true;
6000
6001 if (Ordering == Unordered)
6002 return TokError("fence cannot be unordered");
6003 if (Ordering == Monotonic)
6004 return TokError("fence cannot be monotonic");
6005
6006 Inst = new FenceInst(Context, Ordering, Scope);
6007 return InstNormal;
6008}
6009
Chris Lattnerac161bf2009-01-02 07:01:27 +00006010/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006011/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006012int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006013 Value *Ptr = nullptr;
6014 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006015 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006016
Dan Gohman16cbbe42009-07-29 15:58:36 +00006017 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006018
David Blaikie79e6c742015-02-27 19:29:02 +00006019 Type *Ty = nullptr;
6020 LocTy ExplicitTypeLoc = Lex.getLoc();
6021 if (ParseType(Ty) ||
6022 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6023 ParseTypeAndValue(Ptr, Loc, PFS))
6024 return true;
6025
Eli Benderskyd9806682013-04-22 17:03:42 +00006026 Type *BaseType = Ptr->getType();
6027 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6028 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006029 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006030
David Blaikie8d757942015-03-09 23:08:44 +00006031 if (Ty != BasePointerType->getElementType())
6032 return Error(ExplicitTypeLoc,
6033 "explicit pointee type doesn't match operand's pointee type");
6034
Chris Lattnerac161bf2009-01-02 07:01:27 +00006035 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006036 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006037 // GEP returns a vector of pointers if at least one of parameters is a vector.
6038 // All vector parameters should have the same vector width.
6039 unsigned GEPWidth = BaseType->isVectorTy() ?
6040 BaseType->getVectorNumElements() : 0;
6041
Chris Lattner3822f632009-01-02 08:05:26 +00006042 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006043 if (Lex.getKind() == lltok::MetadataVar) {
6044 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006045 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006046 }
Chris Lattner3822f632009-01-02 08:05:26 +00006047 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006048 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006049 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006050
Nadav Rotem3924cb02011-12-05 06:29:09 +00006051 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006052 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6053 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006054 return Error(EltLoc,
6055 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006056 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006057 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006058 Indices.push_back(Val);
6059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006060
Craig Toppere3dcce92015-08-01 22:20:21 +00006061 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006062 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006063 return Error(Loc, "base element of getelementptr must be sized");
6064
David Blaikied33bad32015-04-17 22:32:13 +00006065 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006066 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006067 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006068 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006069 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006070 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006071}
6072
6073/// ParseExtractValue
6074/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006075int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006076 Value *Val; LocTy Loc;
6077 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006078 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006079 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006080 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006081 return true;
6082
Chris Lattner392be582010-02-12 20:49:41 +00006083 if (!Val->getType()->isAggregateType())
6084 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006085
Jay Foad57aa6362011-07-13 10:26:04 +00006086 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006087 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006088 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006089 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006090}
6091
6092/// ParseInsertValue
6093/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006094int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006095 Value *Val0, *Val1; LocTy Loc0, Loc1;
6096 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006097 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006098 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6099 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6100 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006101 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006102 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006103
Chris Lattner392be582010-02-12 20:49:41 +00006104 if (!Val0->getType()->isAggregateType())
6105 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006106
David Majnemer30074532015-02-11 07:43:58 +00006107 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6108 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006109 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006110 if (IndexedType != Val1->getType())
6111 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6112 getTypeString(Val1->getType()) + "' instead of '" +
6113 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006114 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006115 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006116}
Nick Lewycky49f89192009-04-04 07:22:01 +00006117
6118//===----------------------------------------------------------------------===//
6119// Embedded metadata.
6120//===----------------------------------------------------------------------===//
6121
6122/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006123/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006124/// Element
6125/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006126bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006127 if (ParseToken(lltok::lbrace, "expected '{' here"))
6128 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006129
Dan Gohman1e0213a2010-07-13 19:33:27 +00006130 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006131 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006132 return false;
6133
Nick Lewycky49f89192009-04-04 07:22:01 +00006134 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006135 // Null is a special case since it is typeless.
6136 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006137 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006138 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006139 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006140
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006141 Metadata *MD;
6142 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006143 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006144 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006145 } while (EatIfPresent(lltok::comma));
6146
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006147 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006148}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006149
6150//===----------------------------------------------------------------------===//
6151// Use-list order directives.
6152//===----------------------------------------------------------------------===//
6153bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6154 SMLoc Loc) {
6155 if (V->use_empty())
6156 return Error(Loc, "value has no uses");
6157
6158 unsigned NumUses = 0;
6159 SmallDenseMap<const Use *, unsigned, 16> Order;
6160 for (const Use &U : V->uses()) {
6161 if (++NumUses > Indexes.size())
6162 break;
6163 Order[&U] = Indexes[NumUses - 1];
6164 }
6165 if (NumUses < 2)
6166 return Error(Loc, "value only has one use");
6167 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6168 return Error(Loc, "wrong number of indexes, expected " +
6169 Twine(std::distance(V->use_begin(), V->use_end())));
6170
6171 V->sortUseList([&](const Use &L, const Use &R) {
6172 return Order.lookup(&L) < Order.lookup(&R);
6173 });
6174 return false;
6175}
6176
6177/// ParseUseListOrderIndexes
6178/// ::= '{' uint32 (',' uint32)+ '}'
6179bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6180 SMLoc Loc = Lex.getLoc();
6181 if (ParseToken(lltok::lbrace, "expected '{' here"))
6182 return true;
6183 if (Lex.getKind() == lltok::rbrace)
6184 return Lex.Error("expected non-empty list of uselistorder indexes");
6185
6186 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6187 // indexes should be distinct numbers in the range [0, size-1], and should
6188 // not be in order.
6189 unsigned Offset = 0;
6190 unsigned Max = 0;
6191 bool IsOrdered = true;
6192 assert(Indexes.empty() && "Expected empty order vector");
6193 do {
6194 unsigned Index;
6195 if (ParseUInt32(Index))
6196 return true;
6197
6198 // Update consistency checks.
6199 Offset += Index - Indexes.size();
6200 Max = std::max(Max, Index);
6201 IsOrdered &= Index == Indexes.size();
6202
6203 Indexes.push_back(Index);
6204 } while (EatIfPresent(lltok::comma));
6205
6206 if (ParseToken(lltok::rbrace, "expected '}' here"))
6207 return true;
6208
6209 if (Indexes.size() < 2)
6210 return Error(Loc, "expected >= 2 uselistorder indexes");
6211 if (Offset != 0 || Max >= Indexes.size())
6212 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6213 if (IsOrdered)
6214 return Error(Loc, "expected uselistorder indexes to change the order");
6215
6216 return false;
6217}
6218
6219/// ParseUseListOrder
6220/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6221bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6222 SMLoc Loc = Lex.getLoc();
6223 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6224 return true;
6225
6226 Value *V;
6227 SmallVector<unsigned, 16> Indexes;
6228 if (ParseTypeAndValue(V, PFS) ||
6229 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6230 ParseUseListOrderIndexes(Indexes))
6231 return true;
6232
6233 return sortUseListOrder(V, Indexes, Loc);
6234}
6235
6236/// ParseUseListOrderBB
6237/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6238bool LLParser::ParseUseListOrderBB() {
6239 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6240 SMLoc Loc = Lex.getLoc();
6241 Lex.Lex();
6242
6243 ValID Fn, Label;
6244 SmallVector<unsigned, 16> Indexes;
6245 if (ParseValID(Fn) ||
6246 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6247 ParseValID(Label) ||
6248 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6249 ParseUseListOrderIndexes(Indexes))
6250 return true;
6251
6252 // Check the function.
6253 GlobalValue *GV;
6254 if (Fn.Kind == ValID::t_GlobalName)
6255 GV = M->getNamedValue(Fn.StrVal);
6256 else if (Fn.Kind == ValID::t_GlobalID)
6257 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6258 else
6259 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6260 if (!GV)
6261 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6262 auto *F = dyn_cast<Function>(GV);
6263 if (!F)
6264 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6265 if (F->isDeclaration())
6266 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6267
6268 // Check the basic block.
6269 if (Label.Kind == ValID::t_LocalID)
6270 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6271 if (Label.Kind != ValID::t_LocalName)
6272 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6273 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6274 if (!V)
6275 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6276 if (!isa<BasicBlock>(V))
6277 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6278
6279 return sortUseListOrder(V, Indexes, Loc);
6280}