Bug Summary

File:lib/AsmParser/LLParser.cpp
Warning:line 2338, column 11
Called C++ object pointer is null

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~svn358860/build-llvm/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn358860/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358860/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~svn358860/build-llvm/lib/AsmParser -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358860=. -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-04-22-050718-5320-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358860/lib/AsmParser/LLParser.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn358860/lib/AsmParser/LLParser.cpp

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