Bug Summary

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

Annotated Source Code

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