Bug Summary

File:lib/AsmParser/LLParser.cpp
Warning:line 1239, column 7
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LLParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/AsmParser -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp -faddrsig
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LLParser.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/SlotMapping.h"
20#include "llvm/BinaryFormat/Dwarf.h"
21#include "llvm/IR/Argument.h"
22#include "llvm/IR/AutoUpgrade.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallingConv.h"
25#include "llvm/IR/Comdat.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DebugInfoMetadata.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
42#include "llvm/IR/ValueSymbolTable.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/SaveAndRestore.h"
47#include "llvm/Support/raw_ostream.h"
48#include <algorithm>
49#include <cassert>
50#include <cstring>
51#include <iterator>
52#include <vector>
53
54using namespace llvm;
55
56static std::string getTypeString(Type *T) {
57 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
61}
62
63/// Run: module ::= toplevelentity*
64bool LLParser::Run() {
65 // Prime the lexer.
66 Lex.Lex();
67
68 if (Context.shouldDiscardValueNames())
1
Assuming the condition is false
2
Taking false branch
69 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
3
Calling 'LLParser::ParseTopLevelEntities'
74 ValidateEndOfIndex();
75}
76
77bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
80 Lex.Lex();
81
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
88}
89
90bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
92 restoreParsingState(Slots);
93 Lex.Lex();
94
95 Read = 0;
96 SMLoc Start = Lex.getLoc();
97 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
102
103 return false;
104}
105
106void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
117}
118
119/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120/// module.
121bool LLParser::ValidateEndOfModule() {
122 if (!M)
123 return false;
124 // Handle any function attribute group forward references.
125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
128 AttrBuilder B;
129
130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
132
133 if (Function *Fn = dyn_cast<Function>(V)) {
134 AttributeList AS = Fn->getAttributes();
135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151 AttributeList AS = CI->getAttributes();
152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154 FnAttrs.merge(B);
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
159 AttributeList AS = II->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 FnAttrs.merge(B);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 II->setAttributes(AS);
166 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167 AttributeList AS = CBI->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 CBI->setAttributes(AS);
174 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175 AttrBuilder Attrs(GV->getAttributes());
176 Attrs.merge(B);
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
178 } else {
179 llvm_unreachable("invalid object with forward attribute group reference")::llvm::llvm_unreachable_internal("invalid object with forward attribute group reference"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 179)
;
180 }
181 }
182
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses.empty())
186 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187 "expected function name in blockaddress");
188
189 for (const auto &NT : NumberedTypes)
190 if (NT.second.second.isValid())
191 return Error(NT.second.second,
192 "use of undefined type '%" + Twine(NT.first) + "'");
193
194 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196 if (I->second.second.isValid())
197 return Error(I->second.second,
198 "use of undefined type named '" + I->getKey() + "'");
199
200 if (!ForwardRefComdats.empty())
201 return Error(ForwardRefComdats.begin()->second,
202 "use of undefined comdat '$" +
203 ForwardRefComdats.begin()->first + "'");
204
205 if (!ForwardRefVals.empty())
206 return Error(ForwardRefVals.begin()->second.second,
207 "use of undefined value '@" + ForwardRefVals.begin()->first +
208 "'");
209
210 if (!ForwardRefValIDs.empty())
211 return Error(ForwardRefValIDs.begin()->second.second,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs.begin()->first) + "'");
214
215 if (!ForwardRefMDNodes.empty())
216 return Error(ForwardRefMDNodes.begin()->second.second,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes.begin()->first) + "'");
219
220 // Resolve metadata cycles.
221 for (auto &N : NumberedMetadata) {
222 if (N.second && !N.second->isResolved())
223 N.second->resolveCycles();
224 }
225
226 for (auto *Inst : InstsWithTBAATag) {
227 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag")((MD && "UpgradeInstWithTBAATag should have a TBAA tag"
) ? static_cast<void> (0) : __assert_fail ("MD && \"UpgradeInstWithTBAATag should have a TBAA tag\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 228, __PRETTY_FUNCTION__))
;
229 auto *UpgradedMD = UpgradeTBAANode(*MD);
230 if (MD != UpgradedMD)
231 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
232 }
233
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
236 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
237
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242 Function *F = &*FI++;
243 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244 F->replaceAllUsesWith(Remangled.getValue());
245 F->eraseFromParent();
246 }
247 }
248
249 if (UpgradeDebugInfo)
250 llvm::UpgradeDebugInfo(*M);
251
252 UpgradeModuleFlags(*M);
253 UpgradeSectionAttributes(*M);
254
255 if (!Slots)
256 return false;
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots->GlobalValues = std::move(NumberedVals);
261 Slots->MetadataNodes = std::move(NumberedMetadata);
262 for (const auto &I : NamedTypes)
263 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264 for (const auto &I : NumberedTypes)
265 Slots->Types.insert(std::make_pair(I.first, I.second.first));
266
267 return false;
268}
269
270/// Do final validity and sanity checks at the end of the index.
271bool LLParser::ValidateEndOfIndex() {
272 if (!Index)
273 return false;
274
275 if (!ForwardRefValueInfos.empty())
276 return Error(ForwardRefValueInfos.begin()->second.front().second,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos.begin()->first) + "'");
279
280 if (!ForwardRefAliasees.empty())
281 return Error(ForwardRefAliasees.begin()->second.front().second,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees.begin()->first) + "'");
284
285 if (!ForwardRefTypeIds.empty())
286 return Error(ForwardRefTypeIds.begin()->second.front().second,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds.begin()->first) + "'");
289
290 return false;
291}
292
293//===----------------------------------------------------------------------===//
294// Top-Level Entities
295//===----------------------------------------------------------------------===//
296
297bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
299 if (!M) {
4
Assuming the condition is false
5
Taking false branch
300 while (true) {
301 switch (Lex.getKind()) {
302 case lltok::Eof:
303 return false;
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
306 return true;
307 break;
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
310 return true;
311 break;
312 default:
313 // Skip everything else
314 Lex.Lex();
315 }
316 }
317 }
318 while (true) {
6
Loop condition is true. Entering loop body
319 switch (Lex.getKind()) {
7
Control jumps to 'case kw_attributes:' at line 342
320 default: return TokError("expected top-level entity");
321 case lltok::Eof: return false;
322 case lltok::kw_declare: if (ParseDeclare()) return true; break;
323 case lltok::kw_define: if (ParseDefine()) return true; break;
324 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename:
327 if (ParseSourceFileName())
328 return true;
329 break;
330 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar: if (parseComdat()) return true; break;
336 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID:
338 if (ParseSummaryEntry())
339 return true;
340 break;
341 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
8
Calling 'LLParser::ParseUnnamedAttrGrp'
343 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb:
345 if (ParseUseListOrderBB())
346 return true;
347 break;
348 }
349 }
350}
351
352/// toplevelentity
353/// ::= 'module' 'asm' STRINGCONSTANT
354bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module)((Lex.getKind() == lltok::kw_module) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_module", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 355, __PRETTY_FUNCTION__))
;
356 Lex.Lex();
357
358 std::string AsmStr;
359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
361
362 M->appendModuleInlineAsm(AsmStr);
363 return false;
364}
365
366/// toplevelentity
367/// ::= 'target' 'triple' '=' STRINGCONSTANT
368/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target)((Lex.getKind() == lltok::kw_target) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_target", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 370, __PRETTY_FUNCTION__))
;
371 std::string Str;
372 switch (Lex.Lex()) {
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
375 Lex.Lex();
376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
378 return true;
379 M->setTargetTriple(Str);
380 return false;
381 case lltok::kw_datalayout:
382 Lex.Lex();
383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
385 return true;
386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
388 return false;
389 }
390}
391
392/// toplevelentity
393/// ::= 'source_filename' '=' STRINGCONSTANT
394bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename)((Lex.getKind() == lltok::kw_source_filename) ? static_cast<
void> (0) : __assert_fail ("Lex.getKind() == lltok::kw_source_filename"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 Lex.Lex();
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName))
399 return true;
400 if (M)
401 M->setSourceFileName(SourceFileName);
402 return false;
403}
404
405/// toplevelentity
406/// ::= 'deplibs' '=' '[' ']'
407/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408/// FIXME: Remove in 4.0. Currently parse, but ignore.
409bool LLParser::ParseDepLibs() {
410 assert(Lex.getKind() == lltok::kw_deplibs)((Lex.getKind() == lltok::kw_deplibs) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_deplibs", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 410, __PRETTY_FUNCTION__))
;
411 Lex.Lex();
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414 return true;
415
416 if (EatIfPresent(lltok::rsquare))
417 return false;
418
419 do {
420 std::string Str;
421 if (ParseStringConstant(Str)) return true;
422 } while (EatIfPresent(lltok::comma));
423
424 return ParseToken(lltok::rsquare, "expected ']' at end of list");
425}
426
427/// ParseUnnamedType:
428/// ::= LocalVarID '=' 'type' type
429bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc = Lex.getLoc();
431 unsigned TypeID = Lex.getUIntVal();
432 Lex.Lex(); // eat LocalVarID;
433
434 if (ParseToken(lltok::equal, "expected '=' after name") ||
435 ParseToken(lltok::kw_type, "expected 'type' after '='"))
436 return true;
437
438 Type *Result = nullptr;
439 if (ParseStructDefinition(TypeLoc, "",
440 NumberedTypes[TypeID], Result)) return true;
441
442 if (!isa<StructType>(Result)) {
443 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
444 if (Entry.first)
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
448 }
449
450 return false;
451}
452
453/// toplevelentity
454/// ::= LocalVar '=' 'type' type
455bool LLParser::ParseNamedType() {
456 std::string Name = Lex.getStrVal();
457 LocTy NameLoc = Lex.getLoc();
458 Lex.Lex(); // eat LocalVar.
459
460 if (ParseToken(lltok::equal, "expected '=' after name") ||
461 ParseToken(lltok::kw_type, "expected 'type' after name"))
462 return true;
463
464 Type *Result = nullptr;
465 if (ParseStructDefinition(NameLoc, Name,
466 NamedTypes[Name], Result)) return true;
467
468 if (!isa<StructType>(Result)) {
469 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
470 if (Entry.first)
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
474 }
475
476 return false;
477}
478
479/// toplevelentity
480/// ::= 'declare' FunctionHeader
481bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare)((Lex.getKind() == lltok::kw_declare) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_declare", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 482, __PRETTY_FUNCTION__))
;
483 Lex.Lex();
484
485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
487 unsigned MDK;
488 MDNode *N;
489 if (ParseMetadataAttachment(MDK, N))
490 return true;
491 MDs.push_back({MDK, N});
492 }
493
494 Function *F;
495 if (ParseFunctionHeader(F, false))
496 return true;
497 for (auto &MD : MDs)
498 F->addMetadata(MD.first, *MD.second);
499 return false;
500}
501
502/// toplevelentity
503/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define)((Lex.getKind() == lltok::kw_define) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_define", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 505, __PRETTY_FUNCTION__))
;
506 Lex.Lex();
507
508 Function *F;
509 return ParseFunctionHeader(F, true) ||
510 ParseOptionalFunctionMetadata(*F) ||
511 ParseFunctionBody(*F);
512}
513
514/// ParseGlobalType
515/// ::= 'constant'
516/// ::= 'global'
517bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
519 IsConstant = true;
520 else if (Lex.getKind() == lltok::kw_global)
521 IsConstant = false;
522 else {
523 IsConstant = false;
524 return TokError("expected 'global' or 'constant'");
525 }
526 Lex.Lex();
527 return false;
528}
529
530bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr &UnnamedAddr) {
532 if (EatIfPresent(lltok::kw_unnamed_addr))
533 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
536 else
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
538 return false;
539}
540
541/// ParseUnnamedGlobal:
542/// OptionalVisibility (ALIAS | IFUNC) ...
543/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544/// OptionalDLLStorageClass
545/// ... -> global variable
546/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548/// OptionalDLLStorageClass
549/// ... -> global variable
550bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID = NumberedVals.size();
552 std::string Name;
553 LocTy NameLoc = Lex.getLoc();
554
555 // Handle the GlobalID form.
556 if (Lex.getKind() == lltok::GlobalID) {
557 if (Lex.getUIntVal() != VarID)
558 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
559 Twine(VarID) + "'");
560 Lex.Lex(); // eat GlobalID;
561
562 if (ParseToken(lltok::equal, "expected '=' after name"))
563 return true;
564 }
565
566 bool HasLinkage;
567 unsigned Linkage, Visibility, DLLStorageClass;
568 bool DSOLocal;
569 GlobalVariable::ThreadLocalMode TLM;
570 GlobalVariable::UnnamedAddr UnnamedAddr;
571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572 DSOLocal) ||
573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
574 return true;
575
576 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
577 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
578 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
579
580 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
581 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
582}
583
584/// ParseNamedGlobal:
585/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587/// OptionalVisibility OptionalDLLStorageClass
588/// ... -> global variable
589bool LLParser::ParseNamedGlobal() {
590 assert(Lex.getKind() == lltok::GlobalVar)((Lex.getKind() == lltok::GlobalVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::GlobalVar", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 590, __PRETTY_FUNCTION__))
;
591 LocTy NameLoc = Lex.getLoc();
592 std::string Name = Lex.getStrVal();
593 Lex.Lex();
594
595 bool HasLinkage;
596 unsigned Linkage, Visibility, DLLStorageClass;
597 bool DSOLocal;
598 GlobalVariable::ThreadLocalMode TLM;
599 GlobalVariable::UnnamedAddr UnnamedAddr;
600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602 DSOLocal) ||
603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
604 return true;
605
606 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
607 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
608 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
609
610 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
612}
613
614bool LLParser::parseComdat() {
615 assert(Lex.getKind() == lltok::ComdatVar)((Lex.getKind() == lltok::ComdatVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::ComdatVar", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 615, __PRETTY_FUNCTION__))
;
616 std::string Name = Lex.getStrVal();
617 LocTy NameLoc = Lex.getLoc();
618 Lex.Lex();
619
620 if (ParseToken(lltok::equal, "expected '=' here"))
621 return true;
622
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
625
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
628 default:
629 return TokError("unknown selection kind");
630 case lltok::kw_any:
631 SK = Comdat::Any;
632 break;
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
635 break;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
638 break;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
641 break;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
644 break;
645 }
646 Lex.Lex();
647
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
653
654 Comdat *C;
655 if (I != ComdatSymTab.end())
656 C = &I->second;
657 else
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
660
661 return false;
662}
663
664// MDString:
665// ::= '!' STRINGCONSTANT
666bool LLParser::ParseMDString(MDString *&Result) {
667 std::string Str;
668 if (ParseStringConstant(Str)) return true;
669 Result = MDString::get(Context, Str);
670 return false;
671}
672
673// MDNode:
674// ::= '!' MDNodeNumber
675bool LLParser::ParseMDNodeID(MDNode *&Result) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc = Lex.getLoc();
678 unsigned MID = 0;
679 if (ParseUInt32(MID))
680 return true;
681
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata.count(MID)) {
684 Result = NumberedMetadata[MID];
685 return false;
686 }
687
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef = ForwardRefMDNodes[MID];
690 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
691
692 Result = FwdRef.first.get();
693 NumberedMetadata[MID].reset(Result);
694 return false;
695}
696
697/// ParseNamedMetadata:
698/// !foo = !{ !1, !2 }
699bool LLParser::ParseNamedMetadata() {
700 assert(Lex.getKind() == lltok::MetadataVar)((Lex.getKind() == lltok::MetadataVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 700, __PRETTY_FUNCTION__))
;
701 std::string Name = Lex.getStrVal();
702 Lex.Lex();
703
704 if (ParseToken(lltok::equal, "expected '=' here") ||
705 ParseToken(lltok::exclaim, "Expected '!' here") ||
706 ParseToken(lltok::lbrace, "Expected '{' here"))
707 return true;
708
709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710 if (Lex.getKind() != lltok::rbrace)
711 do {
712 MDNode *N = nullptr;
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex.getKind() == lltok::MetadataVar &&
717 Lex.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N, /*IsDistinct=*/false))
719 return true;
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721 ParseMDNodeID(N)) {
722 return true;
723 }
724 NMD->addOperand(N);
725 } while (EatIfPresent(lltok::comma));
726
727 return ParseToken(lltok::rbrace, "expected end of metadata node");
728}
729
730/// ParseStandaloneMetadata:
731/// !42 = !{...}
732bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex.getKind() == lltok::exclaim)((Lex.getKind() == lltok::exclaim) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::exclaim", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 733, __PRETTY_FUNCTION__))
;
734 Lex.Lex();
735 unsigned MetadataID = 0;
736
737 MDNode *Init;
738 if (ParseUInt32(MetadataID) ||
739 ParseToken(lltok::equal, "expected '=' here"))
740 return true;
741
742 // Detect common error, from old metadata syntax.
743 if (Lex.getKind() == lltok::Type)
744 return TokError("unexpected type in metadata definition");
745
746 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
747 if (Lex.getKind() == lltok::MetadataVar) {
748 if (ParseSpecializedMDNode(Init, IsDistinct))
749 return true;
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
752 return true;
753
754 // See if this was forward referenced, if so, handle it.
755 auto FI = ForwardRefMDNodes.find(MetadataID);
756 if (FI != ForwardRefMDNodes.end()) {
757 FI->second.first->replaceAllUsesWith(Init);
758 ForwardRefMDNodes.erase(FI);
759
760 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work")((NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"
) ? static_cast<void> (0) : __assert_fail ("NumberedMetadata[MetadataID] == Init && \"Tracking VH didn't work\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 760, __PRETTY_FUNCTION__))
;
761 } else {
762 if (NumberedMetadata.count(MetadataID))
763 return TokError("Metadata id is already used");
764 NumberedMetadata[MetadataID].reset(Init);
765 }
766
767 return false;
768}
769
770// Skips a single module summary entry.
771bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777 Lex.getKind() != lltok::kw_typeid)
778 return TokError(
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780 Lex.Lex();
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783 return true;
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen = 1;
787 do {
788 switch (Lex.getKind()) {
789 case lltok::lparen:
790 NumOpenParen++;
791 break;
792 case lltok::rparen:
793 NumOpenParen--;
794 break;
795 case lltok::Eof:
796 return TokError("found end of file while parsing summary entry");
797 default:
798 // Skip everything in between parentheses.
799 break;
800 }
801 Lex.Lex();
802 } while (NumOpenParen > 0);
803 return false;
804}
805
806/// SummaryEntry
807/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808bool LLParser::ParseSummaryEntry() {
809 assert(Lex.getKind() == lltok::SummaryID)((Lex.getKind() == lltok::SummaryID) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::SummaryID", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 809, __PRETTY_FUNCTION__))
;
810 unsigned SummaryID = Lex.getUIntVal();
811
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex.setIgnoreColonInIdentifiers(true);
815
816 Lex.Lex();
817 if (ParseToken(lltok::equal, "expected '=' here"))
818 return true;
819
820 // If we don't have an index object, skip the summary entry.
821 if (!Index)
822 return SkipModuleSummaryEntry();
823
824 bool result = false;
825 switch (Lex.getKind()) {
826 case lltok::kw_gv:
827 result = ParseGVEntry(SummaryID);
828 break;
829 case lltok::kw_module:
830 result = ParseModuleEntry(SummaryID);
831 break;
832 case lltok::kw_typeid:
833 result = ParseTypeIdEntry(SummaryID);
834 break;
835 default:
836 result = Error(Lex.getLoc(), "unexpected summary kind");
837 break;
838 }
839 Lex.setIgnoreColonInIdentifiers(false);
840 return result;
841}
842
843static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
844 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
845 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
846}
847
848// If there was an explicit dso_local, update GV. In the absence of an explicit
849// dso_local we keep the default value.
850static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
851 if (DSOLocal)
852 GV.setDSOLocal(true);
853}
854
855/// parseIndirectSymbol:
856/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
857/// OptionalVisibility OptionalDLLStorageClass
858/// OptionalThreadLocal OptionalUnnamedAddr
859/// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
860///
861/// IndirectSymbol
862/// ::= TypeAndValue
863///
864/// IndirectSymbolAttr
865/// ::= ',' 'partition' StringConstant
866///
867/// Everything through OptionalUnnamedAddr has already been parsed.
868///
869bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
870 unsigned L, unsigned Visibility,
871 unsigned DLLStorageClass, bool DSOLocal,
872 GlobalVariable::ThreadLocalMode TLM,
873 GlobalVariable::UnnamedAddr UnnamedAddr) {
874 bool IsAlias;
875 if (Lex.getKind() == lltok::kw_alias)
876 IsAlias = true;
877 else if (Lex.getKind() == lltok::kw_ifunc)
878 IsAlias = false;
879 else
880 llvm_unreachable("Not an alias or ifunc!")::llvm::llvm_unreachable_internal("Not an alias or ifunc!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 880)
;
881 Lex.Lex();
882
883 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
884
885 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
886 return Error(NameLoc, "invalid linkage type for alias");
887
888 if (!isValidVisibilityForLinkage(Visibility, L))
889 return Error(NameLoc,
890 "symbol with local linkage must have default visibility");
891
892 Type *Ty;
893 LocTy ExplicitTypeLoc = Lex.getLoc();
894 if (ParseType(Ty) ||
895 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
896 return true;
897
898 Constant *Aliasee;
899 LocTy AliaseeLoc = Lex.getLoc();
900 if (Lex.getKind() != lltok::kw_bitcast &&
901 Lex.getKind() != lltok::kw_getelementptr &&
902 Lex.getKind() != lltok::kw_addrspacecast &&
903 Lex.getKind() != lltok::kw_inttoptr) {
904 if (ParseGlobalTypeAndValue(Aliasee))
905 return true;
906 } else {
907 // The bitcast dest type is not present, it is implied by the dest type.
908 ValID ID;
909 if (ParseValID(ID))
910 return true;
911 if (ID.Kind != ValID::t_Constant)
912 return Error(AliaseeLoc, "invalid aliasee");
913 Aliasee = ID.ConstantVal;
914 }
915
916 Type *AliaseeType = Aliasee->getType();
917 auto *PTy = dyn_cast<PointerType>(AliaseeType);
918 if (!PTy)
919 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
920 unsigned AddrSpace = PTy->getAddressSpace();
921
922 if (IsAlias && Ty != PTy->getElementType())
923 return Error(
924 ExplicitTypeLoc,
925 "explicit pointee type doesn't match operand's pointee type");
926
927 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
928 return Error(
929 ExplicitTypeLoc,
930 "explicit pointee type should be a function type");
931
932 GlobalValue *GVal = nullptr;
933
934 // See if the alias was forward referenced, if so, prepare to replace the
935 // forward reference.
936 if (!Name.empty()) {
937 GVal = M->getNamedValue(Name);
938 if (GVal) {
939 if (!ForwardRefVals.erase(Name))
940 return Error(NameLoc, "redefinition of global '@" + Name + "'");
941 }
942 } else {
943 auto I = ForwardRefValIDs.find(NumberedVals.size());
944 if (I != ForwardRefValIDs.end()) {
945 GVal = I->second.first;
946 ForwardRefValIDs.erase(I);
947 }
948 }
949
950 // Okay, create the alias but do not insert it into the module yet.
951 std::unique_ptr<GlobalIndirectSymbol> GA;
952 if (IsAlias)
953 GA.reset(GlobalAlias::create(Ty, AddrSpace,
954 (GlobalValue::LinkageTypes)Linkage, Name,
955 Aliasee, /*Parent*/ nullptr));
956 else
957 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
958 (GlobalValue::LinkageTypes)Linkage, Name,
959 Aliasee, /*Parent*/ nullptr));
960 GA->setThreadLocalMode(TLM);
961 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
962 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
963 GA->setUnnamedAddr(UnnamedAddr);
964 maybeSetDSOLocal(DSOLocal, *GA);
965
966 // At this point we've parsed everything except for the IndirectSymbolAttrs.
967 // Now parse them if there are any.
968 while (Lex.getKind() == lltok::comma) {
969 Lex.Lex();
970
971 if (Lex.getKind() == lltok::kw_partition) {
972 Lex.Lex();
973 GA->setPartition(Lex.getStrVal());
974 if (ParseToken(lltok::StringConstant, "expected partition string"))
975 return true;
976 } else {
977 return TokError("unknown alias or ifunc property!");
978 }
979 }
980
981 if (Name.empty())
982 NumberedVals.push_back(GA.get());
983
984 if (GVal) {
985 // Verify that types agree.
986 if (GVal->getType() != GA->getType())
987 return Error(
988 ExplicitTypeLoc,
989 "forward reference and definition of alias have different types");
990
991 // If they agree, just RAUW the old value with the alias and remove the
992 // forward ref info.
993 GVal->replaceAllUsesWith(GA.get());
994 GVal->eraseFromParent();
995 }
996
997 // Insert into the module, we know its name won't collide now.
998 if (IsAlias)
999 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1000 else
1001 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1002 assert(GA->getName() == Name && "Should not be a name conflict!")((GA->getName() == Name && "Should not be a name conflict!"
) ? static_cast<void> (0) : __assert_fail ("GA->getName() == Name && \"Should not be a name conflict!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 1002, __PRETTY_FUNCTION__))
;
1003
1004 // The module owns this now
1005 GA.release();
1006
1007 return false;
1008}
1009
1010/// ParseGlobal
1011/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1012/// OptionalVisibility OptionalDLLStorageClass
1013/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1014/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1015/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1016/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1017/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1018/// Const OptionalAttrs
1019///
1020/// Everything up to and including OptionalUnnamedAddr has been parsed
1021/// already.
1022///
1023bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1024 unsigned Linkage, bool HasLinkage,
1025 unsigned Visibility, unsigned DLLStorageClass,
1026 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1027 GlobalVariable::UnnamedAddr UnnamedAddr) {
1028 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1029 return Error(NameLoc,
1030 "symbol with local linkage must have default visibility");
1031
1032 unsigned AddrSpace;
1033 bool IsConstant, IsExternallyInitialized;
1034 LocTy IsExternallyInitializedLoc;
1035 LocTy TyLoc;
1036
1037 Type *Ty = nullptr;
1038 if (ParseOptionalAddrSpace(AddrSpace) ||
1039 ParseOptionalToken(lltok::kw_externally_initialized,
1040 IsExternallyInitialized,
1041 &IsExternallyInitializedLoc) ||
1042 ParseGlobalType(IsConstant) ||
1043 ParseType(Ty, TyLoc))
1044 return true;
1045
1046 // If the linkage is specified and is external, then no initializer is
1047 // present.
1048 Constant *Init = nullptr;
1049 if (!HasLinkage ||
1050 !GlobalValue::isValidDeclarationLinkage(
1051 (GlobalValue::LinkageTypes)Linkage)) {
1052 if (ParseGlobalValue(Ty, Init))
1053 return true;
1054 }
1055
1056 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1057 return Error(TyLoc, "invalid type for global variable");
1058
1059 GlobalValue *GVal = nullptr;
1060
1061 // See if the global was forward referenced, if so, use the global.
1062 if (!Name.empty()) {
1063 GVal = M->getNamedValue(Name);
1064 if (GVal) {
1065 if (!ForwardRefVals.erase(Name))
1066 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1067 }
1068 } else {
1069 auto I = ForwardRefValIDs.find(NumberedVals.size());
1070 if (I != ForwardRefValIDs.end()) {
1071 GVal = I->second.first;
1072 ForwardRefValIDs.erase(I);
1073 }
1074 }
1075
1076 GlobalVariable *GV;
1077 if (!GVal) {
1078 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1079 Name, nullptr, GlobalVariable::NotThreadLocal,
1080 AddrSpace);
1081 } else {
1082 if (GVal->getValueType() != Ty)
1083 return Error(TyLoc,
1084 "forward reference and definition of global have different types");
1085
1086 GV = cast<GlobalVariable>(GVal);
1087
1088 // Move the forward-reference to the correct spot in the module.
1089 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1090 }
1091
1092 if (Name.empty())
1093 NumberedVals.push_back(GV);
1094
1095 // Set the parsed properties on the global.
1096 if (Init)
1097 GV->setInitializer(Init);
1098 GV->setConstant(IsConstant);
1099 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1100 maybeSetDSOLocal(DSOLocal, *GV);
1101 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1102 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1103 GV->setExternallyInitialized(IsExternallyInitialized);
1104 GV->setThreadLocalMode(TLM);
1105 GV->setUnnamedAddr(UnnamedAddr);
1106
1107 // Parse attributes on the global.
1108 while (Lex.getKind() == lltok::comma) {
1109 Lex.Lex();
1110
1111 if (Lex.getKind() == lltok::kw_section) {
1112 Lex.Lex();
1113 GV->setSection(Lex.getStrVal());
1114 if (ParseToken(lltok::StringConstant, "expected global section string"))
1115 return true;
1116 } else if (Lex.getKind() == lltok::kw_partition) {
1117 Lex.Lex();
1118 GV->setPartition(Lex.getStrVal());
1119 if (ParseToken(lltok::StringConstant, "expected partition string"))
1120 return true;
1121 } else if (Lex.getKind() == lltok::kw_align) {
1122 unsigned Alignment;
1123 if (ParseOptionalAlignment(Alignment)) return true;
1124 GV->setAlignment(Alignment);
1125 } else if (Lex.getKind() == lltok::MetadataVar) {
1126 if (ParseGlobalObjectMetadataAttachment(*GV))
1127 return true;
1128 } else {
1129 Comdat *C;
1130 if (parseOptionalComdat(Name, C))
1131 return true;
1132 if (C)
1133 GV->setComdat(C);
1134 else
1135 return TokError("unknown global variable property!");
1136 }
1137 }
1138
1139 AttrBuilder Attrs;
1140 LocTy BuiltinLoc;
1141 std::vector<unsigned> FwdRefAttrGrps;
1142 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1143 return true;
1144 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1145 GV->setAttributes(AttributeSet::get(Context, Attrs));
1146 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1147 }
1148
1149 return false;
1150}
1151
1152/// ParseUnnamedAttrGrp
1153/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1154bool LLParser::ParseUnnamedAttrGrp() {
1155 assert(Lex.getKind() == lltok::kw_attributes)((Lex.getKind() == lltok::kw_attributes) ? static_cast<void
> (0) : __assert_fail ("Lex.getKind() == lltok::kw_attributes"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 1155, __PRETTY_FUNCTION__))
;
9
'?' condition is true
1156 LocTy AttrGrpLoc = Lex.getLoc();
1157 Lex.Lex();
1158
1159 if (Lex.getKind() != lltok::AttrGrpID)
10
Assuming the condition is false
11
Taking false branch
1160 return TokError("expected attribute group id");
1161
1162 unsigned VarID = Lex.getUIntVal();
1163 std::vector<unsigned> unused;
1164 LocTy BuiltinLoc;
1165 Lex.Lex();
1166
1167 if (ParseToken(lltok::equal, "expected '=' here") ||
1168 ParseToken(lltok::lbrace, "expected '{' here") ||
1169 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
12
Calling 'LLParser::ParseFnAttributeValuePairs'
1170 BuiltinLoc) ||
1171 ParseToken(lltok::rbrace, "expected end of attribute group"))
1172 return true;
1173
1174 if (!NumberedAttrBuilders[VarID].hasAttributes())
1175 return Error(AttrGrpLoc, "attribute group has no attributes");
1176
1177 return false;
1178}
1179
1180/// ParseFnAttributeValuePairs
1181/// ::= <attr> | <attr> '=' <value>
1182bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1183 std::vector<unsigned> &FwdRefAttrGrps,
1184 bool inAttrGrp, LocTy &BuiltinLoc) {
1185 bool HaveError = false;
1186
1187 B.clear();
1188
1189 while (true) {
13
Loop condition is true. Entering loop body
1190 lltok::Kind Token = Lex.getKind();
1191 if (Token == lltok::kw_builtin)
14
Assuming 'Token' is not equal to kw_builtin
15
Taking false branch
1192 BuiltinLoc = Lex.getLoc();
1193 switch (Token) {
16
Control jumps to 'case kw_align:' at line 1225
1194 default:
1195 if (!inAttrGrp) return HaveError;
1196 return Error(Lex.getLoc(), "unterminated attribute group");
1197 case lltok::rbrace:
1198 // Finished.
1199 return false;
1200
1201 case lltok::AttrGrpID: {
1202 // Allow a function to reference an attribute group:
1203 //
1204 // define void @foo() #1 { ... }
1205 if (inAttrGrp)
1206 HaveError |=
1207 Error(Lex.getLoc(),
1208 "cannot have an attribute group reference in an attribute group");
1209
1210 unsigned AttrGrpNum = Lex.getUIntVal();
1211 if (inAttrGrp) break;
1212
1213 // Save the reference to the attribute group. We'll fill it in later.
1214 FwdRefAttrGrps.push_back(AttrGrpNum);
1215 break;
1216 }
1217 // Target-dependent attributes:
1218 case lltok::StringConstant: {
1219 if (ParseStringAttribute(B))
1220 return true;
1221 continue;
1222 }
1223
1224 // Target-independent attributes:
1225 case lltok::kw_align: {
1226 // As a hack, we allow function alignment to be initially parsed as an
1227 // attribute on a function declaration/definition or added to an attribute
1228 // group and later moved to the alignment field.
1229 unsigned Alignment;
17
'Alignment' declared without an initial value
1230 if (inAttrGrp) {
18
Taking true branch
1231 Lex.Lex();
1232 if (ParseToken(lltok::equal, "expected '=' here") ||
24
Taking false branch
1233 ParseUInt32(Alignment))
19
Calling 'LLParser::ParseUInt32'
22
Returning from 'LLParser::ParseUInt32'
23
Assuming the condition is false
1234 return true;
1235 } else {
1236 if (ParseOptionalAlignment(Alignment))
1237 return true;
1238 }
1239 B.addAlignmentAttr(Alignment);
25
1st function call argument is an uninitialized value
1240 continue;
1241 }
1242 case lltok::kw_alignstack: {
1243 unsigned Alignment;
1244 if (inAttrGrp) {
1245 Lex.Lex();
1246 if (ParseToken(lltok::equal, "expected '=' here") ||
1247 ParseUInt32(Alignment))
1248 return true;
1249 } else {
1250 if (ParseOptionalStackAlignment(Alignment))
1251 return true;
1252 }
1253 B.addStackAlignmentAttr(Alignment);
1254 continue;
1255 }
1256 case lltok::kw_allocsize: {
1257 unsigned ElemSizeArg;
1258 Optional<unsigned> NumElemsArg;
1259 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1260 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1261 return true;
1262 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1263 continue;
1264 }
1265 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1266 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1267 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1268 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1269 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1270 case lltok::kw_inaccessiblememonly:
1271 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1272 case lltok::kw_inaccessiblemem_or_argmemonly:
1273 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1274 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1275 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1276 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1277 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1278 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1279 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1280 case lltok::kw_noimplicitfloat:
1281 B.addAttribute(Attribute::NoImplicitFloat); break;
1282 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1283 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1284 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1285 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1286 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1287 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1288 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1289 case lltok::kw_optforfuzzing:
1290 B.addAttribute(Attribute::OptForFuzzing); break;
1291 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1292 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1293 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1294 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1295 case lltok::kw_returns_twice:
1296 B.addAttribute(Attribute::ReturnsTwice); break;
1297 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1298 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1299 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1300 case lltok::kw_sspstrong:
1301 B.addAttribute(Attribute::StackProtectStrong); break;
1302 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1303 case lltok::kw_shadowcallstack:
1304 B.addAttribute(Attribute::ShadowCallStack); break;
1305 case lltok::kw_sanitize_address:
1306 B.addAttribute(Attribute::SanitizeAddress); break;
1307 case lltok::kw_sanitize_hwaddress:
1308 B.addAttribute(Attribute::SanitizeHWAddress); break;
1309 case lltok::kw_sanitize_thread:
1310 B.addAttribute(Attribute::SanitizeThread); break;
1311 case lltok::kw_sanitize_memory:
1312 B.addAttribute(Attribute::SanitizeMemory); break;
1313 case lltok::kw_speculative_load_hardening:
1314 B.addAttribute(Attribute::SpeculativeLoadHardening);
1315 break;
1316 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1317 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1318 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1319
1320 // Error handling.
1321 case lltok::kw_inreg:
1322 case lltok::kw_signext:
1323 case lltok::kw_zeroext:
1324 HaveError |=
1325 Error(Lex.getLoc(),
1326 "invalid use of attribute on a function");
1327 break;
1328 case lltok::kw_byval:
1329 case lltok::kw_dereferenceable:
1330 case lltok::kw_dereferenceable_or_null:
1331 case lltok::kw_inalloca:
1332 case lltok::kw_nest:
1333 case lltok::kw_noalias:
1334 case lltok::kw_nocapture:
1335 case lltok::kw_nonnull:
1336 case lltok::kw_returned:
1337 case lltok::kw_sret:
1338 case lltok::kw_swifterror:
1339 case lltok::kw_swiftself:
1340 case lltok::kw_immarg:
1341 HaveError |=
1342 Error(Lex.getLoc(),
1343 "invalid use of parameter-only attribute on a function");
1344 break;
1345 }
1346
1347 Lex.Lex();
1348 }
1349}
1350
1351//===----------------------------------------------------------------------===//
1352// GlobalValue Reference/Resolution Routines.
1353//===----------------------------------------------------------------------===//
1354
1355static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1356 const std::string &Name) {
1357 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1358 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1359 PTy->getAddressSpace(), Name, M);
1360 else
1361 return new GlobalVariable(*M, PTy->getElementType(), false,
1362 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1363 nullptr, GlobalVariable::NotThreadLocal,
1364 PTy->getAddressSpace());
1365}
1366
1367Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1368 Value *Val, bool IsCall) {
1369 if (Val->getType() == Ty)
1370 return Val;
1371 // For calls we also accept variables in the program address space.
1372 Type *SuggestedTy = Ty;
1373 if (IsCall && isa<PointerType>(Ty)) {
1374 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1375 M->getDataLayout().getProgramAddressSpace());
1376 SuggestedTy = TyInProgAS;
1377 if (Val->getType() == TyInProgAS)
1378 return Val;
1379 }
1380 if (Ty->isLabelTy())
1381 Error(Loc, "'" + Name + "' is not a basic block");
1382 else
1383 Error(Loc, "'" + Name + "' defined with type '" +
1384 getTypeString(Val->getType()) + "' but expected '" +
1385 getTypeString(SuggestedTy) + "'");
1386 return nullptr;
1387}
1388
1389/// GetGlobalVal - Get a value with the specified name or ID, creating a
1390/// forward reference record if needed. This can return null if the value
1391/// exists but does not have the right type.
1392GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1393 LocTy Loc, bool IsCall) {
1394 PointerType *PTy = dyn_cast<PointerType>(Ty);
1395 if (!PTy) {
1396 Error(Loc, "global variable reference must have pointer type");
1397 return nullptr;
1398 }
1399
1400 // Look this name up in the normal function symbol table.
1401 GlobalValue *Val =
1402 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1403
1404 // If this is a forward reference for the value, see if we already created a
1405 // forward ref record.
1406 if (!Val) {
1407 auto I = ForwardRefVals.find(Name);
1408 if (I != ForwardRefVals.end())
1409 Val = I->second.first;
1410 }
1411
1412 // If we have the value in the symbol table or fwd-ref table, return it.
1413 if (Val)
1414 return cast_or_null<GlobalValue>(
1415 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1416
1417 // Otherwise, create a new forward reference for this value and remember it.
1418 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1419 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1420 return FwdVal;
1421}
1422
1423GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1424 bool IsCall) {
1425 PointerType *PTy = dyn_cast<PointerType>(Ty);
1426 if (!PTy) {
1427 Error(Loc, "global variable reference must have pointer type");
1428 return nullptr;
1429 }
1430
1431 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1432
1433 // If this is a forward reference for the value, see if we already created a
1434 // forward ref record.
1435 if (!Val) {
1436 auto I = ForwardRefValIDs.find(ID);
1437 if (I != ForwardRefValIDs.end())
1438 Val = I->second.first;
1439 }
1440
1441 // If we have the value in the symbol table or fwd-ref table, return it.
1442 if (Val)
1443 return cast_or_null<GlobalValue>(
1444 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1445
1446 // Otherwise, create a new forward reference for this value and remember it.
1447 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1448 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1449 return FwdVal;
1450}
1451
1452//===----------------------------------------------------------------------===//
1453// Comdat Reference/Resolution Routines.
1454//===----------------------------------------------------------------------===//
1455
1456Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1457 // Look this name up in the comdat symbol table.
1458 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1459 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1460 if (I != ComdatSymTab.end())
1461 return &I->second;
1462
1463 // Otherwise, create a new forward reference for this value and remember it.
1464 Comdat *C = M->getOrInsertComdat(Name);
1465 ForwardRefComdats[Name] = Loc;
1466 return C;
1467}
1468
1469//===----------------------------------------------------------------------===//
1470// Helper Routines.
1471//===----------------------------------------------------------------------===//
1472
1473/// ParseToken - If the current token has the specified kind, eat it and return
1474/// success. Otherwise, emit the specified error and return failure.
1475bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1476 if (Lex.getKind() != T)
1477 return TokError(ErrMsg);
1478 Lex.Lex();
1479 return false;
1480}
1481
1482/// ParseStringConstant
1483/// ::= StringConstant
1484bool LLParser::ParseStringConstant(std::string &Result) {
1485 if (Lex.getKind() != lltok::StringConstant)
1486 return TokError("expected string constant");
1487 Result = Lex.getStrVal();
1488 Lex.Lex();
1489 return false;
1490}
1491
1492/// ParseUInt32
1493/// ::= uint32
1494bool LLParser::ParseUInt32(uint32_t &Val) {
1495 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
20
Assuming the condition is true
1496 return TokError("expected integer");
21
Returning without writing to 'Val'
1497 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1498 if (Val64 != unsigned(Val64))
1499 return TokError("expected 32-bit integer (too large)");
1500 Val = Val64;
1501 Lex.Lex();
1502 return false;
1503}
1504
1505/// ParseUInt64
1506/// ::= uint64
1507bool LLParser::ParseUInt64(uint64_t &Val) {
1508 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1509 return TokError("expected integer");
1510 Val = Lex.getAPSIntVal().getLimitedValue();
1511 Lex.Lex();
1512 return false;
1513}
1514
1515/// ParseTLSModel
1516/// := 'localdynamic'
1517/// := 'initialexec'
1518/// := 'localexec'
1519bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1520 switch (Lex.getKind()) {
1521 default:
1522 return TokError("expected localdynamic, initialexec or localexec");
1523 case lltok::kw_localdynamic:
1524 TLM = GlobalVariable::LocalDynamicTLSModel;
1525 break;
1526 case lltok::kw_initialexec:
1527 TLM = GlobalVariable::InitialExecTLSModel;
1528 break;
1529 case lltok::kw_localexec:
1530 TLM = GlobalVariable::LocalExecTLSModel;
1531 break;
1532 }
1533
1534 Lex.Lex();
1535 return false;
1536}
1537
1538/// ParseOptionalThreadLocal
1539/// := /*empty*/
1540/// := 'thread_local'
1541/// := 'thread_local' '(' tlsmodel ')'
1542bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1543 TLM = GlobalVariable::NotThreadLocal;
1544 if (!EatIfPresent(lltok::kw_thread_local))
1545 return false;
1546
1547 TLM = GlobalVariable::GeneralDynamicTLSModel;
1548 if (Lex.getKind() == lltok::lparen) {
1549 Lex.Lex();
1550 return ParseTLSModel(TLM) ||
1551 ParseToken(lltok::rparen, "expected ')' after thread local model");
1552 }
1553 return false;
1554}
1555
1556/// ParseOptionalAddrSpace
1557/// := /*empty*/
1558/// := 'addrspace' '(' uint32 ')'
1559bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1560 AddrSpace = DefaultAS;
1561 if (!EatIfPresent(lltok::kw_addrspace))
1562 return false;
1563 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1564 ParseUInt32(AddrSpace) ||
1565 ParseToken(lltok::rparen, "expected ')' in address space");
1566}
1567
1568/// ParseStringAttribute
1569/// := StringConstant
1570/// := StringConstant '=' StringConstant
1571bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1572 std::string Attr = Lex.getStrVal();
1573 Lex.Lex();
1574 std::string Val;
1575 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1576 return true;
1577 B.addAttribute(Attr, Val);
1578 return false;
1579}
1580
1581/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1582bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1583 bool HaveError = false;
1584
1585 B.clear();
1586
1587 while (true) {
1588 lltok::Kind Token = Lex.getKind();
1589 switch (Token) {
1590 default: // End of attributes.
1591 return HaveError;
1592 case lltok::StringConstant: {
1593 if (ParseStringAttribute(B))
1594 return true;
1595 continue;
1596 }
1597 case lltok::kw_align: {
1598 unsigned Alignment;
1599 if (ParseOptionalAlignment(Alignment))
1600 return true;
1601 B.addAlignmentAttr(Alignment);
1602 continue;
1603 }
1604 case lltok::kw_byval: {
1605 Type *Ty;
1606 if (ParseByValWithOptionalType(Ty))
1607 return true;
1608 B.addByValAttr(Ty);
1609 continue;
1610 }
1611 case lltok::kw_dereferenceable: {
1612 uint64_t Bytes;
1613 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1614 return true;
1615 B.addDereferenceableAttr(Bytes);
1616 continue;
1617 }
1618 case lltok::kw_dereferenceable_or_null: {
1619 uint64_t Bytes;
1620 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1621 return true;
1622 B.addDereferenceableOrNullAttr(Bytes);
1623 continue;
1624 }
1625 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1626 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1627 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1628 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1629 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1630 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1631 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1632 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1633 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1634 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1635 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1636 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1637 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1638 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1639 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1640 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1641
1642 case lltok::kw_alignstack:
1643 case lltok::kw_alwaysinline:
1644 case lltok::kw_argmemonly:
1645 case lltok::kw_builtin:
1646 case lltok::kw_inlinehint:
1647 case lltok::kw_jumptable:
1648 case lltok::kw_minsize:
1649 case lltok::kw_naked:
1650 case lltok::kw_nobuiltin:
1651 case lltok::kw_noduplicate:
1652 case lltok::kw_noimplicitfloat:
1653 case lltok::kw_noinline:
1654 case lltok::kw_nonlazybind:
1655 case lltok::kw_noredzone:
1656 case lltok::kw_noreturn:
1657 case lltok::kw_nocf_check:
1658 case lltok::kw_nounwind:
1659 case lltok::kw_optforfuzzing:
1660 case lltok::kw_optnone:
1661 case lltok::kw_optsize:
1662 case lltok::kw_returns_twice:
1663 case lltok::kw_sanitize_address:
1664 case lltok::kw_sanitize_hwaddress:
1665 case lltok::kw_sanitize_memory:
1666 case lltok::kw_sanitize_thread:
1667 case lltok::kw_speculative_load_hardening:
1668 case lltok::kw_ssp:
1669 case lltok::kw_sspreq:
1670 case lltok::kw_sspstrong:
1671 case lltok::kw_safestack:
1672 case lltok::kw_shadowcallstack:
1673 case lltok::kw_strictfp:
1674 case lltok::kw_uwtable:
1675 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1676 break;
1677 }
1678
1679 Lex.Lex();
1680 }
1681}
1682
1683/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1684bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1685 bool HaveError = false;
1686
1687 B.clear();
1688
1689 while (true) {
1690 lltok::Kind Token = Lex.getKind();
1691 switch (Token) {
1692 default: // End of attributes.
1693 return HaveError;
1694 case lltok::StringConstant: {
1695 if (ParseStringAttribute(B))
1696 return true;
1697 continue;
1698 }
1699 case lltok::kw_dereferenceable: {
1700 uint64_t Bytes;
1701 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1702 return true;
1703 B.addDereferenceableAttr(Bytes);
1704 continue;
1705 }
1706 case lltok::kw_dereferenceable_or_null: {
1707 uint64_t Bytes;
1708 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1709 return true;
1710 B.addDereferenceableOrNullAttr(Bytes);
1711 continue;
1712 }
1713 case lltok::kw_align: {
1714 unsigned Alignment;
1715 if (ParseOptionalAlignment(Alignment))
1716 return true;
1717 B.addAlignmentAttr(Alignment);
1718 continue;
1719 }
1720 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1721 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1722 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1723 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1724 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1725
1726 // Error handling.
1727 case lltok::kw_byval:
1728 case lltok::kw_inalloca:
1729 case lltok::kw_nest:
1730 case lltok::kw_nocapture:
1731 case lltok::kw_returned:
1732 case lltok::kw_sret:
1733 case lltok::kw_swifterror:
1734 case lltok::kw_swiftself:
1735 case lltok::kw_immarg:
1736 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1737 break;
1738
1739 case lltok::kw_alignstack:
1740 case lltok::kw_alwaysinline:
1741 case lltok::kw_argmemonly:
1742 case lltok::kw_builtin:
1743 case lltok::kw_cold:
1744 case lltok::kw_inlinehint:
1745 case lltok::kw_jumptable:
1746 case lltok::kw_minsize:
1747 case lltok::kw_naked:
1748 case lltok::kw_nobuiltin:
1749 case lltok::kw_noduplicate:
1750 case lltok::kw_noimplicitfloat:
1751 case lltok::kw_noinline:
1752 case lltok::kw_nonlazybind:
1753 case lltok::kw_noredzone:
1754 case lltok::kw_noreturn:
1755 case lltok::kw_nocf_check:
1756 case lltok::kw_nounwind:
1757 case lltok::kw_optforfuzzing:
1758 case lltok::kw_optnone:
1759 case lltok::kw_optsize:
1760 case lltok::kw_returns_twice:
1761 case lltok::kw_sanitize_address:
1762 case lltok::kw_sanitize_hwaddress:
1763 case lltok::kw_sanitize_memory:
1764 case lltok::kw_sanitize_thread:
1765 case lltok::kw_speculative_load_hardening:
1766 case lltok::kw_ssp:
1767 case lltok::kw_sspreq:
1768 case lltok::kw_sspstrong:
1769 case lltok::kw_safestack:
1770 case lltok::kw_shadowcallstack:
1771 case lltok::kw_strictfp:
1772 case lltok::kw_uwtable:
1773 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1774 break;
1775
1776 case lltok::kw_readnone:
1777 case lltok::kw_readonly:
1778 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1779 }
1780
1781 Lex.Lex();
1782 }
1783}
1784
1785static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1786 HasLinkage = true;
1787 switch (Kind) {
1788 default:
1789 HasLinkage = false;
1790 return GlobalValue::ExternalLinkage;
1791 case lltok::kw_private:
1792 return GlobalValue::PrivateLinkage;
1793 case lltok::kw_internal:
1794 return GlobalValue::InternalLinkage;
1795 case lltok::kw_weak:
1796 return GlobalValue::WeakAnyLinkage;
1797 case lltok::kw_weak_odr:
1798 return GlobalValue::WeakODRLinkage;
1799 case lltok::kw_linkonce:
1800 return GlobalValue::LinkOnceAnyLinkage;
1801 case lltok::kw_linkonce_odr:
1802 return GlobalValue::LinkOnceODRLinkage;
1803 case lltok::kw_available_externally:
1804 return GlobalValue::AvailableExternallyLinkage;
1805 case lltok::kw_appending:
1806 return GlobalValue::AppendingLinkage;
1807 case lltok::kw_common:
1808 return GlobalValue::CommonLinkage;
1809 case lltok::kw_extern_weak:
1810 return GlobalValue::ExternalWeakLinkage;
1811 case lltok::kw_external:
1812 return GlobalValue::ExternalLinkage;
1813 }
1814}
1815
1816/// ParseOptionalLinkage
1817/// ::= /*empty*/
1818/// ::= 'private'
1819/// ::= 'internal'
1820/// ::= 'weak'
1821/// ::= 'weak_odr'
1822/// ::= 'linkonce'
1823/// ::= 'linkonce_odr'
1824/// ::= 'available_externally'
1825/// ::= 'appending'
1826/// ::= 'common'
1827/// ::= 'extern_weak'
1828/// ::= 'external'
1829bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1830 unsigned &Visibility,
1831 unsigned &DLLStorageClass,
1832 bool &DSOLocal) {
1833 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1834 if (HasLinkage)
1835 Lex.Lex();
1836 ParseOptionalDSOLocal(DSOLocal);
1837 ParseOptionalVisibility(Visibility);
1838 ParseOptionalDLLStorageClass(DLLStorageClass);
1839
1840 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1841 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1842 }
1843
1844 return false;
1845}
1846
1847void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1848 switch (Lex.getKind()) {
1849 default:
1850 DSOLocal = false;
1851 break;
1852 case lltok::kw_dso_local:
1853 DSOLocal = true;
1854 Lex.Lex();
1855 break;
1856 case lltok::kw_dso_preemptable:
1857 DSOLocal = false;
1858 Lex.Lex();
1859 break;
1860 }
1861}
1862
1863/// ParseOptionalVisibility
1864/// ::= /*empty*/
1865/// ::= 'default'
1866/// ::= 'hidden'
1867/// ::= 'protected'
1868///
1869void LLParser::ParseOptionalVisibility(unsigned &Res) {
1870 switch (Lex.getKind()) {
1871 default:
1872 Res = GlobalValue::DefaultVisibility;
1873 return;
1874 case lltok::kw_default:
1875 Res = GlobalValue::DefaultVisibility;
1876 break;
1877 case lltok::kw_hidden:
1878 Res = GlobalValue::HiddenVisibility;
1879 break;
1880 case lltok::kw_protected:
1881 Res = GlobalValue::ProtectedVisibility;
1882 break;
1883 }
1884 Lex.Lex();
1885}
1886
1887/// ParseOptionalDLLStorageClass
1888/// ::= /*empty*/
1889/// ::= 'dllimport'
1890/// ::= 'dllexport'
1891///
1892void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1893 switch (Lex.getKind()) {
1894 default:
1895 Res = GlobalValue::DefaultStorageClass;
1896 return;
1897 case lltok::kw_dllimport:
1898 Res = GlobalValue::DLLImportStorageClass;
1899 break;
1900 case lltok::kw_dllexport:
1901 Res = GlobalValue::DLLExportStorageClass;
1902 break;
1903 }
1904 Lex.Lex();
1905}
1906
1907/// ParseOptionalCallingConv
1908/// ::= /*empty*/
1909/// ::= 'ccc'
1910/// ::= 'fastcc'
1911/// ::= 'intel_ocl_bicc'
1912/// ::= 'coldcc'
1913/// ::= 'x86_stdcallcc'
1914/// ::= 'x86_fastcallcc'
1915/// ::= 'x86_thiscallcc'
1916/// ::= 'x86_vectorcallcc'
1917/// ::= 'arm_apcscc'
1918/// ::= 'arm_aapcscc'
1919/// ::= 'arm_aapcs_vfpcc'
1920/// ::= 'aarch64_vector_pcs'
1921/// ::= 'msp430_intrcc'
1922/// ::= 'avr_intrcc'
1923/// ::= 'avr_signalcc'
1924/// ::= 'ptx_kernel'
1925/// ::= 'ptx_device'
1926/// ::= 'spir_func'
1927/// ::= 'spir_kernel'
1928/// ::= 'x86_64_sysvcc'
1929/// ::= 'win64cc'
1930/// ::= 'webkit_jscc'
1931/// ::= 'anyregcc'
1932/// ::= 'preserve_mostcc'
1933/// ::= 'preserve_allcc'
1934/// ::= 'ghccc'
1935/// ::= 'swiftcc'
1936/// ::= 'x86_intrcc'
1937/// ::= 'hhvmcc'
1938/// ::= 'hhvm_ccc'
1939/// ::= 'cxx_fast_tlscc'
1940/// ::= 'amdgpu_vs'
1941/// ::= 'amdgpu_ls'
1942/// ::= 'amdgpu_hs'
1943/// ::= 'amdgpu_es'
1944/// ::= 'amdgpu_gs'
1945/// ::= 'amdgpu_ps'
1946/// ::= 'amdgpu_cs'
1947/// ::= 'amdgpu_kernel'
1948/// ::= 'cc' UINT
1949///
1950bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1951 switch (Lex.getKind()) {
1952 default: CC = CallingConv::C; return false;
1953 case lltok::kw_ccc: CC = CallingConv::C; break;
1954 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1955 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1956 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1957 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1958 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1959 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1960 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1961 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1962 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1963 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1964 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1965 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1966 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1967 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1968 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1969 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1970 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1971 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1972 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1973 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1974 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1975 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1976 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1977 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1978 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1979 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1980 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1981 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1982 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1983 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1984 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1985 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1986 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1987 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1988 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1989 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1990 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1991 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1992 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1993 case lltok::kw_cc: {
1994 Lex.Lex();
1995 return ParseUInt32(CC);
1996 }
1997 }
1998
1999 Lex.Lex();
2000 return false;
2001}
2002
2003/// ParseMetadataAttachment
2004/// ::= !dbg !42
2005bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2006 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment")((Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata attachment\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2006, __PRETTY_FUNCTION__))
;
2007
2008 std::string Name = Lex.getStrVal();
2009 Kind = M->getMDKindID(Name);
2010 Lex.Lex();
2011
2012 return ParseMDNode(MD);
2013}
2014
2015/// ParseInstructionMetadata
2016/// ::= !dbg !42 (',' !dbg !57)*
2017bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
2018 do {
2019 if (Lex.getKind() != lltok::MetadataVar)
2020 return TokError("expected metadata after comma");
2021
2022 unsigned MDK;
2023 MDNode *N;
2024 if (ParseMetadataAttachment(MDK, N))
2025 return true;
2026
2027 Inst.setMetadata(MDK, N);
2028 if (MDK == LLVMContext::MD_tbaa)
2029 InstsWithTBAATag.push_back(&Inst);
2030
2031 // If this is the end of the list, we're done.
2032 } while (EatIfPresent(lltok::comma));
2033 return false;
2034}
2035
2036/// ParseGlobalObjectMetadataAttachment
2037/// ::= !dbg !57
2038bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2039 unsigned MDK;
2040 MDNode *N;
2041 if (ParseMetadataAttachment(MDK, N))
2042 return true;
2043
2044 GO.addMetadata(MDK, *N);
2045 return false;
2046}
2047
2048/// ParseOptionalFunctionMetadata
2049/// ::= (!dbg !57)*
2050bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2051 while (Lex.getKind() == lltok::MetadataVar)
2052 if (ParseGlobalObjectMetadataAttachment(F))
2053 return true;
2054 return false;
2055}
2056
2057/// ParseOptionalAlignment
2058/// ::= /* empty */
2059/// ::= 'align' 4
2060bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2061 Alignment = 0;
2062 if (!EatIfPresent(lltok::kw_align))
2063 return false;
2064 LocTy AlignLoc = Lex.getLoc();
2065 if (ParseUInt32(Alignment)) return true;
2066 if (!isPowerOf2_32(Alignment))
2067 return Error(AlignLoc, "alignment is not a power of two");
2068 if (Alignment > Value::MaximumAlignment)
2069 return Error(AlignLoc, "huge alignments are not supported yet");
2070 return false;
2071}
2072
2073/// ParseOptionalDerefAttrBytes
2074/// ::= /* empty */
2075/// ::= AttrKind '(' 4 ')'
2076///
2077/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2078bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2079 uint64_t &Bytes) {
2080 assert((AttrKind == lltok::kw_dereferenceable ||(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2082, __PRETTY_FUNCTION__))
2081 AttrKind == lltok::kw_dereferenceable_or_null) &&(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2082, __PRETTY_FUNCTION__))
2082 "contract!")(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2082, __PRETTY_FUNCTION__))
;
2083
2084 Bytes = 0;
2085 if (!EatIfPresent(AttrKind))
2086 return false;
2087 LocTy ParenLoc = Lex.getLoc();
2088 if (!EatIfPresent(lltok::lparen))
2089 return Error(ParenLoc, "expected '('");
2090 LocTy DerefLoc = Lex.getLoc();
2091 if (ParseUInt64(Bytes)) return true;
2092 ParenLoc = Lex.getLoc();
2093 if (!EatIfPresent(lltok::rparen))
2094 return Error(ParenLoc, "expected ')'");
2095 if (!Bytes)
2096 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2097 return false;
2098}
2099
2100/// ParseOptionalCommaAlign
2101/// ::=
2102/// ::= ',' align 4
2103///
2104/// This returns with AteExtraComma set to true if it ate an excess comma at the
2105/// end.
2106bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2107 bool &AteExtraComma) {
2108 AteExtraComma = false;
2109 while (EatIfPresent(lltok::comma)) {
2110 // Metadata at the end is an early exit.
2111 if (Lex.getKind() == lltok::MetadataVar) {
2112 AteExtraComma = true;
2113 return false;
2114 }
2115
2116 if (Lex.getKind() != lltok::kw_align)
2117 return Error(Lex.getLoc(), "expected metadata or 'align'");
2118
2119 if (ParseOptionalAlignment(Alignment)) return true;
2120 }
2121
2122 return false;
2123}
2124
2125/// ParseOptionalCommaAddrSpace
2126/// ::=
2127/// ::= ',' addrspace(1)
2128///
2129/// This returns with AteExtraComma set to true if it ate an excess comma at the
2130/// end.
2131bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2132 LocTy &Loc,
2133 bool &AteExtraComma) {
2134 AteExtraComma = false;
2135 while (EatIfPresent(lltok::comma)) {
2136 // Metadata at the end is an early exit.
2137 if (Lex.getKind() == lltok::MetadataVar) {
2138 AteExtraComma = true;
2139 return false;
2140 }
2141
2142 Loc = Lex.getLoc();
2143 if (Lex.getKind() != lltok::kw_addrspace)
2144 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2145
2146 if (ParseOptionalAddrSpace(AddrSpace))
2147 return true;
2148 }
2149
2150 return false;
2151}
2152
2153bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2154 Optional<unsigned> &HowManyArg) {
2155 Lex.Lex();
2156
2157 auto StartParen = Lex.getLoc();
2158 if (!EatIfPresent(lltok::lparen))
2159 return Error(StartParen, "expected '('");
2160
2161 if (ParseUInt32(BaseSizeArg))
2162 return true;
2163
2164 if (EatIfPresent(lltok::comma)) {
2165 auto HowManyAt = Lex.getLoc();
2166 unsigned HowMany;
2167 if (ParseUInt32(HowMany))
2168 return true;
2169 if (HowMany == BaseSizeArg)
2170 return Error(HowManyAt,
2171 "'allocsize' indices can't refer to the same parameter");
2172 HowManyArg = HowMany;
2173 } else
2174 HowManyArg = None;
2175
2176 auto EndParen = Lex.getLoc();
2177 if (!EatIfPresent(lltok::rparen))
2178 return Error(EndParen, "expected ')'");
2179 return false;
2180}
2181
2182/// ParseScopeAndOrdering
2183/// if isAtomic: ::= SyncScope? AtomicOrdering
2184/// else: ::=
2185///
2186/// This sets Scope and Ordering to the parsed values.
2187bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2188 AtomicOrdering &Ordering) {
2189 if (!isAtomic)
2190 return false;
2191
2192 return ParseScope(SSID) || ParseOrdering(Ordering);
2193}
2194
2195/// ParseScope
2196/// ::= syncscope("singlethread" | "<target scope>")?
2197///
2198/// This sets synchronization scope ID to the ID of the parsed value.
2199bool LLParser::ParseScope(SyncScope::ID &SSID) {
2200 SSID = SyncScope::System;
2201 if (EatIfPresent(lltok::kw_syncscope)) {
2202 auto StartParenAt = Lex.getLoc();
2203 if (!EatIfPresent(lltok::lparen))
2204 return Error(StartParenAt, "Expected '(' in syncscope");
2205
2206 std::string SSN;
2207 auto SSNAt = Lex.getLoc();
2208 if (ParseStringConstant(SSN))
2209 return Error(SSNAt, "Expected synchronization scope name");
2210
2211 auto EndParenAt = Lex.getLoc();
2212 if (!EatIfPresent(lltok::rparen))
2213 return Error(EndParenAt, "Expected ')' in syncscope");
2214
2215 SSID = Context.getOrInsertSyncScopeID(SSN);
2216 }
2217
2218 return false;
2219}
2220
2221/// ParseOrdering
2222/// ::= AtomicOrdering
2223///
2224/// This sets Ordering to the parsed value.
2225bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2226 switch (Lex.getKind()) {
2227 default: return TokError("Expected ordering on atomic instruction");
2228 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2229 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2230 // Not specified yet:
2231 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2232 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2233 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2234 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2235 case lltok::kw_seq_cst:
2236 Ordering = AtomicOrdering::SequentiallyConsistent;
2237 break;
2238 }
2239 Lex.Lex();
2240 return false;
2241}
2242
2243/// ParseOptionalStackAlignment
2244/// ::= /* empty */
2245/// ::= 'alignstack' '(' 4 ')'
2246bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2247 Alignment = 0;
2248 if (!EatIfPresent(lltok::kw_alignstack))
2249 return false;
2250 LocTy ParenLoc = Lex.getLoc();
2251 if (!EatIfPresent(lltok::lparen))
2252 return Error(ParenLoc, "expected '('");
2253 LocTy AlignLoc = Lex.getLoc();
2254 if (ParseUInt32(Alignment)) return true;
2255 ParenLoc = Lex.getLoc();
2256 if (!EatIfPresent(lltok::rparen))
2257 return Error(ParenLoc, "expected ')'");
2258 if (!isPowerOf2_32(Alignment))
2259 return Error(AlignLoc, "stack alignment is not a power of two");
2260 return false;
2261}
2262
2263/// ParseIndexList - This parses the index list for an insert/extractvalue
2264/// instruction. This sets AteExtraComma in the case where we eat an extra
2265/// comma at the end of the line and find that it is followed by metadata.
2266/// Clients that don't allow metadata can call the version of this function that
2267/// only takes one argument.
2268///
2269/// ParseIndexList
2270/// ::= (',' uint32)+
2271///
2272bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2273 bool &AteExtraComma) {
2274 AteExtraComma = false;
2275
2276 if (Lex.getKind() != lltok::comma)
2277 return TokError("expected ',' as start of index list");
2278
2279 while (EatIfPresent(lltok::comma)) {
2280 if (Lex.getKind() == lltok::MetadataVar) {
2281 if (Indices.empty()) return TokError("expected index");
2282 AteExtraComma = true;
2283 return false;
2284 }
2285 unsigned Idx = 0;
2286 if (ParseUInt32(Idx)) return true;
2287 Indices.push_back(Idx);
2288 }
2289
2290 return false;
2291}
2292
2293//===----------------------------------------------------------------------===//
2294// Type Parsing.
2295//===----------------------------------------------------------------------===//
2296
2297/// ParseType - Parse a type.
2298bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2299 SMLoc TypeLoc = Lex.getLoc();
2300 switch (Lex.getKind()) {
2301 default:
2302 return TokError(Msg);
2303 case lltok::Type:
2304 // Type ::= 'float' | 'void' (etc)
2305 Result = Lex.getTyVal();
2306 Lex.Lex();
2307 break;
2308 case lltok::lbrace:
2309 // Type ::= StructType
2310 if (ParseAnonStructType(Result, false))
2311 return true;
2312 break;
2313 case lltok::lsquare:
2314 // Type ::= '[' ... ']'
2315 Lex.Lex(); // eat the lsquare.
2316 if (ParseArrayVectorType(Result, false))
2317 return true;
2318 break;
2319 case lltok::less: // Either vector or packed struct.
2320 // Type ::= '<' ... '>'
2321 Lex.Lex();
2322 if (Lex.getKind() == lltok::lbrace) {
2323 if (ParseAnonStructType(Result, true) ||
2324 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2325 return true;
2326 } else if (ParseArrayVectorType(Result, true))
2327 return true;
2328 break;
2329 case lltok::LocalVar: {
2330 // Type ::= %foo
2331 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2332
2333 // If the type hasn't been defined yet, create a forward definition and
2334 // remember where that forward def'n was seen (in case it never is defined).
2335 if (!Entry.first) {
2336 Entry.first = StructType::create(Context, Lex.getStrVal());
2337 Entry.second = Lex.getLoc();
2338 }
2339 Result = Entry.first;
2340 Lex.Lex();
2341 break;
2342 }
2343
2344 case lltok::LocalVarID: {
2345 // Type ::= %4
2346 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2347
2348 // If the type hasn't been defined yet, create a forward definition and
2349 // remember where that forward def'n was seen (in case it never is defined).
2350 if (!Entry.first) {
2351 Entry.first = StructType::create(Context);
2352 Entry.second = Lex.getLoc();
2353 }
2354 Result = Entry.first;
2355 Lex.Lex();
2356 break;
2357 }
2358 }
2359
2360 // Parse the type suffixes.
2361 while (true) {
2362 switch (Lex.getKind()) {
2363 // End of type.
2364 default:
2365 if (!AllowVoid && Result->isVoidTy())
2366 return Error(TypeLoc, "void type only allowed for function results");
2367 return false;
2368
2369 // Type ::= Type '*'
2370 case lltok::star:
2371 if (Result->isLabelTy())
2372 return TokError("basic block pointers are invalid");
2373 if (Result->isVoidTy())
2374 return TokError("pointers to void are invalid - use i8* instead");
2375 if (!PointerType::isValidElementType(Result))
2376 return TokError("pointer to this type is invalid");
2377 Result = PointerType::getUnqual(Result);
2378 Lex.Lex();
2379 break;
2380
2381 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2382 case lltok::kw_addrspace: {
2383 if (Result->isLabelTy())
2384 return TokError("basic block pointers are invalid");
2385 if (Result->isVoidTy())
2386 return TokError("pointers to void are invalid; use i8* instead");
2387 if (!PointerType::isValidElementType(Result))
2388 return TokError("pointer to this type is invalid");
2389 unsigned AddrSpace;
2390 if (ParseOptionalAddrSpace(AddrSpace) ||
2391 ParseToken(lltok::star, "expected '*' in address space"))
2392 return true;
2393
2394 Result = PointerType::get(Result, AddrSpace);
2395 break;
2396 }
2397
2398 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2399 case lltok::lparen:
2400 if (ParseFunctionType(Result))
2401 return true;
2402 break;
2403 }
2404 }
2405}
2406
2407/// ParseParameterList
2408/// ::= '(' ')'
2409/// ::= '(' Arg (',' Arg)* ')'
2410/// Arg
2411/// ::= Type OptionalAttributes Value OptionalAttributes
2412bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2413 PerFunctionState &PFS, bool IsMustTailCall,
2414 bool InVarArgsFunc) {
2415 if (ParseToken(lltok::lparen, "expected '(' in call"))
2416 return true;
2417
2418 while (Lex.getKind() != lltok::rparen) {
2419 // If this isn't the first argument, we need a comma.
2420 if (!ArgList.empty() &&
2421 ParseToken(lltok::comma, "expected ',' in argument list"))
2422 return true;
2423
2424 // Parse an ellipsis if this is a musttail call in a variadic function.
2425 if (Lex.getKind() == lltok::dotdotdot) {
2426 const char *Msg = "unexpected ellipsis in argument list for ";
2427 if (!IsMustTailCall)
2428 return TokError(Twine(Msg) + "non-musttail call");
2429 if (!InVarArgsFunc)
2430 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2431 Lex.Lex(); // Lex the '...', it is purely for readability.
2432 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2433 }
2434
2435 // Parse the argument.
2436 LocTy ArgLoc;
2437 Type *ArgTy = nullptr;
2438 AttrBuilder ArgAttrs;
2439 Value *V;
2440 if (ParseType(ArgTy, ArgLoc))
2441 return true;
2442
2443 if (ArgTy->isMetadataTy()) {
2444 if (ParseMetadataAsValue(V, PFS))
2445 return true;
2446 } else {
2447 // Otherwise, handle normal operands.
2448 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2449 return true;
2450 }
2451 ArgList.push_back(ParamInfo(
2452 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2453 }
2454
2455 if (IsMustTailCall && InVarArgsFunc)
2456 return TokError("expected '...' at end of argument list for musttail call "
2457 "in varargs function");
2458
2459 Lex.Lex(); // Lex the ')'.
2460 return false;
2461}
2462
2463/// ParseByValWithOptionalType
2464/// ::= byval
2465/// ::= byval(<ty>)
2466bool LLParser::ParseByValWithOptionalType(Type *&Result) {
2467 Result = nullptr;
2468 if (!EatIfPresent(lltok::kw_byval))
2469 return true;
2470 if (!EatIfPresent(lltok::lparen))
2471 return false;
2472 if (ParseType(Result))
2473 return true;
2474 if (!EatIfPresent(lltok::rparen))
2475 return Error(Lex.getLoc(), "expected ')'");
2476 return false;
2477}
2478
2479/// ParseOptionalOperandBundles
2480/// ::= /*empty*/
2481/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2482///
2483/// OperandBundle
2484/// ::= bundle-tag '(' ')'
2485/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2486///
2487/// bundle-tag ::= String Constant
2488bool LLParser::ParseOptionalOperandBundles(
2489 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2490 LocTy BeginLoc = Lex.getLoc();
2491 if (!EatIfPresent(lltok::lsquare))
2492 return false;
2493
2494 while (Lex.getKind() != lltok::rsquare) {
2495 // If this isn't the first operand bundle, we need a comma.
2496 if (!BundleList.empty() &&
2497 ParseToken(lltok::comma, "expected ',' in input list"))
2498 return true;
2499
2500 std::string Tag;
2501 if (ParseStringConstant(Tag))
2502 return true;
2503
2504 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2505 return true;
2506
2507 std::vector<Value *> Inputs;
2508 while (Lex.getKind() != lltok::rparen) {
2509 // If this isn't the first input, we need a comma.
2510 if (!Inputs.empty() &&
2511 ParseToken(lltok::comma, "expected ',' in input list"))
2512 return true;
2513
2514 Type *Ty = nullptr;
2515 Value *Input = nullptr;
2516 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2517 return true;
2518 Inputs.push_back(Input);
2519 }
2520
2521 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2522
2523 Lex.Lex(); // Lex the ')'.
2524 }
2525
2526 if (BundleList.empty())
2527 return Error(BeginLoc, "operand bundle set must not be empty");
2528
2529 Lex.Lex(); // Lex the ']'.
2530 return false;
2531}
2532
2533/// ParseArgumentList - Parse the argument list for a function type or function
2534/// prototype.
2535/// ::= '(' ArgTypeListI ')'
2536/// ArgTypeListI
2537/// ::= /*empty*/
2538/// ::= '...'
2539/// ::= ArgTypeList ',' '...'
2540/// ::= ArgType (',' ArgType)*
2541///
2542bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2543 bool &isVarArg){
2544 isVarArg = false;
2545 assert(Lex.getKind() == lltok::lparen)((Lex.getKind() == lltok::lparen) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lparen", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2545, __PRETTY_FUNCTION__))
;
2546 Lex.Lex(); // eat the (.
2547
2548 if (Lex.getKind() == lltok::rparen) {
2549 // empty
2550 } else if (Lex.getKind() == lltok::dotdotdot) {
2551 isVarArg = true;
2552 Lex.Lex();
2553 } else {
2554 LocTy TypeLoc = Lex.getLoc();
2555 Type *ArgTy = nullptr;
2556 AttrBuilder Attrs;
2557 std::string Name;
2558
2559 if (ParseType(ArgTy) ||
2560 ParseOptionalParamAttrs(Attrs)) return true;
2561
2562 if (ArgTy->isVoidTy())
2563 return Error(TypeLoc, "argument can not have void type");
2564
2565 if (Lex.getKind() == lltok::LocalVar) {
2566 Name = Lex.getStrVal();
2567 Lex.Lex();
2568 }
2569
2570 if (!FunctionType::isValidArgumentType(ArgTy))
2571 return Error(TypeLoc, "invalid type for function argument");
2572
2573 ArgList.emplace_back(TypeLoc, ArgTy,
2574 AttributeSet::get(ArgTy->getContext(), Attrs),
2575 std::move(Name));
2576
2577 while (EatIfPresent(lltok::comma)) {
2578 // Handle ... at end of arg list.
2579 if (EatIfPresent(lltok::dotdotdot)) {
2580 isVarArg = true;
2581 break;
2582 }
2583
2584 // Otherwise must be an argument type.
2585 TypeLoc = Lex.getLoc();
2586 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2587
2588 if (ArgTy->isVoidTy())
2589 return Error(TypeLoc, "argument can not have void type");
2590
2591 if (Lex.getKind() == lltok::LocalVar) {
2592 Name = Lex.getStrVal();
2593 Lex.Lex();
2594 } else {
2595 Name = "";
2596 }
2597
2598 if (!ArgTy->isFirstClassType())
2599 return Error(TypeLoc, "invalid type for function argument");
2600
2601 ArgList.emplace_back(TypeLoc, ArgTy,
2602 AttributeSet::get(ArgTy->getContext(), Attrs),
2603 std::move(Name));
2604 }
2605 }
2606
2607 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2608}
2609
2610/// ParseFunctionType
2611/// ::= Type ArgumentList OptionalAttrs
2612bool LLParser::ParseFunctionType(Type *&Result) {
2613 assert(Lex.getKind() == lltok::lparen)((Lex.getKind() == lltok::lparen) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lparen", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2613, __PRETTY_FUNCTION__))
;
2614
2615 if (!FunctionType::isValidReturnType(Result))
2616 return TokError("invalid function return type");
2617
2618 SmallVector<ArgInfo, 8> ArgList;
2619 bool isVarArg;
2620 if (ParseArgumentList(ArgList, isVarArg))
2621 return true;
2622
2623 // Reject names on the arguments lists.
2624 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2625 if (!ArgList[i].Name.empty())
2626 return Error(ArgList[i].Loc, "argument name invalid in function type");
2627 if (ArgList[i].Attrs.hasAttributes())
2628 return Error(ArgList[i].Loc,
2629 "argument attributes invalid in function type");
2630 }
2631
2632 SmallVector<Type*, 16> ArgListTy;
2633 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2634 ArgListTy.push_back(ArgList[i].Ty);
2635
2636 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2637 return false;
2638}
2639
2640/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2641/// other structs.
2642bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2643 SmallVector<Type*, 8> Elts;
2644 if (ParseStructBody(Elts)) return true;
2645
2646 Result = StructType::get(Context, Elts, Packed);
2647 return false;
2648}
2649
2650/// ParseStructDefinition - Parse a struct in a 'type' definition.
2651bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2652 std::pair<Type*, LocTy> &Entry,
2653 Type *&ResultTy) {
2654 // If the type was already defined, diagnose the redefinition.
2655 if (Entry.first && !Entry.second.isValid())
2656 return Error(TypeLoc, "redefinition of type");
2657
2658 // If we have opaque, just return without filling in the definition for the
2659 // struct. This counts as a definition as far as the .ll file goes.
2660 if (EatIfPresent(lltok::kw_opaque)) {
2661 // This type is being defined, so clear the location to indicate this.
2662 Entry.second = SMLoc();
2663
2664 // If this type number has never been uttered, create it.
2665 if (!Entry.first)
2666 Entry.first = StructType::create(Context, Name);
2667 ResultTy = Entry.first;
2668 return false;
2669 }
2670
2671 // If the type starts with '<', then it is either a packed struct or a vector.
2672 bool isPacked = EatIfPresent(lltok::less);
2673
2674 // If we don't have a struct, then we have a random type alias, which we
2675 // accept for compatibility with old files. These types are not allowed to be
2676 // forward referenced and not allowed to be recursive.
2677 if (Lex.getKind() != lltok::lbrace) {
2678 if (Entry.first)
2679 return Error(TypeLoc, "forward references to non-struct type");
2680
2681 ResultTy = nullptr;
2682 if (isPacked)
2683 return ParseArrayVectorType(ResultTy, true);
2684 return ParseType(ResultTy);
2685 }
2686
2687 // This type is being defined, so clear the location to indicate this.
2688 Entry.second = SMLoc();
2689
2690 // If this type number has never been uttered, create it.
2691 if (!Entry.first)
2692 Entry.first = StructType::create(Context, Name);
2693
2694 StructType *STy = cast<StructType>(Entry.first);
2695
2696 SmallVector<Type*, 8> Body;
2697 if (ParseStructBody(Body) ||
2698 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2699 return true;
2700
2701 STy->setBody(Body, isPacked);
2702 ResultTy = STy;
2703 return false;
2704}
2705
2706/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2707/// StructType
2708/// ::= '{' '}'
2709/// ::= '{' Type (',' Type)* '}'
2710/// ::= '<' '{' '}' '>'
2711/// ::= '<' '{' Type (',' Type)* '}' '>'
2712bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2713 assert(Lex.getKind() == lltok::lbrace)((Lex.getKind() == lltok::lbrace) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lbrace", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 2713, __PRETTY_FUNCTION__))
;
2714 Lex.Lex(); // Consume the '{'
2715
2716 // Handle the empty struct.
2717 if (EatIfPresent(lltok::rbrace))
2718 return false;
2719
2720 LocTy EltTyLoc = Lex.getLoc();
2721 Type *Ty = nullptr;
2722 if (ParseType(Ty)) return true;
2723 Body.push_back(Ty);
2724
2725 if (!StructType::isValidElementType(Ty))
2726 return Error(EltTyLoc, "invalid element type for struct");
2727
2728 while (EatIfPresent(lltok::comma)) {
2729 EltTyLoc = Lex.getLoc();
2730 if (ParseType(Ty)) return true;
2731
2732 if (!StructType::isValidElementType(Ty))
2733 return Error(EltTyLoc, "invalid element type for struct");
2734
2735 Body.push_back(Ty);
2736 }
2737
2738 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2739}
2740
2741/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2742/// token has already been consumed.
2743/// Type
2744/// ::= '[' APSINTVAL 'x' Types ']'
2745/// ::= '<' APSINTVAL 'x' Types '>'
2746/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2747bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2748 bool Scalable = false;
2749
2750 if (isVector && Lex.getKind() == lltok::kw_vscale) {
2751 Lex.Lex(); // consume the 'vscale'
2752 if (ParseToken(lltok::kw_x, "expected 'x' after vscale"))
2753 return true;
2754
2755 Scalable = true;
2756 }
2757
2758 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2759 Lex.getAPSIntVal().getBitWidth() > 64)
2760 return TokError("expected number in address space");
2761
2762 LocTy SizeLoc = Lex.getLoc();
2763 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2764 Lex.Lex();
2765
2766 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2767 return true;
2768
2769 LocTy TypeLoc = Lex.getLoc();
2770 Type *EltTy = nullptr;
2771 if (ParseType(EltTy)) return true;
2772
2773 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2774 "expected end of sequential type"))
2775 return true;
2776
2777 if (isVector) {
2778 if (Size == 0)
2779 return Error(SizeLoc, "zero element vector is illegal");
2780 if ((unsigned)Size != Size)
2781 return Error(SizeLoc, "size too large for vector");
2782 if (!VectorType::isValidElementType(EltTy))
2783 return Error(TypeLoc, "invalid vector element type");
2784 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2785 } else {
2786 if (!ArrayType::isValidElementType(EltTy))
2787 return Error(TypeLoc, "invalid array element type");
2788 Result = ArrayType::get(EltTy, Size);
2789 }
2790 return false;
2791}
2792
2793//===----------------------------------------------------------------------===//
2794// Function Semantic Analysis.
2795//===----------------------------------------------------------------------===//
2796
2797LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2798 int functionNumber)
2799 : P(p), F(f), FunctionNumber(functionNumber) {
2800
2801 // Insert unnamed arguments into the NumberedVals list.
2802 for (Argument &A : F.args())
2803 if (!A.hasName())
2804 NumberedVals.push_back(&A);
2805}
2806
2807LLParser::PerFunctionState::~PerFunctionState() {
2808 // If there were any forward referenced non-basicblock values, delete them.
2809
2810 for (const auto &P : ForwardRefVals) {
2811 if (isa<BasicBlock>(P.second.first))
2812 continue;
2813 P.second.first->replaceAllUsesWith(
2814 UndefValue::get(P.second.first->getType()));
2815 P.second.first->deleteValue();
2816 }
2817
2818 for (const auto &P : ForwardRefValIDs) {
2819 if (isa<BasicBlock>(P.second.first))
2820 continue;
2821 P.second.first->replaceAllUsesWith(
2822 UndefValue::get(P.second.first->getType()));
2823 P.second.first->deleteValue();
2824 }
2825}
2826
2827bool LLParser::PerFunctionState::FinishFunction() {
2828 if (!ForwardRefVals.empty())
2829 return P.Error(ForwardRefVals.begin()->second.second,
2830 "use of undefined value '%" + ForwardRefVals.begin()->first +
2831 "'");
2832 if (!ForwardRefValIDs.empty())
2833 return P.Error(ForwardRefValIDs.begin()->second.second,
2834 "use of undefined value '%" +
2835 Twine(ForwardRefValIDs.begin()->first) + "'");
2836 return false;
2837}
2838
2839/// GetVal - Get a value with the specified name or ID, creating a
2840/// forward reference record if needed. This can return null if the value
2841/// exists but does not have the right type.
2842Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2843 LocTy Loc, bool IsCall) {
2844 // Look this name up in the normal function symbol table.
2845 Value *Val = F.getValueSymbolTable()->lookup(Name);
2846
2847 // If this is a forward reference for the value, see if we already created a
2848 // forward ref record.
2849 if (!Val) {
2850 auto I = ForwardRefVals.find(Name);
2851 if (I != ForwardRefVals.end())
2852 Val = I->second.first;
2853 }
2854
2855 // If we have the value in the symbol table or fwd-ref table, return it.
2856 if (Val)
2857 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2858
2859 // Don't make placeholders with invalid type.
2860 if (!Ty->isFirstClassType()) {
2861 P.Error(Loc, "invalid use of a non-first-class type");
2862 return nullptr;
2863 }
2864
2865 // Otherwise, create a new forward reference for this value and remember it.
2866 Value *FwdVal;
2867 if (Ty->isLabelTy()) {
2868 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2869 } else {
2870 FwdVal = new Argument(Ty, Name);
2871 }
2872
2873 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2874 return FwdVal;
2875}
2876
2877Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2878 bool IsCall) {
2879 // Look this name up in the normal function symbol table.
2880 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2881
2882 // If this is a forward reference for the value, see if we already created a
2883 // forward ref record.
2884 if (!Val) {
2885 auto I = ForwardRefValIDs.find(ID);
2886 if (I != ForwardRefValIDs.end())
2887 Val = I->second.first;
2888 }
2889
2890 // If we have the value in the symbol table or fwd-ref table, return it.
2891 if (Val)
2892 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2893
2894 if (!Ty->isFirstClassType()) {
2895 P.Error(Loc, "invalid use of a non-first-class type");
2896 return nullptr;
2897 }
2898
2899 // Otherwise, create a new forward reference for this value and remember it.
2900 Value *FwdVal;
2901 if (Ty->isLabelTy()) {
2902 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2903 } else {
2904 FwdVal = new Argument(Ty);
2905 }
2906
2907 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2908 return FwdVal;
2909}
2910
2911/// SetInstName - After an instruction is parsed and inserted into its
2912/// basic block, this installs its name.
2913bool LLParser::PerFunctionState::SetInstName(int NameID,
2914 const std::string &NameStr,
2915 LocTy NameLoc, Instruction *Inst) {
2916 // If this instruction has void type, it cannot have a name or ID specified.
2917 if (Inst->getType()->isVoidTy()) {
2918 if (NameID != -1 || !NameStr.empty())
2919 return P.Error(NameLoc, "instructions returning void cannot have a name");
2920 return false;
2921 }
2922
2923 // If this was a numbered instruction, verify that the instruction is the
2924 // expected value and resolve any forward references.
2925 if (NameStr.empty()) {
2926 // If neither a name nor an ID was specified, just use the next ID.
2927 if (NameID == -1)
2928 NameID = NumberedVals.size();
2929
2930 if (unsigned(NameID) != NumberedVals.size())
2931 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2932 Twine(NumberedVals.size()) + "'");
2933
2934 auto FI = ForwardRefValIDs.find(NameID);
2935 if (FI != ForwardRefValIDs.end()) {
2936 Value *Sentinel = FI->second.first;
2937 if (Sentinel->getType() != Inst->getType())
2938 return P.Error(NameLoc, "instruction forward referenced with type '" +
2939 getTypeString(FI->second.first->getType()) + "'");
2940
2941 Sentinel->replaceAllUsesWith(Inst);
2942 Sentinel->deleteValue();
2943 ForwardRefValIDs.erase(FI);
2944 }
2945
2946 NumberedVals.push_back(Inst);
2947 return false;
2948 }
2949
2950 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2951 auto FI = ForwardRefVals.find(NameStr);
2952 if (FI != ForwardRefVals.end()) {
2953 Value *Sentinel = FI->second.first;
2954 if (Sentinel->getType() != Inst->getType())
2955 return P.Error(NameLoc, "instruction forward referenced with type '" +
2956 getTypeString(FI->second.first->getType()) + "'");
2957
2958 Sentinel->replaceAllUsesWith(Inst);
2959 Sentinel->deleteValue();
2960 ForwardRefVals.erase(FI);
2961 }
2962
2963 // Set the name on the instruction.
2964 Inst->setName(NameStr);
2965
2966 if (Inst->getName() != NameStr)
2967 return P.Error(NameLoc, "multiple definition of local value named '" +
2968 NameStr + "'");
2969 return false;
2970}
2971
2972/// GetBB - Get a basic block with the specified name or ID, creating a
2973/// forward reference record if needed.
2974BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2975 LocTy Loc) {
2976 return dyn_cast_or_null<BasicBlock>(
2977 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2978}
2979
2980BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2981 return dyn_cast_or_null<BasicBlock>(
2982 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2983}
2984
2985/// DefineBB - Define the specified basic block, which is either named or
2986/// unnamed. If there is an error, this returns null otherwise it returns
2987/// the block being defined.
2988BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2989 int NameID, LocTy Loc) {
2990 BasicBlock *BB;
2991 if (Name.empty()) {
2992 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
2993 P.Error(Loc, "label expected to be numbered '" +
2994 Twine(NumberedVals.size()) + "'");
2995 return nullptr;
2996 }
2997 BB = GetBB(NumberedVals.size(), Loc);
2998 if (!BB) {
2999 P.Error(Loc, "unable to create block numbered '" +
3000 Twine(NumberedVals.size()) + "'");
3001 return nullptr;
3002 }
3003 } else {
3004 BB = GetBB(Name, Loc);
3005 if (!BB) {
3006 P.Error(Loc, "unable to create block named '" + Name + "'");
3007 return nullptr;
3008 }
3009 }
3010
3011 // Move the block to the end of the function. Forward ref'd blocks are
3012 // inserted wherever they happen to be referenced.
3013 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3014
3015 // Remove the block from forward ref sets.
3016 if (Name.empty()) {
3017 ForwardRefValIDs.erase(NumberedVals.size());
3018 NumberedVals.push_back(BB);
3019 } else {
3020 // BB forward references are already in the function symbol table.
3021 ForwardRefVals.erase(Name);
3022 }
3023
3024 return BB;
3025}
3026
3027//===----------------------------------------------------------------------===//
3028// Constants.
3029//===----------------------------------------------------------------------===//
3030
3031/// ParseValID - Parse an abstract value that doesn't necessarily have a
3032/// type implied. For example, if we parse "4" we don't know what integer type
3033/// it has. The value will later be combined with its type and checked for
3034/// sanity. PFS is used to convert function-local operands of metadata (since
3035/// metadata operands are not just parsed here but also converted to values).
3036/// PFS can be null when we are not parsing metadata values inside a function.
3037bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
3038 ID.Loc = Lex.getLoc();
3039 switch (Lex.getKind()) {
3040 default: return TokError("expected value token");
3041 case lltok::GlobalID: // @42
3042 ID.UIntVal = Lex.getUIntVal();
3043 ID.Kind = ValID::t_GlobalID;
3044 break;
3045 case lltok::GlobalVar: // @foo
3046 ID.StrVal = Lex.getStrVal();
3047 ID.Kind = ValID::t_GlobalName;
3048 break;
3049 case lltok::LocalVarID: // %42
3050 ID.UIntVal = Lex.getUIntVal();
3051 ID.Kind = ValID::t_LocalID;
3052 break;
3053 case lltok::LocalVar: // %foo
3054 ID.StrVal = Lex.getStrVal();
3055 ID.Kind = ValID::t_LocalName;
3056 break;
3057 case lltok::APSInt:
3058 ID.APSIntVal = Lex.getAPSIntVal();
3059 ID.Kind = ValID::t_APSInt;
3060 break;
3061 case lltok::APFloat:
3062 ID.APFloatVal = Lex.getAPFloatVal();
3063 ID.Kind = ValID::t_APFloat;
3064 break;
3065 case lltok::kw_true:
3066 ID.ConstantVal = ConstantInt::getTrue(Context);
3067 ID.Kind = ValID::t_Constant;
3068 break;
3069 case lltok::kw_false:
3070 ID.ConstantVal = ConstantInt::getFalse(Context);
3071 ID.Kind = ValID::t_Constant;
3072 break;
3073 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3074 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3075 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3076 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3077
3078 case lltok::lbrace: {
3079 // ValID ::= '{' ConstVector '}'
3080 Lex.Lex();
3081 SmallVector<Constant*, 16> Elts;
3082 if (ParseGlobalValueVector(Elts) ||
3083 ParseToken(lltok::rbrace, "expected end of struct constant"))
3084 return true;
3085
3086 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3087 ID.UIntVal = Elts.size();
3088 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3089 Elts.size() * sizeof(Elts[0]));
3090 ID.Kind = ValID::t_ConstantStruct;
3091 return false;
3092 }
3093 case lltok::less: {
3094 // ValID ::= '<' ConstVector '>' --> Vector.
3095 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3096 Lex.Lex();
3097 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3098
3099 SmallVector<Constant*, 16> Elts;
3100 LocTy FirstEltLoc = Lex.getLoc();
3101 if (ParseGlobalValueVector(Elts) ||
3102 (isPackedStruct &&
3103 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3104 ParseToken(lltok::greater, "expected end of constant"))
3105 return true;
3106
3107 if (isPackedStruct) {
3108 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3109 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3110 Elts.size() * sizeof(Elts[0]));
3111 ID.UIntVal = Elts.size();
3112 ID.Kind = ValID::t_PackedConstantStruct;
3113 return false;
3114 }
3115
3116 if (Elts.empty())
3117 return Error(ID.Loc, "constant vector must not be empty");
3118
3119 if (!Elts[0]->getType()->isIntegerTy() &&
3120 !Elts[0]->getType()->isFloatingPointTy() &&
3121 !Elts[0]->getType()->isPointerTy())
3122 return Error(FirstEltLoc,
3123 "vector elements must have integer, pointer or floating point type");
3124
3125 // Verify that all the vector elements have the same type.
3126 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3127 if (Elts[i]->getType() != Elts[0]->getType())
3128 return Error(FirstEltLoc,
3129 "vector element #" + Twine(i) +
3130 " is not of type '" + getTypeString(Elts[0]->getType()));
3131
3132 ID.ConstantVal = ConstantVector::get(Elts);
3133 ID.Kind = ValID::t_Constant;
3134 return false;
3135 }
3136 case lltok::lsquare: { // Array Constant
3137 Lex.Lex();
3138 SmallVector<Constant*, 16> Elts;
3139 LocTy FirstEltLoc = Lex.getLoc();
3140 if (ParseGlobalValueVector(Elts) ||
3141 ParseToken(lltok::rsquare, "expected end of array constant"))
3142 return true;
3143
3144 // Handle empty element.
3145 if (Elts.empty()) {
3146 // Use undef instead of an array because it's inconvenient to determine
3147 // the element type at this point, there being no elements to examine.
3148 ID.Kind = ValID::t_EmptyArray;
3149 return false;
3150 }
3151
3152 if (!Elts[0]->getType()->isFirstClassType())
3153 return Error(FirstEltLoc, "invalid array element type: " +
3154 getTypeString(Elts[0]->getType()));
3155
3156 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3157
3158 // Verify all elements are correct type!
3159 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3160 if (Elts[i]->getType() != Elts[0]->getType())
3161 return Error(FirstEltLoc,
3162 "array element #" + Twine(i) +
3163 " is not of type '" + getTypeString(Elts[0]->getType()));
3164 }
3165
3166 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3167 ID.Kind = ValID::t_Constant;
3168 return false;
3169 }
3170 case lltok::kw_c: // c "foo"
3171 Lex.Lex();
3172 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3173 false);
3174 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3175 ID.Kind = ValID::t_Constant;
3176 return false;
3177
3178 case lltok::kw_asm: {
3179 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3180 // STRINGCONSTANT
3181 bool HasSideEffect, AlignStack, AsmDialect;
3182 Lex.Lex();
3183 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3184 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3185 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3186 ParseStringConstant(ID.StrVal) ||
3187 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3188 ParseToken(lltok::StringConstant, "expected constraint string"))
3189 return true;
3190 ID.StrVal2 = Lex.getStrVal();
3191 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3192 (unsigned(AsmDialect)<<2);
3193 ID.Kind = ValID::t_InlineAsm;
3194 return false;
3195 }
3196
3197 case lltok::kw_blockaddress: {
3198 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3199 Lex.Lex();
3200
3201 ValID Fn, Label;
3202
3203 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3204 ParseValID(Fn) ||
3205 ParseToken(lltok::comma, "expected comma in block address expression")||
3206 ParseValID(Label) ||
3207 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3208 return true;
3209
3210 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3211 return Error(Fn.Loc, "expected function name in blockaddress");
3212 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3213 return Error(Label.Loc, "expected basic block name in blockaddress");
3214
3215 // Try to find the function (but skip it if it's forward-referenced).
3216 GlobalValue *GV = nullptr;
3217 if (Fn.Kind == ValID::t_GlobalID) {
3218 if (Fn.UIntVal < NumberedVals.size())
3219 GV = NumberedVals[Fn.UIntVal];
3220 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3221 GV = M->getNamedValue(Fn.StrVal);
3222 }
3223 Function *F = nullptr;
3224 if (GV) {
3225 // Confirm that it's actually a function with a definition.
3226 if (!isa<Function>(GV))
3227 return Error(Fn.Loc, "expected function name in blockaddress");
3228 F = cast<Function>(GV);
3229 if (F->isDeclaration())
3230 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3231 }
3232
3233 if (!F) {
3234 // Make a global variable as a placeholder for this reference.
3235 GlobalValue *&FwdRef =
3236 ForwardRefBlockAddresses.insert(std::make_pair(
3237 std::move(Fn),
3238 std::map<ValID, GlobalValue *>()))
3239 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3240 .first->second;
3241 if (!FwdRef)
3242 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3243 GlobalValue::InternalLinkage, nullptr, "");
3244 ID.ConstantVal = FwdRef;
3245 ID.Kind = ValID::t_Constant;
3246 return false;
3247 }
3248
3249 // We found the function; now find the basic block. Don't use PFS, since we
3250 // might be inside a constant expression.
3251 BasicBlock *BB;
3252 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3253 if (Label.Kind == ValID::t_LocalID)
3254 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3255 else
3256 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3257 if (!BB)
3258 return Error(Label.Loc, "referenced value is not a basic block");
3259 } else {
3260 if (Label.Kind == ValID::t_LocalID)
3261 return Error(Label.Loc, "cannot take address of numeric label after "
3262 "the function is defined");
3263 BB = dyn_cast_or_null<BasicBlock>(
3264 F->getValueSymbolTable()->lookup(Label.StrVal));
3265 if (!BB)
3266 return Error(Label.Loc, "referenced value is not a basic block");
3267 }
3268
3269 ID.ConstantVal = BlockAddress::get(F, BB);
3270 ID.Kind = ValID::t_Constant;
3271 return false;
3272 }
3273
3274 case lltok::kw_trunc:
3275 case lltok::kw_zext:
3276 case lltok::kw_sext:
3277 case lltok::kw_fptrunc:
3278 case lltok::kw_fpext:
3279 case lltok::kw_bitcast:
3280 case lltok::kw_addrspacecast:
3281 case lltok::kw_uitofp:
3282 case lltok::kw_sitofp:
3283 case lltok::kw_fptoui:
3284 case lltok::kw_fptosi:
3285 case lltok::kw_inttoptr:
3286 case lltok::kw_ptrtoint: {
3287 unsigned Opc = Lex.getUIntVal();
3288 Type *DestTy = nullptr;
3289 Constant *SrcVal;
3290 Lex.Lex();
3291 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3292 ParseGlobalTypeAndValue(SrcVal) ||
3293 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3294 ParseType(DestTy) ||
3295 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3296 return true;
3297 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3298 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3299 getTypeString(SrcVal->getType()) + "' to '" +
3300 getTypeString(DestTy) + "'");
3301 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3302 SrcVal, DestTy);
3303 ID.Kind = ValID::t_Constant;
3304 return false;
3305 }
3306 case lltok::kw_extractvalue: {
3307 Lex.Lex();
3308 Constant *Val;
3309 SmallVector<unsigned, 4> Indices;
3310 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3311 ParseGlobalTypeAndValue(Val) ||
3312 ParseIndexList(Indices) ||
3313 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3314 return true;
3315
3316 if (!Val->getType()->isAggregateType())
3317 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3318 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3319 return Error(ID.Loc, "invalid indices for extractvalue");
3320 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3321 ID.Kind = ValID::t_Constant;
3322 return false;
3323 }
3324 case lltok::kw_insertvalue: {
3325 Lex.Lex();
3326 Constant *Val0, *Val1;
3327 SmallVector<unsigned, 4> Indices;
3328 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3329 ParseGlobalTypeAndValue(Val0) ||
3330 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3331 ParseGlobalTypeAndValue(Val1) ||
3332 ParseIndexList(Indices) ||
3333 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3334 return true;
3335 if (!Val0->getType()->isAggregateType())
3336 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3337 Type *IndexedType =
3338 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3339 if (!IndexedType)
3340 return Error(ID.Loc, "invalid indices for insertvalue");
3341 if (IndexedType != Val1->getType())
3342 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3343 getTypeString(Val1->getType()) +
3344 "' instead of '" + getTypeString(IndexedType) +
3345 "'");
3346 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3347 ID.Kind = ValID::t_Constant;
3348 return false;
3349 }
3350 case lltok::kw_icmp:
3351 case lltok::kw_fcmp: {
3352 unsigned PredVal, Opc = Lex.getUIntVal();
3353 Constant *Val0, *Val1;
3354 Lex.Lex();
3355 if (ParseCmpPredicate(PredVal, Opc) ||
3356 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3357 ParseGlobalTypeAndValue(Val0) ||
3358 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3359 ParseGlobalTypeAndValue(Val1) ||
3360 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3361 return true;
3362
3363 if (Val0->getType() != Val1->getType())
3364 return Error(ID.Loc, "compare operands must have the same type");
3365
3366 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3367
3368 if (Opc == Instruction::FCmp) {
3369 if (!Val0->getType()->isFPOrFPVectorTy())
3370 return Error(ID.Loc, "fcmp requires floating point operands");
3371 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3372 } else {
3373 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!")((Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"
) ? static_cast<void> (0) : __assert_fail ("Opc == Instruction::ICmp && \"Unexpected opcode for CmpInst!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3373, __PRETTY_FUNCTION__))
;
3374 if (!Val0->getType()->isIntOrIntVectorTy() &&
3375 !Val0->getType()->isPtrOrPtrVectorTy())
3376 return Error(ID.Loc, "icmp requires pointer or integer operands");
3377 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3378 }
3379 ID.Kind = ValID::t_Constant;
3380 return false;
3381 }
3382
3383 // Unary Operators.
3384 case lltok::kw_fneg: {
3385 unsigned Opc = Lex.getUIntVal();
3386 Constant *Val;
3387 Lex.Lex();
3388 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3389 ParseGlobalTypeAndValue(Val) ||
3390 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3391 return true;
3392
3393 // Check that the type is valid for the operator.
3394 switch (Opc) {
3395 case Instruction::FNeg:
3396 if (!Val->getType()->isFPOrFPVectorTy())
3397 return Error(ID.Loc, "constexpr requires fp operands");
3398 break;
3399 default: llvm_unreachable("Unknown unary operator!")::llvm::llvm_unreachable_internal("Unknown unary operator!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3399)
;
3400 }
3401 unsigned Flags = 0;
3402 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3403 ID.ConstantVal = C;
3404 ID.Kind = ValID::t_Constant;
3405 return false;
3406 }
3407 // Binary Operators.
3408 case lltok::kw_add:
3409 case lltok::kw_fadd:
3410 case lltok::kw_sub:
3411 case lltok::kw_fsub:
3412 case lltok::kw_mul:
3413 case lltok::kw_fmul:
3414 case lltok::kw_udiv:
3415 case lltok::kw_sdiv:
3416 case lltok::kw_fdiv:
3417 case lltok::kw_urem:
3418 case lltok::kw_srem:
3419 case lltok::kw_frem:
3420 case lltok::kw_shl:
3421 case lltok::kw_lshr:
3422 case lltok::kw_ashr: {
3423 bool NUW = false;
3424 bool NSW = false;
3425 bool Exact = false;
3426 unsigned Opc = Lex.getUIntVal();
3427 Constant *Val0, *Val1;
3428 Lex.Lex();
3429 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3430 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3431 if (EatIfPresent(lltok::kw_nuw))
3432 NUW = true;
3433 if (EatIfPresent(lltok::kw_nsw)) {
3434 NSW = true;
3435 if (EatIfPresent(lltok::kw_nuw))
3436 NUW = true;
3437 }
3438 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3439 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3440 if (EatIfPresent(lltok::kw_exact))
3441 Exact = true;
3442 }
3443 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3444 ParseGlobalTypeAndValue(Val0) ||
3445 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3446 ParseGlobalTypeAndValue(Val1) ||
3447 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3448 return true;
3449 if (Val0->getType() != Val1->getType())
3450 return Error(ID.Loc, "operands of constexpr must have same type");
3451 // Check that the type is valid for the operator.
3452 switch (Opc) {
3453 case Instruction::Add:
3454 case Instruction::Sub:
3455 case Instruction::Mul:
3456 case Instruction::UDiv:
3457 case Instruction::SDiv:
3458 case Instruction::URem:
3459 case Instruction::SRem:
3460 case Instruction::Shl:
3461 case Instruction::AShr:
3462 case Instruction::LShr:
3463 if (!Val0->getType()->isIntOrIntVectorTy())
3464 return Error(ID.Loc, "constexpr requires integer operands");
3465 break;
3466 case Instruction::FAdd:
3467 case Instruction::FSub:
3468 case Instruction::FMul:
3469 case Instruction::FDiv:
3470 case Instruction::FRem:
3471 if (!Val0->getType()->isFPOrFPVectorTy())
3472 return Error(ID.Loc, "constexpr requires fp operands");
3473 break;
3474 default: llvm_unreachable("Unknown binary operator!")::llvm::llvm_unreachable_internal("Unknown binary operator!",
"/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3474)
;
3475 }
3476 unsigned Flags = 0;
3477 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3478 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3479 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3480 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3481 ID.ConstantVal = C;
3482 ID.Kind = ValID::t_Constant;
3483 return false;
3484 }
3485
3486 // Logical Operations
3487 case lltok::kw_and:
3488 case lltok::kw_or:
3489 case lltok::kw_xor: {
3490 unsigned Opc = Lex.getUIntVal();
3491 Constant *Val0, *Val1;
3492 Lex.Lex();
3493 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3494 ParseGlobalTypeAndValue(Val0) ||
3495 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3496 ParseGlobalTypeAndValue(Val1) ||
3497 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3498 return true;
3499 if (Val0->getType() != Val1->getType())
3500 return Error(ID.Loc, "operands of constexpr must have same type");
3501 if (!Val0->getType()->isIntOrIntVectorTy())
3502 return Error(ID.Loc,
3503 "constexpr requires integer or integer vector operands");
3504 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3505 ID.Kind = ValID::t_Constant;
3506 return false;
3507 }
3508
3509 case lltok::kw_getelementptr:
3510 case lltok::kw_shufflevector:
3511 case lltok::kw_insertelement:
3512 case lltok::kw_extractelement:
3513 case lltok::kw_select: {
3514 unsigned Opc = Lex.getUIntVal();
3515 SmallVector<Constant*, 16> Elts;
3516 bool InBounds = false;
3517 Type *Ty;
3518 Lex.Lex();
3519
3520 if (Opc == Instruction::GetElementPtr)
3521 InBounds = EatIfPresent(lltok::kw_inbounds);
3522
3523 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3524 return true;
3525
3526 LocTy ExplicitTypeLoc = Lex.getLoc();
3527 if (Opc == Instruction::GetElementPtr) {
3528 if (ParseType(Ty) ||
3529 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3530 return true;
3531 }
3532
3533 Optional<unsigned> InRangeOp;
3534 if (ParseGlobalValueVector(
3535 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3536 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3537 return true;
3538
3539 if (Opc == Instruction::GetElementPtr) {
3540 if (Elts.size() == 0 ||
3541 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3542 return Error(ID.Loc, "base of getelementptr must be a pointer");
3543
3544 Type *BaseType = Elts[0]->getType();
3545 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3546 if (Ty != BasePointerType->getElementType())
3547 return Error(
3548 ExplicitTypeLoc,
3549 "explicit pointee type doesn't match operand's pointee type");
3550
3551 unsigned GEPWidth =
3552 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3553
3554 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3555 for (Constant *Val : Indices) {
3556 Type *ValTy = Val->getType();
3557 if (!ValTy->isIntOrIntVectorTy())
3558 return Error(ID.Loc, "getelementptr index must be an integer");
3559 if (ValTy->isVectorTy()) {
3560 unsigned ValNumEl = ValTy->getVectorNumElements();
3561 if (GEPWidth && (ValNumEl != GEPWidth))
3562 return Error(
3563 ID.Loc,
3564 "getelementptr vector index has a wrong number of elements");
3565 // GEPWidth may have been unknown because the base is a scalar,
3566 // but it is known now.
3567 GEPWidth = ValNumEl;
3568 }
3569 }
3570
3571 SmallPtrSet<Type*, 4> Visited;
3572 if (!Indices.empty() && !Ty->isSized(&Visited))
3573 return Error(ID.Loc, "base element of getelementptr must be sized");
3574
3575 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3576 return Error(ID.Loc, "invalid getelementptr indices");
3577
3578 if (InRangeOp) {
3579 if (*InRangeOp == 0)
3580 return Error(ID.Loc,
3581 "inrange keyword may not appear on pointer operand");
3582 --*InRangeOp;
3583 }
3584
3585 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3586 InBounds, InRangeOp);
3587 } else if (Opc == Instruction::Select) {
3588 if (Elts.size() != 3)
3589 return Error(ID.Loc, "expected three operands to select");
3590 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3591 Elts[2]))
3592 return Error(ID.Loc, Reason);
3593 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3594 } else if (Opc == Instruction::ShuffleVector) {
3595 if (Elts.size() != 3)
3596 return Error(ID.Loc, "expected three operands to shufflevector");
3597 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3598 return Error(ID.Loc, "invalid operands to shufflevector");
3599 ID.ConstantVal =
3600 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3601 } else if (Opc == Instruction::ExtractElement) {
3602 if (Elts.size() != 2)
3603 return Error(ID.Loc, "expected two operands to extractelement");
3604 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3605 return Error(ID.Loc, "invalid extractelement operands");
3606 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3607 } else {
3608 assert(Opc == Instruction::InsertElement && "Unknown opcode")((Opc == Instruction::InsertElement && "Unknown opcode"
) ? static_cast<void> (0) : __assert_fail ("Opc == Instruction::InsertElement && \"Unknown opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3608, __PRETTY_FUNCTION__))
;
3609 if (Elts.size() != 3)
3610 return Error(ID.Loc, "expected three operands to insertelement");
3611 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3612 return Error(ID.Loc, "invalid insertelement operands");
3613 ID.ConstantVal =
3614 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3615 }
3616
3617 ID.Kind = ValID::t_Constant;
3618 return false;
3619 }
3620 }
3621
3622 Lex.Lex();
3623 return false;
3624}
3625
3626/// ParseGlobalValue - Parse a global value with the specified type.
3627bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3628 C = nullptr;
3629 ValID ID;
3630 Value *V = nullptr;
3631 bool Parsed = ParseValID(ID) ||
3632 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3633 if (V && !(C = dyn_cast<Constant>(V)))
3634 return Error(ID.Loc, "global values must be constants");
3635 return Parsed;
3636}
3637
3638bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3639 Type *Ty = nullptr;
3640 return ParseType(Ty) ||
3641 ParseGlobalValue(Ty, V);
3642}
3643
3644bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3645 C = nullptr;
3646
3647 LocTy KwLoc = Lex.getLoc();
3648 if (!EatIfPresent(lltok::kw_comdat))
3649 return false;
3650
3651 if (EatIfPresent(lltok::lparen)) {
3652 if (Lex.getKind() != lltok::ComdatVar)
3653 return TokError("expected comdat variable");
3654 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3655 Lex.Lex();
3656 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3657 return true;
3658 } else {
3659 if (GlobalName.empty())
3660 return TokError("comdat cannot be unnamed");
3661 C = getComdat(GlobalName, KwLoc);
3662 }
3663
3664 return false;
3665}
3666
3667/// ParseGlobalValueVector
3668/// ::= /*empty*/
3669/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3670bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3671 Optional<unsigned> *InRangeOp) {
3672 // Empty list.
3673 if (Lex.getKind() == lltok::rbrace ||
3674 Lex.getKind() == lltok::rsquare ||
3675 Lex.getKind() == lltok::greater ||
3676 Lex.getKind() == lltok::rparen)
3677 return false;
3678
3679 do {
3680 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3681 *InRangeOp = Elts.size();
3682
3683 Constant *C;
3684 if (ParseGlobalTypeAndValue(C)) return true;
3685 Elts.push_back(C);
3686 } while (EatIfPresent(lltok::comma));
3687
3688 return false;
3689}
3690
3691bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3692 SmallVector<Metadata *, 16> Elts;
3693 if (ParseMDNodeVector(Elts))
3694 return true;
3695
3696 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3697 return false;
3698}
3699
3700/// MDNode:
3701/// ::= !{ ... }
3702/// ::= !7
3703/// ::= !DILocation(...)
3704bool LLParser::ParseMDNode(MDNode *&N) {
3705 if (Lex.getKind() == lltok::MetadataVar)
3706 return ParseSpecializedMDNode(N);
3707
3708 return ParseToken(lltok::exclaim, "expected '!' here") ||
3709 ParseMDNodeTail(N);
3710}
3711
3712bool LLParser::ParseMDNodeTail(MDNode *&N) {
3713 // !{ ... }
3714 if (Lex.getKind() == lltok::lbrace)
3715 return ParseMDTuple(N);
3716
3717 // !42
3718 return ParseMDNodeID(N);
3719}
3720
3721namespace {
3722
3723/// Structure to represent an optional metadata field.
3724template <class FieldTy> struct MDFieldImpl {
3725 typedef MDFieldImpl ImplTy;
3726 FieldTy Val;
3727 bool Seen;
3728
3729 void assign(FieldTy Val) {
3730 Seen = true;
3731 this->Val = std::move(Val);
3732 }
3733
3734 explicit MDFieldImpl(FieldTy Default)
3735 : Val(std::move(Default)), Seen(false) {}
3736};
3737
3738/// Structure to represent an optional metadata field that
3739/// can be of either type (A or B) and encapsulates the
3740/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3741/// to reimplement the specifics for representing each Field.
3742template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3743 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3744 FieldTypeA A;
3745 FieldTypeB B;
3746 bool Seen;
3747
3748 enum {
3749 IsInvalid = 0,
3750 IsTypeA = 1,
3751 IsTypeB = 2
3752 } WhatIs;
3753
3754 void assign(FieldTypeA A) {
3755 Seen = true;
3756 this->A = std::move(A);
3757 WhatIs = IsTypeA;
3758 }
3759
3760 void assign(FieldTypeB B) {
3761 Seen = true;
3762 this->B = std::move(B);
3763 WhatIs = IsTypeB;
3764 }
3765
3766 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3767 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3768 WhatIs(IsInvalid) {}
3769};
3770
3771struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3772 uint64_t Max;
3773
3774 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX(18446744073709551615UL))
3775 : ImplTy(Default), Max(Max) {}
3776};
3777
3778struct LineField : public MDUnsignedField {
3779 LineField() : MDUnsignedField(0, UINT32_MAX(4294967295U)) {}
3780};
3781
3782struct ColumnField : public MDUnsignedField {
3783 ColumnField() : MDUnsignedField(0, UINT16_MAX(65535)) {}
3784};
3785
3786struct DwarfTagField : public MDUnsignedField {
3787 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3788 DwarfTagField(dwarf::Tag DefaultTag)
3789 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3790};
3791
3792struct DwarfMacinfoTypeField : public MDUnsignedField {
3793 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3794 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3795 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3796};
3797
3798struct DwarfAttEncodingField : public MDUnsignedField {
3799 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3800};
3801
3802struct DwarfVirtualityField : public MDUnsignedField {
3803 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3804};
3805
3806struct DwarfLangField : public MDUnsignedField {
3807 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3808};
3809
3810struct DwarfCCField : public MDUnsignedField {
3811 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3812};
3813
3814struct EmissionKindField : public MDUnsignedField {
3815 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3816};
3817
3818struct NameTableKindField : public MDUnsignedField {
3819 NameTableKindField()
3820 : MDUnsignedField(
3821 0, (unsigned)
3822 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3823};
3824
3825struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3826 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3827};
3828
3829struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3830 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3831};
3832
3833struct MDSignedField : public MDFieldImpl<int64_t> {
3834 int64_t Min;
3835 int64_t Max;
3836
3837 MDSignedField(int64_t Default = 0)
3838 : ImplTy(Default), Min(INT64_MIN(-9223372036854775807L -1)), Max(INT64_MAX(9223372036854775807L)) {}
3839 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3840 : ImplTy(Default), Min(Min), Max(Max) {}
3841};
3842
3843struct MDBoolField : public MDFieldImpl<bool> {
3844 MDBoolField(bool Default = false) : ImplTy(Default) {}
3845};
3846
3847struct MDField : public MDFieldImpl<Metadata *> {
3848 bool AllowNull;
3849
3850 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3851};
3852
3853struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3854 MDConstant() : ImplTy(nullptr) {}
3855};
3856
3857struct MDStringField : public MDFieldImpl<MDString *> {
3858 bool AllowEmpty;
3859 MDStringField(bool AllowEmpty = true)
3860 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3861};
3862
3863struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3864 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3865};
3866
3867struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3868 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3869};
3870
3871struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3872 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3873 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3874
3875 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3876 bool AllowNull = true)
3877 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3878
3879 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3880 bool isMDField() const { return WhatIs == IsTypeB; }
3881 int64_t getMDSignedValue() const {
3882 assert(isMDSignedField() && "Wrong field type")((isMDSignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDSignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3882, __PRETTY_FUNCTION__))
;
3883 return A.Val;
3884 }
3885 Metadata *getMDFieldValue() const {
3886 assert(isMDField() && "Wrong field type")((isMDField() && "Wrong field type") ? static_cast<
void> (0) : __assert_fail ("isMDField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3886, __PRETTY_FUNCTION__))
;
3887 return B.Val;
3888 }
3889};
3890
3891struct MDSignedOrUnsignedField
3892 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3893 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3894
3895 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3896 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3897 int64_t getMDSignedValue() const {
3898 assert(isMDSignedField() && "Wrong field type")((isMDSignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDSignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3898, __PRETTY_FUNCTION__))
;
3899 return A.Val;
3900 }
3901 uint64_t getMDUnsignedValue() const {
3902 assert(isMDUnsignedField() && "Wrong field type")((isMDUnsignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDUnsignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3902, __PRETTY_FUNCTION__))
;
3903 return B.Val;
3904 }
3905};
3906
3907} // end anonymous namespace
3908
3909namespace llvm {
3910
3911template <>
3912bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3913 MDUnsignedField &Result) {
3914 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3915 return TokError("expected unsigned integer");
3916
3917 auto &U = Lex.getAPSIntVal();
3918 if (U.ugt(Result.Max))
3919 return TokError("value for '" + Name + "' too large, limit is " +
3920 Twine(Result.Max));
3921 Result.assign(U.getZExtValue());
3922 assert(Result.Val <= Result.Max && "Expected value in range")((Result.Val <= Result.Max && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val <= Result.Max && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3922, __PRETTY_FUNCTION__))
;
3923 Lex.Lex();
3924 return false;
3925}
3926
3927template <>
3928bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3929 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3930}
3931template <>
3932bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3933 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3934}
3935
3936template <>
3937bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3938 if (Lex.getKind() == lltok::APSInt)
3939 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3940
3941 if (Lex.getKind() != lltok::DwarfTag)
3942 return TokError("expected DWARF tag");
3943
3944 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3945 if (Tag == dwarf::DW_TAG_invalid)
3946 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3947 assert(Tag <= Result.Max && "Expected valid DWARF tag")((Tag <= Result.Max && "Expected valid DWARF tag")
? static_cast<void> (0) : __assert_fail ("Tag <= Result.Max && \"Expected valid DWARF tag\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3947, __PRETTY_FUNCTION__))
;
3948
3949 Result.assign(Tag);
3950 Lex.Lex();
3951 return false;
3952}
3953
3954template <>
3955bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3956 DwarfMacinfoTypeField &Result) {
3957 if (Lex.getKind() == lltok::APSInt)
3958 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3959
3960 if (Lex.getKind() != lltok::DwarfMacinfo)
3961 return TokError("expected DWARF macinfo type");
3962
3963 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3964 if (Macinfo == dwarf::DW_MACINFO_invalid)
3965 return TokError(
3966 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3967 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type")((Macinfo <= Result.Max && "Expected valid DWARF macinfo type"
) ? static_cast<void> (0) : __assert_fail ("Macinfo <= Result.Max && \"Expected valid DWARF macinfo type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3967, __PRETTY_FUNCTION__))
;
3968
3969 Result.assign(Macinfo);
3970 Lex.Lex();
3971 return false;
3972}
3973
3974template <>
3975bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3976 DwarfVirtualityField &Result) {
3977 if (Lex.getKind() == lltok::APSInt)
3978 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3979
3980 if (Lex.getKind() != lltok::DwarfVirtuality)
3981 return TokError("expected DWARF virtuality code");
3982
3983 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3984 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3985 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3986 Lex.getStrVal() + "'");
3987 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code")((Virtuality <= Result.Max && "Expected valid DWARF virtuality code"
) ? static_cast<void> (0) : __assert_fail ("Virtuality <= Result.Max && \"Expected valid DWARF virtuality code\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 3987, __PRETTY_FUNCTION__))
;
3988 Result.assign(Virtuality);
3989 Lex.Lex();
3990 return false;
3991}
3992
3993template <>
3994bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3995 if (Lex.getKind() == lltok::APSInt)
3996 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3997
3998 if (Lex.getKind() != lltok::DwarfLang)
3999 return TokError("expected DWARF language");
4000
4001 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4002 if (!Lang)
4003 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4004 "'");
4005 assert(Lang <= Result.Max && "Expected valid DWARF language")((Lang <= Result.Max && "Expected valid DWARF language"
) ? static_cast<void> (0) : __assert_fail ("Lang <= Result.Max && \"Expected valid DWARF language\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4005, __PRETTY_FUNCTION__))
;
4006 Result.assign(Lang);
4007 Lex.Lex();
4008 return false;
4009}
4010
4011template <>
4012bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4013 if (Lex.getKind() == lltok::APSInt)
4014 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4015
4016 if (Lex.getKind() != lltok::DwarfCC)
4017 return TokError("expected DWARF calling convention");
4018
4019 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4020 if (!CC)
4021 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
4022 "'");
4023 assert(CC <= Result.Max && "Expected valid DWARF calling convention")((CC <= Result.Max && "Expected valid DWARF calling convention"
) ? static_cast<void> (0) : __assert_fail ("CC <= Result.Max && \"Expected valid DWARF calling convention\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4023, __PRETTY_FUNCTION__))
;
4024 Result.assign(CC);
4025 Lex.Lex();
4026 return false;
4027}
4028
4029template <>
4030bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
4031 if (Lex.getKind() == lltok::APSInt)
4032 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4033
4034 if (Lex.getKind() != lltok::EmissionKind)
4035 return TokError("expected emission kind");
4036
4037 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4038 if (!Kind)
4039 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4040 "'");
4041 assert(*Kind <= Result.Max && "Expected valid emission kind")((*Kind <= Result.Max && "Expected valid emission kind"
) ? static_cast<void> (0) : __assert_fail ("*Kind <= Result.Max && \"Expected valid emission kind\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4041, __PRETTY_FUNCTION__))
;
4042 Result.assign(*Kind);
4043 Lex.Lex();
4044 return false;
4045}
4046
4047template <>
4048bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4049 NameTableKindField &Result) {
4050 if (Lex.getKind() == lltok::APSInt)
4051 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4052
4053 if (Lex.getKind() != lltok::NameTableKind)
4054 return TokError("expected nameTable kind");
4055
4056 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4057 if (!Kind)
4058 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4059 "'");
4060 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind")((((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"
) ? static_cast<void> (0) : __assert_fail ("((unsigned)*Kind) <= Result.Max && \"Expected valid nameTable kind\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4060, __PRETTY_FUNCTION__))
;
4061 Result.assign((unsigned)*Kind);
4062 Lex.Lex();
4063 return false;
4064}
4065
4066template <>
4067bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4068 DwarfAttEncodingField &Result) {
4069 if (Lex.getKind() == lltok::APSInt)
4070 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4071
4072 if (Lex.getKind() != lltok::DwarfAttEncoding)
4073 return TokError("expected DWARF type attribute encoding");
4074
4075 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4076 if (!Encoding)
4077 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4078 Lex.getStrVal() + "'");
4079 assert(Encoding <= Result.Max && "Expected valid DWARF language")((Encoding <= Result.Max && "Expected valid DWARF language"
) ? static_cast<void> (0) : __assert_fail ("Encoding <= Result.Max && \"Expected valid DWARF language\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4079, __PRETTY_FUNCTION__))
;
4080 Result.assign(Encoding);
4081 Lex.Lex();
4082 return false;
4083}
4084
4085/// DIFlagField
4086/// ::= uint32
4087/// ::= DIFlagVector
4088/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4089template <>
4090bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4091
4092 // Parser for a single flag.
4093 auto parseFlag = [&](DINode::DIFlags &Val) {
4094 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4095 uint32_t TempVal = static_cast<uint32_t>(Val);
4096 bool Res = ParseUInt32(TempVal);
4097 Val = static_cast<DINode::DIFlags>(TempVal);
4098 return Res;
4099 }
4100
4101 if (Lex.getKind() != lltok::DIFlag)
4102 return TokError("expected debug info flag");
4103
4104 Val = DINode::getFlag(Lex.getStrVal());
4105 if (!Val)
4106 return TokError(Twine("invalid debug info flag flag '") +
4107 Lex.getStrVal() + "'");
4108 Lex.Lex();
4109 return false;
4110 };
4111
4112 // Parse the flags and combine them together.
4113 DINode::DIFlags Combined = DINode::FlagZero;
4114 do {
4115 DINode::DIFlags Val;
4116 if (parseFlag(Val))
4117 return true;
4118 Combined |= Val;
4119 } while (EatIfPresent(lltok::bar));
4120
4121 Result.assign(Combined);
4122 return false;
4123}
4124
4125/// DISPFlagField
4126/// ::= uint32
4127/// ::= DISPFlagVector
4128/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4129template <>
4130bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4131
4132 // Parser for a single flag.
4133 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4134 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4135 uint32_t TempVal = static_cast<uint32_t>(Val);
4136 bool Res = ParseUInt32(TempVal);
4137 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4138 return Res;
4139 }
4140
4141 if (Lex.getKind() != lltok::DISPFlag)
4142 return TokError("expected debug info flag");
4143
4144 Val = DISubprogram::getFlag(Lex.getStrVal());
4145 if (!Val)
4146 return TokError(Twine("invalid subprogram debug info flag '") +
4147 Lex.getStrVal() + "'");
4148 Lex.Lex();
4149 return false;
4150 };
4151
4152 // Parse the flags and combine them together.
4153 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4154 do {
4155 DISubprogram::DISPFlags Val;
4156 if (parseFlag(Val))
4157 return true;
4158 Combined |= Val;
4159 } while (EatIfPresent(lltok::bar));
4160
4161 Result.assign(Combined);
4162 return false;
4163}
4164
4165template <>
4166bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4167 MDSignedField &Result) {
4168 if (Lex.getKind() != lltok::APSInt)
4169 return TokError("expected signed integer");
4170
4171 auto &S = Lex.getAPSIntVal();
4172 if (S < Result.Min)
4173 return TokError("value for '" + Name + "' too small, limit is " +
4174 Twine(Result.Min));
4175 if (S > Result.Max)
4176 return TokError("value for '" + Name + "' too large, limit is " +
4177 Twine(Result.Max));
4178 Result.assign(S.getExtValue());
4179 assert(Result.Val >= Result.Min && "Expected value in range")((Result.Val >= Result.Min && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val >= Result.Min && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4179, __PRETTY_FUNCTION__))
;
4180 assert(Result.Val <= Result.Max && "Expected value in range")((Result.Val <= Result.Max && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val <= Result.Max && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4180, __PRETTY_FUNCTION__))
;
4181 Lex.Lex();
4182 return false;
4183}
4184
4185template <>
4186bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4187 switch (Lex.getKind()) {
4188 default:
4189 return TokError("expected 'true' or 'false'");
4190 case lltok::kw_true:
4191 Result.assign(true);
4192 break;
4193 case lltok::kw_false:
4194 Result.assign(false);
4195 break;
4196 }
4197 Lex.Lex();
4198 return false;
4199}
4200
4201template <>
4202bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4203 if (Lex.getKind() == lltok::kw_null) {
4204 if (!Result.AllowNull)
4205 return TokError("'" + Name + "' cannot be null");
4206 Lex.Lex();
4207 Result.assign(nullptr);
4208 return false;
4209 }
4210
4211 Metadata *MD;
4212 if (ParseMetadata(MD, nullptr))
4213 return true;
4214
4215 Result.assign(MD);
4216 return false;
4217}
4218
4219template <>
4220bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4221 MDSignedOrMDField &Result) {
4222 // Try to parse a signed int.
4223 if (Lex.getKind() == lltok::APSInt) {
4224 MDSignedField Res = Result.A;
4225 if (!ParseMDField(Loc, Name, Res)) {
4226 Result.assign(Res);
4227 return false;
4228 }
4229 return true;
4230 }
4231
4232 // Otherwise, try to parse as an MDField.
4233 MDField Res = Result.B;
4234 if (!ParseMDField(Loc, Name, Res)) {
4235 Result.assign(Res);
4236 return false;
4237 }
4238
4239 return true;
4240}
4241
4242template <>
4243bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4244 MDSignedOrUnsignedField &Result) {
4245 if (Lex.getKind() != lltok::APSInt)
4246 return false;
4247
4248 if (Lex.getAPSIntVal().isSigned()) {
4249 MDSignedField Res = Result.A;
4250 if (ParseMDField(Loc, Name, Res))
4251 return true;
4252 Result.assign(Res);
4253 return false;
4254 }
4255
4256 MDUnsignedField Res = Result.B;
4257 if (ParseMDField(Loc, Name, Res))
4258 return true;
4259 Result.assign(Res);
4260 return false;
4261}
4262
4263template <>
4264bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4265 LocTy ValueLoc = Lex.getLoc();
4266 std::string S;
4267 if (ParseStringConstant(S))
4268 return true;
4269
4270 if (!Result.AllowEmpty && S.empty())
4271 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4272
4273 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4274 return false;
4275}
4276
4277template <>
4278bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4279 SmallVector<Metadata *, 4> MDs;
4280 if (ParseMDNodeVector(MDs))
4281 return true;
4282
4283 Result.assign(std::move(MDs));
4284 return false;
4285}
4286
4287template <>
4288bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4289 ChecksumKindField &Result) {
4290 Optional<DIFile::ChecksumKind> CSKind =
4291 DIFile::getChecksumKind(Lex.getStrVal());
4292
4293 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4294 return TokError(
4295 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4296
4297 Result.assign(*CSKind);
4298 Lex.Lex();
4299 return false;
4300}
4301
4302} // end namespace llvm
4303
4304template <class ParserTy>
4305bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4306 do {
4307 if (Lex.getKind() != lltok::LabelStr)
4308 return TokError("expected field label here");
4309
4310 if (parseField())
4311 return true;
4312 } while (EatIfPresent(lltok::comma));
4313
4314 return false;
4315}
4316
4317template <class ParserTy>
4318bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4319 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4319, __PRETTY_FUNCTION__))
;
4320 Lex.Lex();
4321
4322 if (ParseToken(lltok::lparen, "expected '(' here"))
4323 return true;
4324 if (Lex.getKind() != lltok::rparen)
4325 if (ParseMDFieldsImplBody(parseField))
4326 return true;
4327
4328 ClosingLoc = Lex.getLoc();
4329 return ParseToken(lltok::rparen, "expected ')' here");
4330}
4331
4332template <class FieldTy>
4333bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4334 if (Result.Seen)
4335 return TokError("field '" + Name + "' cannot be specified more than once");
4336
4337 LocTy Loc = Lex.getLoc();
4338 Lex.Lex();
4339 return ParseMDField(Loc, Name, Result);
4340}
4341
4342bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4343 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4343, __PRETTY_FUNCTION__))
;
4344
4345#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4346 if (Lex.getStrVal() == #CLASS) \
4347 return Parse##CLASS(N, IsDistinct);
4348#include "llvm/IR/Metadata.def"
4349
4350 return TokError("expected metadata type");
4351}
4352
4353#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4354#define NOP_FIELD(NAME, TYPE, INIT)
4355#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4356 if (!NAME.Seen) \
4357 return Error(ClosingLoc, "missing required field '" #NAME "'");
4358#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4359 if (Lex.getStrVal() == #NAME) \
4360 return ParseMDField(#NAME, NAME);
4361#define PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
\
4362 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4363 do { \
4364 LocTy ClosingLoc; \
4365 if (ParseMDFieldsImpl([&]() -> bool { \
4366 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4367 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4368 }, ClosingLoc)) \
4369 return true; \
4370 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4371 } while (false)
4372#define GET_OR_DISTINCT(CLASS, ARGS)(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) \
4373 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4374
4375/// ParseDILocationFields:
4376/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4377/// isImplicitCode: true)
4378bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4379#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4380 OPTIONAL(line, LineField, ); \
4381 OPTIONAL(column, ColumnField, ); \
4382 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4383 OPTIONAL(inlinedAt, MDField, ); \
4384 OPTIONAL(isImplicitCode, MDBoolField, (false));
4385 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4386#undef VISIT_MD_FIELDS
4387
4388 Result =
4389 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
4390 inlinedAt.Val, isImplicitCode.Val))(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
;
4391 return false;
4392}
4393
4394/// ParseGenericDINode:
4395/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4396bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4397#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4398 REQUIRED(tag, DwarfTagField, ); \
4399 OPTIONAL(header, MDStringField, ); \
4400 OPTIONAL(operands, MDFieldList, );
4401 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4402#undef VISIT_MD_FIELDS
4403
4404 Result = GET_OR_DISTINCT(GenericDINode,(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
4405 (Context, tag.Val, header.Val, operands.Val))(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
;
4406 return false;
4407}
4408
4409/// ParseDISubrange:
4410/// ::= !DISubrange(count: 30, lowerBound: 2)
4411/// ::= !DISubrange(count: !node, lowerBound: 2)
4412bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4413#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4414 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX(9223372036854775807L), false)); \
4415 OPTIONAL(lowerBound, MDSignedField, );
4416 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4417#undef VISIT_MD_FIELDS
4418
4419 if (count.isMDSignedField())
4420 Result = GET_OR_DISTINCT((IsDistinct ? DISubrange::getDistinct (Context, count.getMDSignedValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDSignedValue
(), lowerBound.Val))
4421 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val))(IsDistinct ? DISubrange::getDistinct (Context, count.getMDSignedValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDSignedValue
(), lowerBound.Val))
;
4422 else if (count.isMDField())
4423 Result = GET_OR_DISTINCT((IsDistinct ? DISubrange::getDistinct (Context, count.getMDFieldValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDFieldValue
(), lowerBound.Val))
4424 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val))(IsDistinct ? DISubrange::getDistinct (Context, count.getMDFieldValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDFieldValue
(), lowerBound.Val))
;
4425 else
4426 return true;
4427
4428 return false;
4429}
4430
4431/// ParseDIEnumerator:
4432/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4433bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4434#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4435 REQUIRED(name, MDStringField, ); \
4436 REQUIRED(value, MDSignedOrUnsignedField, ); \
4437 OPTIONAL(isUnsigned, MDBoolField, (false));
4438 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4439#undef VISIT_MD_FIELDS
4440
4441 if (isUnsigned.Val && value.isMDSignedField())
4442 return TokError("unsigned enumerator with negative value");
4443
4444 int64_t Value = value.isMDSignedField()
4445 ? value.getMDSignedValue()
4446 : static_cast<int64_t>(value.getMDUnsignedValue());
4447 Result =
4448 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val))(IsDistinct ? DIEnumerator::getDistinct (Context, Value, isUnsigned
.Val, name.Val) : DIEnumerator::get (Context, Value, isUnsigned
.Val, name.Val))
;
4449
4450 return false;
4451}
4452
4453/// ParseDIBasicType:
4454/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4455/// encoding: DW_ATE_encoding, flags: 0)
4456bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4457#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4458 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4459 OPTIONAL(name, MDStringField, ); \
4460 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4461 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4462 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4463 OPTIONAL(flags, DIFlagField, );
4464 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4465#undef VISIT_MD_FIELDS
4466
4467 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
4468 align.Val, encoding.Val, flags.Val))(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
;
4469 return false;
4470}
4471
4472/// ParseDIDerivedType:
4473/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4474/// line: 7, scope: !1, baseType: !2, size: 32,
4475/// align: 32, offset: 0, flags: 0, extraData: !3,
4476/// dwarfAddressSpace: 3)
4477bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4478#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4479 REQUIRED(tag, DwarfTagField, ); \
4480 OPTIONAL(name, MDStringField, ); \
4481 OPTIONAL(file, MDField, ); \
4482 OPTIONAL(line, LineField, ); \
4483 OPTIONAL(scope, MDField, ); \
4484 REQUIRED(baseType, MDField, ); \
4485 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4486 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4487 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4488 OPTIONAL(flags, DIFlagField, ); \
4489 OPTIONAL(extraData, MDField, ); \
4490 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX(4294967295U), UINT32_MAX(4294967295U)));
4491 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4492#undef VISIT_MD_FIELDS
4493
4494 Optional<unsigned> DWARFAddressSpace;
4495 if (dwarfAddressSpace.Val != UINT32_MAX(4294967295U))
4496 DWARFAddressSpace = dwarfAddressSpace.Val;
4497
4498 Result = GET_OR_DISTINCT(DIDerivedType,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4499 (Context, tag.Val, name.Val, file.Val, line.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4500 scope.Val, baseType.Val, size.Val, align.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4501 offset.Val, DWARFAddressSpace, flags.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4502 extraData.Val))(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
;
4503 return false;
4504}
4505
4506bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4507#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4508 REQUIRED(tag, DwarfTagField, ); \
4509 OPTIONAL(name, MDStringField, ); \
4510 OPTIONAL(file, MDField, ); \
4511 OPTIONAL(line, LineField, ); \
4512 OPTIONAL(scope, MDField, ); \
4513 OPTIONAL(baseType, MDField, ); \
4514 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4515 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4516 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4517 OPTIONAL(flags, DIFlagField, ); \
4518 OPTIONAL(elements, MDField, ); \
4519 OPTIONAL(runtimeLang, DwarfLangField, ); \
4520 OPTIONAL(vtableHolder, MDField, ); \
4521 OPTIONAL(templateParams, MDField, ); \
4522 OPTIONAL(identifier, MDStringField, ); \
4523 OPTIONAL(discriminator, MDField, );
4524 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4525#undef VISIT_MD_FIELDS
4526
4527 // If this has an identifier try to build an ODR type.
4528 if (identifier.Val)
4529 if (auto *CT = DICompositeType::buildODRType(
4530 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4531 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4532 elements.Val, runtimeLang.Val, vtableHolder.Val,
4533 templateParams.Val, discriminator.Val)) {
4534 Result = CT;
4535 return false;
4536 }
4537
4538 // Create a new node, and save it in the context if it belongs in the type
4539 // map.
4540 Result = GET_OR_DISTINCT((IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4541 DICompositeType,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4542 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4543 size.Val, align.Val, offset.Val, flags.Val, elements.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4544 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4545 discriminator.Val))(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
;
4546 return false;
4547}
4548
4549bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4550#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4551 OPTIONAL(flags, DIFlagField, ); \
4552 OPTIONAL(cc, DwarfCCField, ); \
4553 REQUIRED(types, MDField, );
4554 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4555#undef VISIT_MD_FIELDS
4556
4557 Result = GET_OR_DISTINCT(DISubroutineType,(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
4558 (Context, flags.Val, cc.Val, types.Val))(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
;
4559 return false;
4560}
4561
4562/// ParseDIFileType:
4563/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4564/// checksumkind: CSK_MD5,
4565/// checksum: "000102030405060708090a0b0c0d0e0f",
4566/// source: "source file contents")
4567bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4568 // The default constructed value for checksumkind is required, but will never
4569 // be used, as the parser checks if the field was actually Seen before using
4570 // the Val.
4571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4572 REQUIRED(filename, MDStringField, ); \
4573 REQUIRED(directory, MDStringField, ); \
4574 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4575 OPTIONAL(checksum, MDStringField, ); \
4576 OPTIONAL(source, MDStringField, );
4577 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4578#undef VISIT_MD_FIELDS
4579
4580 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4581 if (checksumkind.Seen && checksum.Seen)
4582 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4583 else if (checksumkind.Seen || checksum.Seen)
4584 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4585
4586 Optional<MDString *> OptSource;
4587 if (source.Seen)
4588 OptSource = source.Val;
4589 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
4590 OptChecksum, OptSource))(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
;
4591 return false;
4592}
4593
4594/// ParseDICompileUnit:
4595/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4596/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4597/// splitDebugFilename: "abc.debug",
4598/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4599/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4600bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4601 if (!IsDistinct)
4602 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4603
4604#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4605 REQUIRED(language, DwarfLangField, ); \
4606 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4607 OPTIONAL(producer, MDStringField, ); \
4608 OPTIONAL(isOptimized, MDBoolField, ); \
4609 OPTIONAL(flags, MDStringField, ); \
4610 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4611 OPTIONAL(splitDebugFilename, MDStringField, ); \
4612 OPTIONAL(emissionKind, EmissionKindField, ); \
4613 OPTIONAL(enums, MDField, ); \
4614 OPTIONAL(retainedTypes, MDField, ); \
4615 OPTIONAL(globals, MDField, ); \
4616 OPTIONAL(imports, MDField, ); \
4617 OPTIONAL(macros, MDField, ); \
4618 OPTIONAL(dwoId, MDUnsignedField, ); \
4619 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4620 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4621 OPTIONAL(nameTableKind, NameTableKindField, ); \
4622 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4623 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4624#undef VISIT_MD_FIELDS
4625
4626 Result = DICompileUnit::getDistinct(
4627 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4628 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4629 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4630 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4631 debugBaseAddress.Val);
4632 return false;
4633}
4634
4635/// ParseDISubprogram:
4636/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4637/// file: !1, line: 7, type: !2, isLocal: false,
4638/// isDefinition: true, scopeLine: 8, containingType: !3,
4639/// virtuality: DW_VIRTUALTIY_pure_virtual,
4640/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4641/// spFlags: 10, isOptimized: false, templateParams: !4,
4642/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4643bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4644 auto Loc = Lex.getLoc();
4645#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4646 OPTIONAL(scope, MDField, ); \
4647 OPTIONAL(name, MDStringField, ); \
4648 OPTIONAL(linkageName, MDStringField, ); \
4649 OPTIONAL(file, MDField, ); \
4650 OPTIONAL(line, LineField, ); \
4651 OPTIONAL(type, MDField, ); \
4652 OPTIONAL(isLocal, MDBoolField, ); \
4653 OPTIONAL(isDefinition, MDBoolField, (true)); \
4654 OPTIONAL(scopeLine, LineField, ); \
4655 OPTIONAL(containingType, MDField, ); \
4656 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4657 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4658 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN(-2147483647-1), INT32_MAX(2147483647))); \
4659 OPTIONAL(flags, DIFlagField, ); \
4660 OPTIONAL(spFlags, DISPFlagField, ); \
4661 OPTIONAL(isOptimized, MDBoolField, ); \
4662 OPTIONAL(unit, MDField, ); \
4663 OPTIONAL(templateParams, MDField, ); \
4664 OPTIONAL(declaration, MDField, ); \
4665 OPTIONAL(retainedNodes, MDField, ); \
4666 OPTIONAL(thrownTypes, MDField, );
4667 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4668#undef VISIT_MD_FIELDS
4669
4670 // An explicit spFlags field takes precedence over individual fields in
4671 // older IR versions.
4672 DISubprogram::DISPFlags SPFlags =
4673 spFlags.Seen ? spFlags.Val
4674 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4675 isOptimized.Val, virtuality.Val);
4676 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4677 return Lex.Error(
4678 Loc,
4679 "missing 'distinct', required for !DISubprogram that is a Definition");
4680 Result = GET_OR_DISTINCT((IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4681 DISubprogram,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4682 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4683 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4684 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4685 declaration.Val, retainedNodes.Val, thrownTypes.Val))(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
;
4686 return false;
4687}
4688
4689/// ParseDILexicalBlock:
4690/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4691bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4692#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4693 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4694 OPTIONAL(file, MDField, ); \
4695 OPTIONAL(line, LineField, ); \
4696 OPTIONAL(column, ColumnField, );
4697 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4698#undef VISIT_MD_FIELDS
4699
4700 Result = GET_OR_DISTINCT((IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
4701 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val))(IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
;
4702 return false;
4703}
4704
4705/// ParseDILexicalBlockFile:
4706/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4707bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4708#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4709 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4710 OPTIONAL(file, MDField, ); \
4711 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4712 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4713#undef VISIT_MD_FIELDS
4714
4715 Result = GET_OR_DISTINCT(DILexicalBlockFile,(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
4716 (Context, scope.Val, file.Val, discriminator.Val))(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
;
4717 return false;
4718}
4719
4720/// ParseDICommonBlock:
4721/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4722bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4723#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4724 REQUIRED(scope, MDField, ); \
4725 OPTIONAL(declaration, MDField, ); \
4726 OPTIONAL(name, MDStringField, ); \
4727 OPTIONAL(file, MDField, ); \
4728 OPTIONAL(line, LineField, );
4729 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4730#undef VISIT_MD_FIELDS
4731
4732 Result = GET_OR_DISTINCT(DICommonBlock,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4733 (Context, scope.Val, declaration.Val, name.Val,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4734 file.Val, line.Val))(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
;
4735 return false;
4736}
4737
4738/// ParseDINamespace:
4739/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4740bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4741#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4742 REQUIRED(scope, MDField, ); \
4743 OPTIONAL(name, MDStringField, ); \
4744 OPTIONAL(exportSymbols, MDBoolField, );
4745 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4746#undef VISIT_MD_FIELDS
4747
4748 Result = GET_OR_DISTINCT(DINamespace,(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
4749 (Context, scope.Val, name.Val, exportSymbols.Val))(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
;
4750 return false;
4751}
4752
4753/// ParseDIMacro:
4754/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4755bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4756#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4757 REQUIRED(type, DwarfMacinfoTypeField, ); \
4758 OPTIONAL(line, LineField, ); \
4759 REQUIRED(name, MDStringField, ); \
4760 OPTIONAL(value, MDStringField, );
4761 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4762#undef VISIT_MD_FIELDS
4763
4764 Result = GET_OR_DISTINCT(DIMacro,(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
4765 (Context, type.Val, line.Val, name.Val, value.Val))(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
;
4766 return false;
4767}
4768
4769/// ParseDIMacroFile:
4770/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4771bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4772#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4773 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4774 OPTIONAL(line, LineField, ); \
4775 REQUIRED(file, MDField, ); \
4776 OPTIONAL(nodes, MDField, );
4777 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4778#undef VISIT_MD_FIELDS
4779
4780 Result = GET_OR_DISTINCT(DIMacroFile,(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
4781 (Context, type.Val, line.Val, file.Val, nodes.Val))(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
;
4782 return false;
4783}
4784
4785/// ParseDIModule:
4786/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4787/// includePath: "/usr/include", isysroot: "/")
4788bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4789#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4790 REQUIRED(scope, MDField, ); \
4791 REQUIRED(name, MDStringField, ); \
4792 OPTIONAL(configMacros, MDStringField, ); \
4793 OPTIONAL(includePath, MDStringField, ); \
4794 OPTIONAL(isysroot, MDStringField, );
4795 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4796#undef VISIT_MD_FIELDS
4797
4798 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,(IsDistinct ? DIModule::getDistinct (Context, scope.Val, name
.Val, configMacros.Val, includePath.Val, isysroot.Val) : DIModule
::get (Context, scope.Val, name.Val, configMacros.Val, includePath
.Val, isysroot.Val))
4799 configMacros.Val, includePath.Val, isysroot.Val))(IsDistinct ? DIModule::getDistinct (Context, scope.Val, name
.Val, configMacros.Val, includePath.Val, isysroot.Val) : DIModule
::get (Context, scope.Val, name.Val, configMacros.Val, includePath
.Val, isysroot.Val))
;
4800 return false;
4801}
4802
4803/// ParseDITemplateTypeParameter:
4804/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4805bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4806#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4807 OPTIONAL(name, MDStringField, ); \
4808 REQUIRED(type, MDField, );
4809 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4810#undef VISIT_MD_FIELDS
4811
4812 Result =
4813 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val))(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val) : DITemplateTypeParameter::get (Context, name
.Val, type.Val))
;
4814 return false;
4815}
4816
4817/// ParseDITemplateValueParameter:
4818/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4819/// name: "V", type: !1, value: i32 7)
4820bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4821#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4822 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4823 OPTIONAL(name, MDStringField, ); \
4824 OPTIONAL(type, MDField, ); \
4825 REQUIRED(value, MDField, );
4826 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4827#undef VISIT_MD_FIELDS
4828
4829 Result = GET_OR_DISTINCT(DITemplateValueParameter,(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, value.Val))
4830 (Context, tag.Val, name.Val, type.Val, value.Val))(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, value.Val))
;
4831 return false;
4832}
4833
4834/// ParseDIGlobalVariable:
4835/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4836/// file: !1, line: 7, type: !2, isLocal: false,
4837/// isDefinition: true, templateParams: !3,
4838/// declaration: !4, align: 8)
4839bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4840#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4841 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4842 OPTIONAL(scope, MDField, ); \
4843 OPTIONAL(linkageName, MDStringField, ); \
4844 OPTIONAL(file, MDField, ); \
4845 OPTIONAL(line, LineField, ); \
4846 OPTIONAL(type, MDField, ); \
4847 OPTIONAL(isLocal, MDBoolField, ); \
4848 OPTIONAL(isDefinition, MDBoolField, (true)); \
4849 OPTIONAL(templateParams, MDField, ); \
4850 OPTIONAL(declaration, MDField, ); \
4851 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4852 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4853#undef VISIT_MD_FIELDS
4854
4855 Result =
4856 GET_OR_DISTINCT(DIGlobalVariable,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4857 (Context, scope.Val, name.Val, linkageName.Val, file.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4858 line.Val, type.Val, isLocal.Val, isDefinition.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4859 declaration.Val, templateParams.Val, align.Val))(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
;
4860 return false;
4861}
4862
4863/// ParseDILocalVariable:
4864/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4865/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4866/// align: 8)
4867/// ::= !DILocalVariable(scope: !0, name: "foo",
4868/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4869/// align: 8)
4870bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4871#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4872 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4873 OPTIONAL(name, MDStringField, ); \
4874 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX(65535))); \
4875 OPTIONAL(file, MDField, ); \
4876 OPTIONAL(line, LineField, ); \
4877 OPTIONAL(type, MDField, ); \
4878 OPTIONAL(flags, DIFlagField, ); \
4879 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4880 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4881#undef VISIT_MD_FIELDS
4882
4883 Result = GET_OR_DISTINCT(DILocalVariable,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
4884 (Context, scope.Val, name.Val, file.Val, line.Val,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
4885 type.Val, arg.Val, flags.Val, align.Val))(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
;
4886 return false;
4887}
4888
4889/// ParseDILabel:
4890/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4891bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4892#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4893 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4894 REQUIRED(name, MDStringField, ); \
4895 REQUIRED(file, MDField, ); \
4896 REQUIRED(line, LineField, );
4897 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4898#undef VISIT_MD_FIELDS
4899
4900 Result = GET_OR_DISTINCT(DILabel,(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
4901 (Context, scope.Val, name.Val, file.Val, line.Val))(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
;
4902 return false;
4903}
4904
4905/// ParseDIExpression:
4906/// ::= !DIExpression(0, 7, -1)
4907bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4908 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 4908, __PRETTY_FUNCTION__))
;
4909 Lex.Lex();
4910
4911 if (ParseToken(lltok::lparen, "expected '(' here"))
4912 return true;
4913
4914 SmallVector<uint64_t, 8> Elements;
4915 if (Lex.getKind() != lltok::rparen)
4916 do {
4917 if (Lex.getKind() == lltok::DwarfOp) {
4918 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4919 Lex.Lex();
4920 Elements.push_back(Op);
4921 continue;
4922 }
4923 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4924 }
4925
4926 if (Lex.getKind() == lltok::DwarfAttEncoding) {
4927 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4928 Lex.Lex();
4929 Elements.push_back(Op);
4930 continue;
4931 }
4932 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4933 }
4934
4935 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4936 return TokError("expected unsigned integer");
4937
4938 auto &U = Lex.getAPSIntVal();
4939 if (U.ugt(UINT64_MAX(18446744073709551615UL)))
4940 return TokError("element too large, limit is " + Twine(UINT64_MAX(18446744073709551615UL)));
4941 Elements.push_back(U.getZExtValue());
4942 Lex.Lex();
4943 } while (EatIfPresent(lltok::comma));
4944
4945 if (ParseToken(lltok::rparen, "expected ')' here"))
4946 return true;
4947
4948 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements))(IsDistinct ? DIExpression::getDistinct (Context, Elements) :
DIExpression::get (Context, Elements))
;
4949 return false;
4950}
4951
4952/// ParseDIGlobalVariableExpression:
4953/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4954bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4955 bool IsDistinct) {
4956#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4957 REQUIRED(var, MDField, ); \
4958 REQUIRED(expr, MDField, );
4959 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4960#undef VISIT_MD_FIELDS
4961
4962 Result =
4963 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val))(IsDistinct ? DIGlobalVariableExpression::getDistinct (Context
, var.Val, expr.Val) : DIGlobalVariableExpression::get (Context
, var.Val, expr.Val))
;
4964 return false;
4965}
4966
4967/// ParseDIObjCProperty:
4968/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4969/// getter: "getFoo", attributes: 7, type: !2)
4970bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4971#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4972 OPTIONAL(name, MDStringField, ); \
4973 OPTIONAL(file, MDField, ); \
4974 OPTIONAL(line, LineField, ); \
4975 OPTIONAL(setter, MDStringField, ); \
4976 OPTIONAL(getter, MDStringField, ); \
4977 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4978 OPTIONAL(type, MDField, );
4979 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4980#undef VISIT_MD_FIELDS
4981
4982 Result = GET_OR_DISTINCT(DIObjCProperty,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
4983 (Context, name.Val, file.Val, line.Val, setter.Val,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
4984 getter.Val, attributes.Val, type.Val))(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
;
4985 return false;
4986}
4987
4988/// ParseDIImportedEntity:
4989/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4990/// line: 7, name: "foo")
4991bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4992#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4993 REQUIRED(tag, DwarfTagField, ); \
4994 REQUIRED(scope, MDField, ); \
4995 OPTIONAL(entity, MDField, ); \
4996 OPTIONAL(file, MDField, ); \
4997 OPTIONAL(line, LineField, ); \
4998 OPTIONAL(name, MDStringField, );
4999 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5000#undef VISIT_MD_FIELDS
5001
5002 Result = GET_OR_DISTINCT((IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5003 DIImportedEntity,(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5004 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val))(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
;
5005 return false;
5006}
5007
5008#undef PARSE_MD_FIELD
5009#undef NOP_FIELD
5010#undef REQUIRE_FIELD
5011#undef DECLARE_FIELD
5012
5013/// ParseMetadataAsValue
5014/// ::= metadata i32 %local
5015/// ::= metadata i32 @global
5016/// ::= metadata i32 7
5017/// ::= metadata !0
5018/// ::= metadata !{...}
5019/// ::= metadata !"string"
5020bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5021 // Note: the type 'metadata' has already been parsed.
5022 Metadata *MD;
5023 if (ParseMetadata(MD, &PFS))
5024 return true;
5025
5026 V = MetadataAsValue::get(Context, MD);
5027 return false;
5028}
5029
5030/// ParseValueAsMetadata
5031/// ::= i32 %local
5032/// ::= i32 @global
5033/// ::= i32 7
5034bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5035 PerFunctionState *PFS) {
5036 Type *Ty;
5037 LocTy Loc;
5038 if (ParseType(Ty, TypeMsg, Loc))
5039 return true;
5040 if (Ty->isMetadataTy())
5041 return Error(Loc, "invalid metadata-value-metadata roundtrip");
5042
5043 Value *V;
5044 if (ParseValue(Ty, V, PFS))
5045 return true;
5046
5047 MD = ValueAsMetadata::get(V);
5048 return false;
5049}
5050
5051/// ParseMetadata
5052/// ::= i32 %local
5053/// ::= i32 @global
5054/// ::= i32 7
5055/// ::= !42
5056/// ::= !{...}
5057/// ::= !"string"
5058/// ::= !DILocation(...)
5059bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5060 if (Lex.getKind() == lltok::MetadataVar) {
5061 MDNode *N;
5062 if (ParseSpecializedMDNode(N))
5063 return true;
5064 MD = N;
5065 return false;
5066 }
5067
5068 // ValueAsMetadata:
5069 // <type> <value>
5070 if (Lex.getKind() != lltok::exclaim)
5071 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
5072
5073 // '!'.
5074 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here")((Lex.getKind() == lltok::exclaim && "Expected '!' here"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::exclaim && \"Expected '!' here\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5074, __PRETTY_FUNCTION__))
;
5075 Lex.Lex();
5076
5077 // MDString:
5078 // ::= '!' STRINGCONSTANT
5079 if (Lex.getKind() == lltok::StringConstant) {
5080 MDString *S;
5081 if (ParseMDString(S))
5082 return true;
5083 MD = S;
5084 return false;
5085 }
5086
5087 // MDNode:
5088 // !{ ... }
5089 // !7
5090 MDNode *N;
5091 if (ParseMDNodeTail(N))
5092 return true;
5093 MD = N;
5094 return false;
5095}
5096
5097//===----------------------------------------------------------------------===//
5098// Function Parsing.
5099//===----------------------------------------------------------------------===//
5100
5101bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5102 PerFunctionState *PFS, bool IsCall) {
5103 if (Ty->isFunctionTy())
5104 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5105
5106 switch (ID.Kind) {
5107 case ValID::t_LocalID:
5108 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5109 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5110 return V == nullptr;
5111 case ValID::t_LocalName:
5112 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5113 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5114 return V == nullptr;
5115 case ValID::t_InlineAsm: {
5116 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5117 return Error(ID.Loc, "invalid type for inline asm constraint string");
5118 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5119 (ID.UIntVal >> 1) & 1,
5120 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5121 return false;
5122 }
5123 case ValID::t_GlobalName:
5124 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5125 return V == nullptr;
5126 case ValID::t_GlobalID:
5127 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5128 return V == nullptr;
5129 case ValID::t_APSInt:
5130 if (!Ty->isIntegerTy())
5131 return Error(ID.Loc, "integer constant must have integer type");
5132 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5133 V = ConstantInt::get(Context, ID.APSIntVal);
5134 return false;
5135 case ValID::t_APFloat:
5136 if (!Ty->isFloatingPointTy() ||
5137 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5138 return Error(ID.Loc, "floating point constant invalid for type");
5139
5140 // The lexer has no type info, so builds all half, float, and double FP
5141 // constants as double. Fix this here. Long double does not need this.
5142 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5143 bool Ignored;
5144 if (Ty->isHalfTy())
5145 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5146 &Ignored);
5147 else if (Ty->isFloatTy())
5148 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5149 &Ignored);
5150 }
5151 V = ConstantFP::get(Context, ID.APFloatVal);
5152
5153 if (V->getType() != Ty)
5154 return Error(ID.Loc, "floating point constant does not have type '" +
5155 getTypeString(Ty) + "'");
5156
5157 return false;
5158 case ValID::t_Null:
5159 if (!Ty->isPointerTy())
5160 return Error(ID.Loc, "null must be a pointer type");
5161 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5162 return false;
5163 case ValID::t_Undef:
5164 // FIXME: LabelTy should not be a first-class type.
5165 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5166 return Error(ID.Loc, "invalid type for undef constant");
5167 V = UndefValue::get(Ty);
5168 return false;
5169 case ValID::t_EmptyArray:
5170 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5171 return Error(ID.Loc, "invalid empty array initializer");
5172 V = UndefValue::get(Ty);
5173 return false;
5174 case ValID::t_Zero:
5175 // FIXME: LabelTy should not be a first-class type.
5176 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5177 return Error(ID.Loc, "invalid type for null constant");
5178 V = Constant::getNullValue(Ty);
5179 return false;
5180 case ValID::t_None:
5181 if (!Ty->isTokenTy())
5182 return Error(ID.Loc, "invalid type for none constant");
5183 V = Constant::getNullValue(Ty);
5184 return false;
5185 case ValID::t_Constant:
5186 if (ID.ConstantVal->getType() != Ty)
5187 return Error(ID.Loc, "constant expression type mismatch");
5188
5189 V = ID.ConstantVal;
5190 return false;
5191 case ValID::t_ConstantStruct:
5192 case ValID::t_PackedConstantStruct:
5193 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5194 if (ST->getNumElements() != ID.UIntVal)
5195 return Error(ID.Loc,
5196 "initializer with struct type has wrong # elements");
5197 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5198 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5199
5200 // Verify that the elements are compatible with the structtype.
5201 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5202 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5203 return Error(ID.Loc, "element " + Twine(i) +
5204 " of struct initializer doesn't match struct element type");
5205
5206 V = ConstantStruct::get(
5207 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5208 } else
5209 return Error(ID.Loc, "constant expression type mismatch");
5210 return false;
5211 }
5212 llvm_unreachable("Invalid ValID")::llvm::llvm_unreachable_internal("Invalid ValID", "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5212)
;
5213}
5214
5215bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5216 C = nullptr;
5217 ValID ID;
5218 auto Loc = Lex.getLoc();
5219 if (ParseValID(ID, /*PFS=*/nullptr))
5220 return true;
5221 switch (ID.Kind) {
5222 case ValID::t_APSInt:
5223 case ValID::t_APFloat:
5224 case ValID::t_Undef:
5225 case ValID::t_Constant:
5226 case ValID::t_ConstantStruct:
5227 case ValID::t_PackedConstantStruct: {
5228 Value *V;
5229 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5230 return true;
5231 assert(isa<Constant>(V) && "Expected a constant value")((isa<Constant>(V) && "Expected a constant value"
) ? static_cast<void> (0) : __assert_fail ("isa<Constant>(V) && \"Expected a constant value\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5231, __PRETTY_FUNCTION__))
;
5232 C = cast<Constant>(V);
5233 return false;
5234 }
5235 case ValID::t_Null:
5236 C = Constant::getNullValue(Ty);
5237 return false;
5238 default:
5239 return Error(Loc, "expected a constant value");
5240 }
5241}
5242
5243bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5244 V = nullptr;
5245 ValID ID;
5246 return ParseValID(ID, PFS) ||
5247 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5248}
5249
5250bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5251 Type *Ty = nullptr;
5252 return ParseType(Ty) ||
5253 ParseValue(Ty, V, PFS);
5254}
5255
5256bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5257 PerFunctionState &PFS) {
5258 Value *V;
5259 Loc = Lex.getLoc();
5260 if (ParseTypeAndValue(V, PFS)) return true;
5261 if (!isa<BasicBlock>(V))
5262 return Error(Loc, "expected a basic block");
5263 BB = cast<BasicBlock>(V);
5264 return false;
5265}
5266
5267/// FunctionHeader
5268/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5269/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5270/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5271/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5272bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5273 // Parse the linkage.
5274 LocTy LinkageLoc = Lex.getLoc();
5275 unsigned Linkage;
5276 unsigned Visibility;
5277 unsigned DLLStorageClass;
5278 bool DSOLocal;
5279 AttrBuilder RetAttrs;
5280 unsigned CC;
5281 bool HasLinkage;
5282 Type *RetType = nullptr;
5283 LocTy RetTypeLoc = Lex.getLoc();
5284 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5285 DSOLocal) ||
5286 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5287 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5288 return true;
5289
5290 // Verify that the linkage is ok.
5291 switch ((GlobalValue::LinkageTypes)Linkage) {
5292 case GlobalValue::ExternalLinkage:
5293 break; // always ok.
5294 case GlobalValue::ExternalWeakLinkage:
5295 if (isDefine)
5296 return Error(LinkageLoc, "invalid linkage for function definition");
5297 break;
5298 case GlobalValue::PrivateLinkage:
5299 case GlobalValue::InternalLinkage:
5300 case GlobalValue::AvailableExternallyLinkage:
5301 case GlobalValue::LinkOnceAnyLinkage:
5302 case GlobalValue::LinkOnceODRLinkage:
5303 case GlobalValue::WeakAnyLinkage:
5304 case GlobalValue::WeakODRLinkage:
5305 if (!isDefine)
5306 return Error(LinkageLoc, "invalid linkage for function declaration");
5307 break;
5308 case GlobalValue::AppendingLinkage:
5309 case GlobalValue::CommonLinkage:
5310 return Error(LinkageLoc, "invalid function linkage type");
5311 }
5312
5313 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5314 return Error(LinkageLoc,
5315 "symbol with local linkage must have default visibility");
5316
5317 if (!FunctionType::isValidReturnType(RetType))
5318 return Error(RetTypeLoc, "invalid function return type");
5319
5320 LocTy NameLoc = Lex.getLoc();
5321
5322 std::string FunctionName;
5323 if (Lex.getKind() == lltok::GlobalVar) {
5324 FunctionName = Lex.getStrVal();
5325 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5326 unsigned NameID = Lex.getUIntVal();
5327
5328 if (NameID != NumberedVals.size())
5329 return TokError("function expected to be numbered '%" +
5330 Twine(NumberedVals.size()) + "'");
5331 } else {
5332 return TokError("expected function name");
5333 }
5334
5335 Lex.Lex();
5336
5337 if (Lex.getKind() != lltok::lparen)
5338 return TokError("expected '(' in function argument list");
5339
5340 SmallVector<ArgInfo, 8> ArgList;
5341 bool isVarArg;
5342 AttrBuilder FuncAttrs;
5343 std::vector<unsigned> FwdRefAttrGrps;
5344 LocTy BuiltinLoc;
5345 std::string Section;
5346 std::string Partition;
5347 unsigned Alignment;
5348 std::string GC;
5349 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5350 unsigned AddrSpace = 0;
5351 Constant *Prefix = nullptr;
5352 Constant *Prologue = nullptr;
5353 Constant *PersonalityFn = nullptr;
5354 Comdat *C;
5355
5356 if (ParseArgumentList(ArgList, isVarArg) ||
5357 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5358 ParseOptionalProgramAddrSpace(AddrSpace) ||
5359 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5360 BuiltinLoc) ||
5361 (EatIfPresent(lltok::kw_section) &&
5362 ParseStringConstant(Section)) ||
5363 (EatIfPresent(lltok::kw_partition) &&
5364 ParseStringConstant(Partition)) ||
5365 parseOptionalComdat(FunctionName, C) ||
5366 ParseOptionalAlignment(Alignment) ||
5367 (EatIfPresent(lltok::kw_gc) &&
5368 ParseStringConstant(GC)) ||
5369 (EatIfPresent(lltok::kw_prefix) &&
5370 ParseGlobalTypeAndValue(Prefix)) ||
5371 (EatIfPresent(lltok::kw_prologue) &&
5372 ParseGlobalTypeAndValue(Prologue)) ||
5373 (EatIfPresent(lltok::kw_personality) &&
5374 ParseGlobalTypeAndValue(PersonalityFn)))
5375 return true;
5376
5377 if (FuncAttrs.contains(Attribute::Builtin))
5378 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5379
5380 // If the alignment was parsed as an attribute, move to the alignment field.
5381 if (FuncAttrs.hasAlignmentAttr()) {
5382 Alignment = FuncAttrs.getAlignment();
5383 FuncAttrs.removeAttribute(Attribute::Alignment);
5384 }
5385
5386 // Okay, if we got here, the function is syntactically valid. Convert types
5387 // and do semantic checks.
5388 std::vector<Type*> ParamTypeList;
5389 SmallVector<AttributeSet, 8> Attrs;
5390
5391 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5392 ParamTypeList.push_back(ArgList[i].Ty);
5393 Attrs.push_back(ArgList[i].Attrs);
5394 }
5395
5396 AttributeList PAL =
5397 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5398 AttributeSet::get(Context, RetAttrs), Attrs);
5399
5400 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5401 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5402
5403 FunctionType *FT =
5404 FunctionType::get(RetType, ParamTypeList, isVarArg);
5405 PointerType *PFT = PointerType::get(FT, AddrSpace);
5406
5407 Fn = nullptr;
5408 if (!FunctionName.empty()) {
5409 // If this was a definition of a forward reference, remove the definition
5410 // from the forward reference table and fill in the forward ref.
5411 auto FRVI = ForwardRefVals.find(FunctionName);
5412 if (FRVI != ForwardRefVals.end()) {
5413 Fn = M->getFunction(FunctionName);
5414 if (!Fn)
5415 return Error(FRVI->second.second, "invalid forward reference to "
5416 "function as global value!");
5417 if (Fn->getType() != PFT)
5418 return Error(FRVI->second.second, "invalid forward reference to "
5419 "function '" + FunctionName + "' with wrong type: "
5420 "expected '" + getTypeString(PFT) + "' but was '" +
5421 getTypeString(Fn->getType()) + "'");
5422 ForwardRefVals.erase(FRVI);
5423 } else if ((Fn = M->getFunction(FunctionName))) {
5424 // Reject redefinitions.
5425 return Error(NameLoc, "invalid redefinition of function '" +
5426 FunctionName + "'");
5427 } else if (M->getNamedValue(FunctionName)) {
5428 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5429 }
5430
5431 } else {
5432 // If this is a definition of a forward referenced function, make sure the
5433 // types agree.
5434 auto I = ForwardRefValIDs.find(NumberedVals.size());
5435 if (I != ForwardRefValIDs.end()) {
5436 Fn = cast<Function>(I->second.first);
5437 if (Fn->getType() != PFT)
5438 return Error(NameLoc, "type of definition and forward reference of '@" +
5439 Twine(NumberedVals.size()) + "' disagree: "
5440 "expected '" + getTypeString(PFT) + "' but was '" +
5441 getTypeString(Fn->getType()) + "'");
5442 ForwardRefValIDs.erase(I);
5443 }
5444 }
5445
5446 if (!Fn)
5447 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5448 FunctionName, M);
5449 else // Move the forward-reference to the correct spot in the module.
5450 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5451
5452 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS")((Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"
) ? static_cast<void> (0) : __assert_fail ("Fn->getAddressSpace() == AddrSpace && \"Created function in wrong AS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5452, __PRETTY_FUNCTION__))
;
5453
5454 if (FunctionName.empty())
5455 NumberedVals.push_back(Fn);
5456
5457 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5458 maybeSetDSOLocal(DSOLocal, *Fn);
5459 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5460 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5461 Fn->setCallingConv(CC);
5462 Fn->setAttributes(PAL);
5463 Fn->setUnnamedAddr(UnnamedAddr);
5464 Fn->setAlignment(Alignment);
5465 Fn->setSection(Section);
5466 Fn->setPartition(Partition);
5467 Fn->setComdat(C);
5468 Fn->setPersonalityFn(PersonalityFn);
5469 if (!GC.empty()) Fn->setGC(GC);
5470 Fn->setPrefixData(Prefix);
5471 Fn->setPrologueData(Prologue);
5472 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5473
5474 // Add all of the arguments we parsed to the function.
5475 Function::arg_iterator ArgIt = Fn->arg_begin();
5476 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5477 // If the argument has a name, insert it into the argument symbol table.
5478 if (ArgList[i].Name.empty()) continue;
5479
5480 // Set the name, if it conflicted, it will be auto-renamed.
5481 ArgIt->setName(ArgList[i].Name);
5482
5483 if (ArgIt->getName() != ArgList[i].Name)
5484 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5485 ArgList[i].Name + "'");
5486 }
5487
5488 if (isDefine)
5489 return false;
5490
5491 // Check the declaration has no block address forward references.
5492 ValID ID;
5493 if (FunctionName.empty()) {
5494 ID.Kind = ValID::t_GlobalID;
5495 ID.UIntVal = NumberedVals.size() - 1;
5496 } else {
5497 ID.Kind = ValID::t_GlobalName;
5498 ID.StrVal = FunctionName;
5499 }
5500 auto Blocks = ForwardRefBlockAddresses.find(ID);
5501 if (Blocks != ForwardRefBlockAddresses.end())
5502 return Error(Blocks->first.Loc,
5503 "cannot take blockaddress inside a declaration");
5504 return false;
5505}
5506
5507bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5508 ValID ID;
5509 if (FunctionNumber == -1) {
5510 ID.Kind = ValID::t_GlobalName;
5511 ID.StrVal = F.getName();
5512 } else {
5513 ID.Kind = ValID::t_GlobalID;
5514 ID.UIntVal = FunctionNumber;
5515 }
5516
5517 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5518 if (Blocks == P.ForwardRefBlockAddresses.end())
5519 return false;
5520
5521 for (const auto &I : Blocks->second) {
5522 const ValID &BBID = I.first;
5523 GlobalValue *GV = I.second;
5524
5525 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&(((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName
) && "Expected local id or name") ? static_cast<void
> (0) : __assert_fail ("(BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && \"Expected local id or name\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5526, __PRETTY_FUNCTION__))
5526 "Expected local id or name")(((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName
) && "Expected local id or name") ? static_cast<void
> (0) : __assert_fail ("(BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && \"Expected local id or name\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5526, __PRETTY_FUNCTION__))
;
5527 BasicBlock *BB;
5528 if (BBID.Kind == ValID::t_LocalName)
5529 BB = GetBB(BBID.StrVal, BBID.Loc);
5530 else
5531 BB = GetBB(BBID.UIntVal, BBID.Loc);
5532 if (!BB)
5533 return P.Error(BBID.Loc, "referenced value is not a basic block");
5534
5535 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5536 GV->eraseFromParent();
5537 }
5538
5539 P.ForwardRefBlockAddresses.erase(Blocks);
5540 return false;
5541}
5542
5543/// ParseFunctionBody
5544/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5545bool LLParser::ParseFunctionBody(Function &Fn) {
5546 if (Lex.getKind() != lltok::lbrace)
5547 return TokError("expected '{' in function body");
5548 Lex.Lex(); // eat the {.
5549
5550 int FunctionNumber = -1;
5551 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5552
5553 PerFunctionState PFS(*this, Fn, FunctionNumber);
5554
5555 // Resolve block addresses and allow basic blocks to be forward-declared
5556 // within this function.
5557 if (PFS.resolveForwardRefBlockAddresses())
5558 return true;
5559 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5560
5561 // We need at least one basic block.
5562 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5563 return TokError("function body requires at least one basic block");
5564
5565 while (Lex.getKind() != lltok::rbrace &&
5566 Lex.getKind() != lltok::kw_uselistorder)
5567 if (ParseBasicBlock(PFS)) return true;
5568
5569 while (Lex.getKind() != lltok::rbrace)
5570 if (ParseUseListOrder(&PFS))
5571 return true;
5572
5573 // Eat the }.
5574 Lex.Lex();
5575
5576 // Verify function is ok.
5577 return PFS.FinishFunction();
5578}
5579
5580/// ParseBasicBlock
5581/// ::= (LabelStr|LabelID)? Instruction*
5582bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5583 // If this basic block starts out with a name, remember it.
5584 std::string Name;
5585 int NameID = -1;
5586 LocTy NameLoc = Lex.getLoc();
5587 if (Lex.getKind() == lltok::LabelStr) {
5588 Name = Lex.getStrVal();
5589 Lex.Lex();
5590 } else if (Lex.getKind() == lltok::LabelID) {
5591 NameID = Lex.getUIntVal();
5592 Lex.Lex();
5593 }
5594
5595 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
5596 if (!BB)
5597 return true;
5598
5599 std::string NameStr;
5600
5601 // Parse the instructions in this block until we get a terminator.
5602 Instruction *Inst;
5603 do {
5604 // This instruction may have three possibilities for a name: a) none
5605 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5606 LocTy NameLoc = Lex.getLoc();
5607 int NameID = -1;
5608 NameStr = "";
5609
5610 if (Lex.getKind() == lltok::LocalVarID) {
5611 NameID = Lex.getUIntVal();
5612 Lex.Lex();
5613 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5614 return true;
5615 } else if (Lex.getKind() == lltok::LocalVar) {
5616 NameStr = Lex.getStrVal();
5617 Lex.Lex();
5618 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5619 return true;
5620 }
5621
5622 switch (ParseInstruction(Inst, BB, PFS)) {
5623 default: llvm_unreachable("Unknown ParseInstruction result!")::llvm::llvm_unreachable_internal("Unknown ParseInstruction result!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/AsmParser/LLParser.cpp"
, 5623)
;
5624 case InstError: return true;
5625 case InstNormal:
5626 BB->getInstList().push_back(Inst);
5627
5628 // With a normal result, we check to see if the instruction is followed by
5629 // a comma and metadata.
5630 if (EatIfPresent(lltok::comma))
5631 if (ParseInstructionMetadata(*Inst))
5632 return true;
5633 break;
5634 case InstExtraComma:
5635 BB->getInstList().push_back(Inst);
5636
5637 // If the instruction parser ate an extra comma at the end of it, it
5638 // *must* be followed by metadata.
5639 if (ParseInstructionMetadata(*Inst))
5640 return true;
5641 break;
5642 }
5643
5644 // Set the name on the instruction.
5645 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5646 } while (!Inst->isTerminator());
5647
5648 return false;
5649}
5650
5651//===----------------------------------------------------------------------===//
5652// Instruction Parsing.
5653//===----------------------------------------------------------------------===//
5654
5655/// ParseInstruction - Parse one of the many different instructions.
5656///
5657int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5658 PerFunctionState &PFS) {
5659 lltok::Kind Token = Lex.getKind();
5660 if (Token == lltok::Eof)
5661 return TokError("found end of file when expecting more instructions");
5662 LocTy Loc = Lex.getLoc();
5663 unsigned KeywordVal = Lex.getUIntVal();
5664 Lex.Lex(); // Eat the keyword.
5665
5666 switch (Token) {
5667 default: return Error(Loc, "expected instruction opcode");
5668 // Terminator Instructions.
5669 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5670 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5671 case lltok::kw_br: return ParseBr(Inst, PFS);
5672 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5673 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5674 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5675 case lltok::kw_resume: return ParseResume(Inst, PFS);
5676 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5677 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5678 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5679 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5680 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5681 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5682 // Unary Operators.
5683 case lltok::kw_fneg: {
5684 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5685 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
5686 if (Res != 0)
5687 return Res;
5688 if (FMF.any())
5689 Inst->setFastMathFlags(FMF);
5690 return false;
5691 }
5692 // Binary Operators.
5693 case lltok::kw_add:
5694 case lltok::kw_sub:
5695 case lltok::kw_mul:
5696 case lltok::kw_shl: {
5697 bool NUW = EatIfPresent(lltok::kw_nuw);
5698 bool NSW = EatIfPresent(lltok::kw_nsw);
5699 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5700
5701 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5702
5703 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5704 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5705 return false;
5706 }
5707 case lltok::kw_fadd:
5708 case lltok::kw_fsub:
5709 case lltok::kw_fmul:
5710 case lltok::kw_fdiv:
5711 case lltok::kw_frem: {
5712 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5713 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
5714 if (Res != 0)
5715 return Res;
5716 if (FMF.any())
5717 Inst->setFastMathFlags(FMF);
5718 return 0;
5719 }
5720
5721 case lltok::kw_sdiv:
5722 case lltok::kw_udiv:
5723 case lltok::kw_lshr:
5724 case lltok::kw_ashr: {
5725 bool Exact = EatIfPresent(lltok::kw_exact);
5726
5727 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5728 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5729 return false;
5730 }
5731
5732 case lltok::kw_urem:
5733 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5734 /*IsFP*/false);
5735 case lltok::kw_and:
5736 case lltok::kw_or:
5737 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5738 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5739 case lltok::kw_fcmp: {
5740 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5741 int Res = ParseCompare(Inst, PFS, KeywordVal);
5742 if (Res != 0)
5743 return Res;
5744 if (FMF.any())
5745 Inst->setFastMathFlags(FMF);
5746 return 0;
5747 }
5748
5749 // Casts.
5750 case lltok::kw_trunc:
5751 case lltok::kw_zext:
5752 case lltok::kw_sext:
5753 case lltok::kw_fptrunc:
5754 case lltok::kw_fpext:
5755 case lltok::kw_bitcast:
5756 case lltok::kw_addrspacecast:
5757 case lltok::kw_uitofp:
5758 case lltok::kw_sitofp:
5759 case lltok::kw_fptoui:
5760 case lltok::kw_fptosi:
5761 case lltok::kw_inttoptr:
5762 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5763 // Other.
5764 case lltok::kw_select: {
5765 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5766 int Res = ParseSelect(Inst, PFS);
5767 if (Res != 0)
5768 return Res;
5769 if (FMF.any()) {
5770 if (!Inst->getType()->isFPOrFPVectorTy())
5771 return Error(Loc, "fast-math-flags specified for select without "
5772 "floating-point scalar or vector return type");
5773 Inst->setFastMathFlags(FMF);
5774 }
5775 return 0;
5776 }
5777 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5778 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5779 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5780 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5781 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5782 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5783 // Call.
5784 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5785 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5786 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5787 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5788 // Memory.
5789 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5790 case lltok::kw_load: return ParseLoad(Inst, PFS);
5791 case lltok::kw_store: return ParseStore(Inst, PFS);
5792 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5793 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5794 case lltok::kw_fence: return ParseFence(Inst, PFS);