1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/AsmParser/LLParser.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/LLToken.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/ConstantRange.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugInfoMetadata.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalIFunc.h"
33#include "llvm/IR/GlobalObject.h"
34#include "llvm/IR/InlineAsm.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/ValueSymbolTable.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/SaveAndRestore.h"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstring>
49#include <iterator>
50#include <vector>
51
52using namespace llvm;
53
54static std::string getTypeString(Type *T) {
55 std::string Result;
56 raw_string_ostream Tmp(Result);
57 Tmp << *T;
58 return Tmp.str();
59}
60
61/// Run: module ::= toplevelentity*
62bool LLParser::Run(bool UpgradeDebugInfo,
63 DataLayoutCallbackTy DataLayoutCallback) {
64 // Prime the lexer.
65 Lex.Lex();
66
67 if (Context.shouldDiscardValueNames())
68 return error(
69 Lex.getLoc(),
70 "Can't read textual IR with a Context that discards named Values");
71
72 if (M) {
73 if (parseTargetDefinitions())
74 return true;
75
76 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
77 M->setDataLayout(*LayoutOverride);
78 }
79
80 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
81 validateEndOfIndex();
82}
83
84bool LLParser::parseStandaloneConstantValue(Constant *&C,
85 const SlotMapping *Slots) {
86 restoreParsingState(Slots);
87 Lex.Lex();
88
89 Type *Ty = nullptr;
90 if (parseType(Ty) || parseConstantValue(Ty, C))
91 return true;
92 if (Lex.getKind() != lltok::Eof)
93 return error(Lex.getLoc(), "expected end of string");
94 return false;
95}
96
97bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98 const SlotMapping *Slots) {
99 restoreParsingState(Slots);
100 Lex.Lex();
101
102 Read = 0;
103 SMLoc Start = Lex.getLoc();
104 Ty = nullptr;
105 if (parseType(Ty))
106 return true;
107 SMLoc End = Lex.getLoc();
108 Read = End.getPointer() - Start.getPointer();
109
110 return false;
111}
112
113void LLParser::restoreParsingState(const SlotMapping *Slots) {
114 if (!Slots)
115 return;
116 NumberedVals = Slots->GlobalValues;
117 NumberedMetadata = Slots->MetadataNodes;
118 for (const auto &I : Slots->NamedTypes)
119 NamedTypes.insert(
120 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121 for (const auto &I : Slots->Types)
122 NumberedTypes.insert(
123 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
124}
125
126/// validateEndOfModule - Do final validity and sanity checks at the end of the
127/// module.
128bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
129 if (!M)
130 return false;
131 // Handle any function attribute group forward references.
132 for (const auto &RAG : ForwardRefAttrGroups) {
133 Value *V = RAG.first;
134 const std::vector<unsigned> &Attrs = RAG.second;
135 AttrBuilder B;
136
137 for (const auto &Attr : Attrs)
138 B.merge(NumberedAttrBuilders[Attr]);
139
140 if (Function *Fn = dyn_cast<Function>(V)) {
141 AttributeList AS = Fn->getAttributes();
142 AttrBuilder FnAttrs(AS.getFnAttributes());
143 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
144
145 FnAttrs.merge(B);
146
147 // If the alignment was parsed as an attribute, move to the alignment
148 // field.
149 if (FnAttrs.hasAlignmentAttr()) {
150 Fn->setAlignment(FnAttrs.getAlignment());
151 FnAttrs.removeAttribute(Attribute::Alignment);
152 }
153
154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
156 Fn->setAttributes(AS);
157 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
158 AttributeList AS = CI->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 CI->setAttributes(AS);
165 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
166 AttributeList AS = II->getAttributes();
167 AttrBuilder FnAttrs(AS.getFnAttributes());
168 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
169 FnAttrs.merge(B);
170 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
171 AttributeSet::get(Context, FnAttrs));
172 II->setAttributes(AS);
173 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174 AttributeList AS = CBI->getAttributes();
175 AttrBuilder FnAttrs(AS.getFnAttributes());
176 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
177 FnAttrs.merge(B);
178 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
179 AttributeSet::get(Context, FnAttrs));
180 CBI->setAttributes(AS);
181 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
182 AttrBuilder Attrs(GV->getAttributes());
183 Attrs.merge(B);
184 GV->setAttributes(AttributeSet::get(Context,Attrs));
185 } else {
186 llvm_unreachable("invalid object with forward attribute group reference");
187 }
188 }
189
190 // If there are entries in ForwardRefBlockAddresses at this point, the
191 // function was never defined.
192 if (!ForwardRefBlockAddresses.empty())
193 return error(ForwardRefBlockAddresses.begin()->first.Loc,
194 "expected function name in blockaddress");
195
196 for (const auto &NT : NumberedTypes)
197 if (NT.second.second.isValid())
198 return error(NT.second.second,
199 "use of undefined type '%" + Twine(NT.first) + "'");
200
201 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
202 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
203 if (I->second.second.isValid())
204 return error(I->second.second,
205 "use of undefined type named '" + I->getKey() + "'");
206
207 if (!ForwardRefComdats.empty())
208 return error(ForwardRefComdats.begin()->second,
209 "use of undefined comdat '$" +
210 ForwardRefComdats.begin()->first + "'");
211
212 if (!ForwardRefVals.empty())
213 return error(ForwardRefVals.begin()->second.second,
214 "use of undefined value '@" + ForwardRefVals.begin()->first +
215 "'");
216
217 if (!ForwardRefValIDs.empty())
218 return error(ForwardRefValIDs.begin()->second.second,
219 "use of undefined value '@" +
220 Twine(ForwardRefValIDs.begin()->first) + "'");
221
222 if (!ForwardRefMDNodes.empty())
223 return error(ForwardRefMDNodes.begin()->second.second,
224 "use of undefined metadata '!" +
225 Twine(ForwardRefMDNodes.begin()->first) + "'");
226
227 // Resolve metadata cycles.
228 for (auto &N : NumberedMetadata) {
229 if (N.second && !N.second->isResolved())
230 N.second->resolveCycles();
231 }
232
233 for (auto *Inst : InstsWithTBAATag) {
234 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
235 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
236 auto *UpgradedMD = UpgradeTBAANode(*MD);
237 if (MD != UpgradedMD)
238 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
239 }
240
241 // Look for intrinsic functions and CallInst that need to be upgraded
242 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
243 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
244
245 // Some types could be renamed during loading if several modules are
246 // loaded in the same LLVMContext (LTO scenario). In this case we should
247 // remangle intrinsics names as well.
248 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
249 Function *F = &*FI++;
250 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
251 F->replaceAllUsesWith(Remangled.getValue());
252 F->eraseFromParent();
253 }
254 }
255
256 if (UpgradeDebugInfo)
257 llvm::UpgradeDebugInfo(*M);
258
259 UpgradeModuleFlags(*M);
260 UpgradeSectionAttributes(*M);
261
262 if (!Slots)
263 return false;
264 // Initialize the slot mapping.
265 // Because by this point we've parsed and validated everything, we can "steal"
266 // the mapping from LLParser as it doesn't need it anymore.
267 Slots->GlobalValues = std::move(NumberedVals);
268 Slots->MetadataNodes = std::move(NumberedMetadata);
269 for (const auto &I : NamedTypes)
270 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
271 for (const auto &I : NumberedTypes)
272 Slots->Types.insert(std::make_pair(I.first, I.second.first));
273
274 return false;
275}
276
277/// Do final validity and sanity checks at the end of the index.
278bool LLParser::validateEndOfIndex() {
279 if (!Index)
280 return false;
281
282 if (!ForwardRefValueInfos.empty())
283 return error(ForwardRefValueInfos.begin()->second.front().second,
284 "use of undefined summary '^" +
285 Twine(ForwardRefValueInfos.begin()->first) + "'");
286
287 if (!ForwardRefAliasees.empty())
288 return error(ForwardRefAliasees.begin()->second.front().second,
289 "use of undefined summary '^" +
290 Twine(ForwardRefAliasees.begin()->first) + "'");
291
292 if (!ForwardRefTypeIds.empty())
293 return error(ForwardRefTypeIds.begin()->second.front().second,
294 "use of undefined type id summary '^" +
295 Twine(ForwardRefTypeIds.begin()->first) + "'");
296
297 return false;
298}
299
300//===----------------------------------------------------------------------===//
301// Top-Level Entities
302//===----------------------------------------------------------------------===//
303
304bool LLParser::parseTargetDefinitions() {
305 while (true) {
306 switch (Lex.getKind()) {
307 case lltok::kw_target:
308 if (parseTargetDefinition())
309 return true;
310 break;
311 case lltok::kw_source_filename:
312 if (parseSourceFileName())
313 return true;
314 break;
315 default:
316 return false;
317 }
318 }
319}
320
321bool LLParser::parseTopLevelEntities() {
322 // If there is no Module, then parse just the summary index entries.
323 if (!M) {
324 while (true) {
325 switch (Lex.getKind()) {
326 case lltok::Eof:
327 return false;
328 case lltok::SummaryID:
329 if (parseSummaryEntry())
330 return true;
331 break;
332 case lltok::kw_source_filename:
333 if (parseSourceFileName())
334 return true;
335 break;
336 default:
337 // Skip everything else
338 Lex.Lex();
339 }
340 }
341 }
342 while (true) {
343 switch (Lex.getKind()) {
344 default:
345 return tokError("expected top-level entity");
346 case lltok::Eof: return false;
347 case lltok::kw_declare:
348 if (parseDeclare())
349 return true;
350 break;
351 case lltok::kw_define:
352 if (parseDefine())
353 return true;
354 break;
355 case lltok::kw_module:
356 if (parseModuleAsm())
357 return true;
358 break;
359 case lltok::kw_deplibs:
360 if (parseDepLibs())
361 return true;
362 break;
363 case lltok::LocalVarID:
364 if (parseUnnamedType())
365 return true;
366 break;
367 case lltok::LocalVar:
368 if (parseNamedType())
369 return true;
370 break;
371 case lltok::GlobalID:
372 if (parseUnnamedGlobal())
373 return true;
374 break;
375 case lltok::GlobalVar:
376 if (parseNamedGlobal())
377 return true;
378 break;
379 case lltok::ComdatVar: if (parseComdat()) return true; break;
380 case lltok::exclaim:
381 if (parseStandaloneMetadata())
382 return true;
383 break;
384 case lltok::SummaryID:
385 if (parseSummaryEntry())
386 return true;
387 break;
388 case lltok::MetadataVar:
389 if (parseNamedMetadata())
390 return true;
391 break;
392 case lltok::kw_attributes:
393 if (parseUnnamedAttrGrp())
394 return true;
395 break;
396 case lltok::kw_uselistorder:
397 if (parseUseListOrder())
398 return true;
399 break;
400 case lltok::kw_uselistorder_bb:
401 if (parseUseListOrderBB())
402 return true;
403 break;
404 }
405 }
406}
407
408/// toplevelentity
409/// ::= 'module' 'asm' STRINGCONSTANT
410bool LLParser::parseModuleAsm() {
411 assert(Lex.getKind() == lltok::kw_module);
412 Lex.Lex();
413
414 std::string AsmStr;
415 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
416 parseStringConstant(AsmStr))
417 return true;
418
419 M->appendModuleInlineAsm(AsmStr);
420 return false;
421}
422
423/// toplevelentity
424/// ::= 'target' 'triple' '=' STRINGCONSTANT
425/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
426bool LLParser::parseTargetDefinition() {
427 assert(Lex.getKind() == lltok::kw_target);
428 std::string Str;
429 switch (Lex.Lex()) {
430 default:
431 return tokError("unknown target property");
432 case lltok::kw_triple:
433 Lex.Lex();
434 if (parseToken(lltok::equal, "expected '=' after target triple") ||
435 parseStringConstant(Str))
436 return true;
437 M->setTargetTriple(Str);
438 return false;
439 case lltok::kw_datalayout:
440 Lex.Lex();
441 if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
442 parseStringConstant(Str))
443 return true;
444 M->setDataLayout(Str);
445 return false;
446 }
447}
448
449/// toplevelentity
450/// ::= 'source_filename' '=' STRINGCONSTANT
451bool LLParser::parseSourceFileName() {
452 assert(Lex.getKind() == lltok::kw_source_filename);
453 Lex.Lex();
454 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
455 parseStringConstant(SourceFileName))
456 return true;
457 if (M)
458 M->setSourceFileName(SourceFileName);
459 return false;
460}
461
462/// toplevelentity
463/// ::= 'deplibs' '=' '[' ']'
464/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
465/// FIXME: Remove in 4.0. Currently parse, but ignore.
466bool LLParser::parseDepLibs() {
467 assert(Lex.getKind() == lltok::kw_deplibs);
468 Lex.Lex();
469 if (parseToken(lltok::equal, "expected '=' after deplibs") ||
470 parseToken(lltok::lsquare, "expected '=' after deplibs"))
471 return true;
472
473 if (EatIfPresent(lltok::rsquare))
474 return false;
475
476 do {
477 std::string Str;
478 if (parseStringConstant(Str))
479 return true;
480 } while (EatIfPresent(lltok::comma));
481
482 return parseToken(lltok::rsquare, "expected ']' at end of list");
483}
484
485/// parseUnnamedType:
486/// ::= LocalVarID '=' 'type' type
487bool LLParser::parseUnnamedType() {
488 LocTy TypeLoc = Lex.getLoc();
489 unsigned TypeID = Lex.getUIntVal();
490 Lex.Lex(); // eat LocalVarID;
491
492 if (parseToken(lltok::equal, "expected '=' after name") ||
493 parseToken(lltok::kw_type, "expected 'type' after '='"))
494 return true;
495
496 Type *Result = nullptr;
497 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
498 return true;
499
500 if (!isa<StructType>(Result)) {
501 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
502 if (Entry.first)
503 return error(TypeLoc, "non-struct types may not be recursive");
504 Entry.first = Result;
505 Entry.second = SMLoc();
506 }
507
508 return false;
509}
510
511/// toplevelentity
512/// ::= LocalVar '=' 'type' type
513bool LLParser::parseNamedType() {
514 std::string Name = Lex.getStrVal();
515 LocTy NameLoc = Lex.getLoc();
516 Lex.Lex(); // eat LocalVar.
517
518 if (parseToken(lltok::equal, "expected '=' after name") ||
519 parseToken(lltok::kw_type, "expected 'type' after name"))
520 return true;
521
522 Type *Result = nullptr;
523 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
524 return true;
525
526 if (!isa<StructType>(Result)) {
527 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
528 if (Entry.first)
529 return error(NameLoc, "non-struct types may not be recursive");
530 Entry.first = Result;
531 Entry.second = SMLoc();
532 }
533
534 return false;
535}
536
537/// toplevelentity
538/// ::= 'declare' FunctionHeader
539bool LLParser::parseDeclare() {
540 assert(Lex.getKind() == lltok::kw_declare);
541 Lex.Lex();
542
543 std::vector<std::pair<unsigned, MDNode *>> MDs;
544 while (Lex.getKind() == lltok::MetadataVar) {
545 unsigned MDK;
546 MDNode *N;
547 if (parseMetadataAttachment(MDK, N))
548 return true;
549 MDs.push_back({MDK, N});
550 }
551
552 Function *F;
553 if (parseFunctionHeader(F, false))
554 return true;
555 for (auto &MD : MDs)
556 F->addMetadata(MD.first, *MD.second);
557 return false;
558}
559
560/// toplevelentity
561/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
562bool LLParser::parseDefine() {
563 assert(Lex.getKind() == lltok::kw_define);
564 Lex.Lex();
565
566 Function *F;
567 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
568 parseFunctionBody(*F);
569}
570
571/// parseGlobalType
572/// ::= 'constant'
573/// ::= 'global'
574bool LLParser::parseGlobalType(bool &IsConstant) {
575 if (Lex.getKind() == lltok::kw_constant)
576 IsConstant = true;
577 else if (Lex.getKind() == lltok::kw_global)
578 IsConstant = false;
579 else {
580 IsConstant = false;
581 return tokError("expected 'global' or 'constant'");
582 }
583 Lex.Lex();
584 return false;
585}
586
587bool LLParser::parseOptionalUnnamedAddr(
588 GlobalVariable::UnnamedAddr &UnnamedAddr) {
589 if (EatIfPresent(lltok::kw_unnamed_addr))
590 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
591 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
592 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
593 else
594 UnnamedAddr = GlobalValue::UnnamedAddr::None;
595 return false;
596}
597
598/// parseUnnamedGlobal:
599/// OptionalVisibility (ALIAS | IFUNC) ...
600/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
601/// OptionalDLLStorageClass
602/// ... -> global variable
603/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
604/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
605/// OptionalVisibility
606/// OptionalDLLStorageClass
607/// ... -> global variable
608bool LLParser::parseUnnamedGlobal() {
609 unsigned VarID = NumberedVals.size();
610 std::string Name;
611 LocTy NameLoc = Lex.getLoc();
612
613 // Handle the GlobalID form.
614 if (Lex.getKind() == lltok::GlobalID) {
615 if (Lex.getUIntVal() != VarID)
616 return error(Lex.getLoc(),
617 "variable expected to be numbered '%" + Twine(VarID) + "'");
618 Lex.Lex(); // eat GlobalID;
619
620 if (parseToken(lltok::equal, "expected '=' after name"))
621 return true;
622 }
623
624 bool HasLinkage;
625 unsigned Linkage, Visibility, DLLStorageClass;
626 bool DSOLocal;
627 GlobalVariable::ThreadLocalMode TLM;
628 GlobalVariable::UnnamedAddr UnnamedAddr;
629 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
630 DSOLocal) ||
631 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
632 return true;
633
634 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
635 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
636 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
637
638 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
639 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
640}
641
642/// parseNamedGlobal:
643/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
644/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
645/// OptionalVisibility OptionalDLLStorageClass
646/// ... -> global variable
647bool LLParser::parseNamedGlobal() {
648 assert(Lex.getKind() == lltok::GlobalVar);
649 LocTy NameLoc = Lex.getLoc();
650 std::string Name = Lex.getStrVal();
651 Lex.Lex();
652
653 bool HasLinkage;
654 unsigned Linkage, Visibility, DLLStorageClass;
655 bool DSOLocal;
656 GlobalVariable::ThreadLocalMode TLM;
657 GlobalVariable::UnnamedAddr UnnamedAddr;
658 if (parseToken(lltok::equal, "expected '=' in global variable") ||
659 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
660 DSOLocal) ||
661 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
662 return true;
663
664 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
665 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
666 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667
668 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
669 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
670}
671
672bool LLParser::parseComdat() {
673 assert(Lex.getKind() == lltok::ComdatVar);
674 std::string Name = Lex.getStrVal();
675 LocTy NameLoc = Lex.getLoc();
676 Lex.Lex();
677
678 if (parseToken(lltok::equal, "expected '=' here"))
679 return true;
680
681 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
682 return tokError("expected comdat type");
683
684 Comdat::SelectionKind SK;
685 switch (Lex.getKind()) {
686 default:
687 return tokError("unknown selection kind");
688 case lltok::kw_any:
689 SK = Comdat::Any;
690 break;
691 case lltok::kw_exactmatch:
692 SK = Comdat::ExactMatch;
693 break;
694 case lltok::kw_largest:
695 SK = Comdat::Largest;
696 break;
697 case lltok::kw_noduplicates:
698 SK = Comdat::NoDuplicates;
699 break;
700 case lltok::kw_samesize:
701 SK = Comdat::SameSize;
702 break;
703 }
704 Lex.Lex();
705
706 // See if the comdat was forward referenced, if so, use the comdat.
707 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
708 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
709 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
710 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
711
712 Comdat *C;
713 if (I != ComdatSymTab.end())
714 C = &I->second;
715 else
716 C = M->getOrInsertComdat(Name);
717 C->setSelectionKind(SK);
718
719 return false;
720}
721
722// MDString:
723// ::= '!' STRINGCONSTANT
724bool LLParser::parseMDString(MDString *&Result) {
725 std::string Str;
726 if (parseStringConstant(Str))
727 return true;
728 Result = MDString::get(Context, Str);
729 return false;
730}
731
732// MDNode:
733// ::= '!' MDNodeNumber
734bool LLParser::parseMDNodeID(MDNode *&Result) {
735 // !{ ..., !42, ... }
736 LocTy IDLoc = Lex.getLoc();
737 unsigned MID = 0;
738 if (parseUInt32(MID))
739 return true;
740
741 // If not a forward reference, just return it now.
742 if (NumberedMetadata.count(MID)) {
743 Result = NumberedMetadata[MID];
744 return false;
745 }
746
747 // Otherwise, create MDNode forward reference.
748 auto &FwdRef = ForwardRefMDNodes[MID];
749 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
750
751 Result = FwdRef.first.get();
752 NumberedMetadata[MID].reset(Result);
753 return false;
754}
755
756/// parseNamedMetadata:
757/// !foo = !{ !1, !2 }
758bool LLParser::parseNamedMetadata() {
759 assert(Lex.getKind() == lltok::MetadataVar);
760 std::string Name = Lex.getStrVal();
761 Lex.Lex();
762
763 if (parseToken(lltok::equal, "expected '=' here") ||
764 parseToken(lltok::exclaim, "Expected '!' here") ||
765 parseToken(lltok::lbrace, "Expected '{' here"))
766 return true;
767
768 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
769 if (Lex.getKind() != lltok::rbrace)
770 do {
771 MDNode *N = nullptr;
772 // parse DIExpressions inline as a special case. They are still MDNodes,
773 // so they can still appear in named metadata. Remove this logic if they
774 // become plain Metadata.
775 if (Lex.getKind() == lltok::MetadataVar &&
776 Lex.getStrVal() == "DIExpression") {
777 if (parseDIExpression(N, /*IsDistinct=*/false))
778 return true;
779 // DIArgLists should only appear inline in a function, as they may
780 // contain LocalAsMetadata arguments which require a function context.
781 } else if (Lex.getKind() == lltok::MetadataVar &&
782 Lex.getStrVal() == "DIArgList") {
783 return tokError("found DIArgList outside of function");
784 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
785 parseMDNodeID(N)) {
786 return true;
787 }
788 NMD->addOperand(N);
789 } while (EatIfPresent(lltok::comma));
790
791 return parseToken(lltok::rbrace, "expected end of metadata node");
792}
793
794/// parseStandaloneMetadata:
795/// !42 = !{...}
796bool LLParser::parseStandaloneMetadata() {
797 assert(Lex.getKind() == lltok::exclaim);
798 Lex.Lex();
799 unsigned MetadataID = 0;
800
801 MDNode *Init;
802 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
803 return true;
804
805 // Detect common error, from old metadata syntax.
806 if (Lex.getKind() == lltok::Type)
807 return tokError("unexpected type in metadata definition");
808
809 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
810 if (Lex.getKind() == lltok::MetadataVar) {
811 if (parseSpecializedMDNode(Init, IsDistinct))
812 return true;
813 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
814 parseMDTuple(Init, IsDistinct))
815 return true;
816
817 // See if this was forward referenced, if so, handle it.
818 auto FI = ForwardRefMDNodes.find(MetadataID);
819 if (FI != ForwardRefMDNodes.end()) {
820 FI->second.first->replaceAllUsesWith(Init);
821 ForwardRefMDNodes.erase(FI);
822
823 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
824 } else {
825 if (NumberedMetadata.count(MetadataID))
826 return tokError("Metadata id is already used");
827 NumberedMetadata[MetadataID].reset(Init);
828 }
829
830 return false;
831}
832
833// Skips a single module summary entry.
834bool LLParser::skipModuleSummaryEntry() {
835 // Each module summary entry consists of a tag for the entry
836 // type, followed by a colon, then the fields which may be surrounded by
837 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
838 // support is in place we will look for the tokens corresponding to the
839 // expected tags.
840 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
841 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
842 Lex.getKind() != lltok::kw_blockcount)
843 return tokError(
844 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
845 "start of summary entry");
846 if (Lex.getKind() == lltok::kw_flags)
847 return parseSummaryIndexFlags();
848 if (Lex.getKind() == lltok::kw_blockcount)
849 return parseBlockCount();
850 Lex.Lex();
851 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
852 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
853 return true;
854 // Now walk through the parenthesized entry, until the number of open
855 // parentheses goes back down to 0 (the first '(' was parsed above).
856 unsigned NumOpenParen = 1;
857 do {
858 switch (Lex.getKind()) {
859 case lltok::lparen:
860 NumOpenParen++;
861 break;
862 case lltok::rparen:
863 NumOpenParen--;
864 break;
865 case lltok::Eof:
866 return tokError("found end of file while parsing summary entry");
867 default:
868 // Skip everything in between parentheses.
869 break;
870 }
871 Lex.Lex();
872 } while (NumOpenParen > 0);
873 return false;
874}
875
876/// SummaryEntry
877/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
878bool LLParser::parseSummaryEntry() {
879 assert(Lex.getKind() == lltok::SummaryID);
880 unsigned SummaryID = Lex.getUIntVal();
881
882 // For summary entries, colons should be treated as distinct tokens,
883 // not an indication of the end of a label token.
884 Lex.setIgnoreColonInIdentifiers(true);
885
886 Lex.Lex();
887 if (parseToken(lltok::equal, "expected '=' here"))
888 return true;
889
890 // If we don't have an index object, skip the summary entry.
891 if (!Index)
892 return skipModuleSummaryEntry();
893
894 bool result = false;
895 switch (Lex.getKind()) {
896 case lltok::kw_gv:
897 result = parseGVEntry(SummaryID);
898 break;
899 case lltok::kw_module:
900 result = parseModuleEntry(SummaryID);
901 break;
902 case lltok::kw_typeid:
903 result = parseTypeIdEntry(SummaryID);
904 break;
905 case lltok::kw_typeidCompatibleVTable:
906 result = parseTypeIdCompatibleVtableEntry(SummaryID);
907 break;
908 case lltok::kw_flags:
909 result = parseSummaryIndexFlags();
910 break;
911 case lltok::kw_blockcount:
912 result = parseBlockCount();
913 break;
914 default:
915 result = error(Lex.getLoc(), "unexpected summary kind");
916 break;
917 }
918 Lex.setIgnoreColonInIdentifiers(false);
919 return result;
920}
921
922static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
923 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
924 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
925}
926
927// If there was an explicit dso_local, update GV. In the absence of an explicit
928// dso_local we keep the default value.
929static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
930 if (DSOLocal)
931 GV.setDSOLocal(true);
932}
933
934static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
935 Type *Ty2) {
936 std::string ErrString;
937 raw_string_ostream ErrOS(ErrString);
938 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
939 return ErrOS.str();
940}
941
942/// parseIndirectSymbol:
943/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
944/// OptionalVisibility OptionalDLLStorageClass
945/// OptionalThreadLocal OptionalUnnamedAddr
946/// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
947///
948/// IndirectSymbol
949/// ::= TypeAndValue
950///
951/// IndirectSymbolAttr
952/// ::= ',' 'partition' StringConstant
953///
954/// Everything through OptionalUnnamedAddr has already been parsed.
955///
956bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
957 unsigned L, unsigned Visibility,
958 unsigned DLLStorageClass, bool DSOLocal,
959 GlobalVariable::ThreadLocalMode TLM,
960 GlobalVariable::UnnamedAddr UnnamedAddr) {
961 bool IsAlias;
962 if (Lex.getKind() == lltok::kw_alias)
963 IsAlias = true;
964 else if (Lex.getKind() == lltok::kw_ifunc)
965 IsAlias = false;
966 else
967 llvm_unreachable("Not an alias or ifunc!");
968 Lex.Lex();
969
970 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
971
972 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
973 return error(NameLoc, "invalid linkage type for alias");
974
975 if (!isValidVisibilityForLinkage(Visibility, L))
976 return error(NameLoc,
977 "symbol with local linkage must have default visibility");
978
979 Type *Ty;
980 LocTy ExplicitTypeLoc = Lex.getLoc();
981 if (parseType(Ty) ||
982 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
983 return true;
984
985 Constant *Aliasee;
986 LocTy AliaseeLoc = Lex.getLoc();
987 if (Lex.getKind() != lltok::kw_bitcast &&
988 Lex.getKind() != lltok::kw_getelementptr &&
989 Lex.getKind() != lltok::kw_addrspacecast &&
990 Lex.getKind() != lltok::kw_inttoptr) {
991 if (parseGlobalTypeAndValue(Aliasee))
992 return true;
993 } else {
994 // The bitcast dest type is not present, it is implied by the dest type.
995 ValID ID;
996 if (parseValID(ID))
997 return true;
998 if (ID.Kind != ValID::t_Constant)
999 return error(AliaseeLoc, "invalid aliasee");
1000 Aliasee = ID.ConstantVal;
1001 }
1002
1003 Type *AliaseeType = Aliasee->getType();
1004 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1005 if (!PTy)
1006 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1007 unsigned AddrSpace = PTy->getAddressSpace();
1008
1009 if (IsAlias && Ty != PTy->getElementType()) {
1010 return error(
1011 ExplicitTypeLoc,
1012 typeComparisonErrorMessage(
1013 "explicit pointee type doesn't match operand's pointee type", Ty,
1014 PTy->getElementType()));
1015 }
1016
1017 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
1018 return error(ExplicitTypeLoc,
1019 "explicit pointee type should be a function type");
1020 }
1021
1022 GlobalValue *GVal = nullptr;
1023
1024 // See if the alias was forward referenced, if so, prepare to replace the
1025 // forward reference.
1026 if (!Name.empty()) {
1027 GVal = M->getNamedValue(Name);
1028 if (GVal) {
1029 if (!ForwardRefVals.erase(Name))
1030 return error(NameLoc, "redefinition of global '@" + Name + "'");
1031 }
1032 } else {
1033 auto I = ForwardRefValIDs.find(NumberedVals.size());
1034 if (I != ForwardRefValIDs.end()) {
1035 GVal = I->second.first;
1036 ForwardRefValIDs.erase(I);
1037 }
1038 }
1039
1040 // Okay, create the alias but do not insert it into the module yet.
1041 std::unique_ptr<GlobalIndirectSymbol> GA;
1042 if (IsAlias)
1043 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1044 (GlobalValue::LinkageTypes)Linkage, Name,
1045 Aliasee, /*Parent*/ nullptr));
1046 else
1047 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1048 (GlobalValue::LinkageTypes)Linkage, Name,
1049 Aliasee, /*Parent*/ nullptr));
1050 GA->setThreadLocalMode(TLM);
1051 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1052 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1053 GA->setUnnamedAddr(UnnamedAddr);
1054 maybeSetDSOLocal(DSOLocal, *GA);
1055
1056 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1057 // Now parse them if there are any.
1058 while (Lex.getKind() == lltok::comma) {
1059 Lex.Lex();
1060
1061 if (Lex.getKind() == lltok::kw_partition) {
1062 Lex.Lex();
1063 GA->setPartition(Lex.getStrVal());
1064 if (parseToken(lltok::StringConstant, "expected partition string"))
1065 return true;
1066 } else {
1067 return tokError("unknown alias or ifunc property!");
1068 }
1069 }
1070
1071 if (Name.empty())
1072 NumberedVals.push_back(GA.get());
1073
1074 if (GVal) {
1075 // Verify that types agree.
1076 if (GVal->getType() != GA->getType())
1077 return error(
1078 ExplicitTypeLoc,
1079 "forward reference and definition of alias have different types");
1080
1081 // If they agree, just RAUW the old value with the alias and remove the
1082 // forward ref info.
1083 GVal->replaceAllUsesWith(GA.get());
1084 GVal->eraseFromParent();
1085 }
1086
1087 // Insert into the module, we know its name won't collide now.
1088 if (IsAlias)
1089 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1090 else
1091 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1092 assert(GA->getName() == Name && "Should not be a name conflict!");
1093
1094 // The module owns this now
1095 GA.release();
1096
1097 return false;
1098}
1099
1100/// parseGlobal
1101/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1102/// OptionalVisibility OptionalDLLStorageClass
1103/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1104/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1105/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1106/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1107/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1108/// Const OptionalAttrs
1109///
1110/// Everything up to and including OptionalUnnamedAddr has been parsed
1111/// already.
1112///
1113bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1114 unsigned Linkage, bool HasLinkage,
1115 unsigned Visibility, unsigned DLLStorageClass,
1116 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1117 GlobalVariable::UnnamedAddr UnnamedAddr) {
1118 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1119 return error(NameLoc,
1120 "symbol with local linkage must have default visibility");
1121
1122 unsigned AddrSpace;
1123 bool IsConstant, IsExternallyInitialized;
1124 LocTy IsExternallyInitializedLoc;
1125 LocTy TyLoc;
1126
1127 Type *Ty = nullptr;
1128 if (parseOptionalAddrSpace(AddrSpace) ||
1129 parseOptionalToken(lltok::kw_externally_initialized,
1130 IsExternallyInitialized,
1131 &IsExternallyInitializedLoc) ||
1132 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1133 return true;
1134
1135 // If the linkage is specified and is external, then no initializer is
1136 // present.
1137 Constant *Init = nullptr;
1138 if (!HasLinkage ||
1139 !GlobalValue::isValidDeclarationLinkage(
1140 (GlobalValue::LinkageTypes)Linkage)) {
1141 if (parseGlobalValue(Ty, Init))
1142 return true;
1143 }
1144
1145 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1146 return error(TyLoc, "invalid type for global variable");
1147
1148 GlobalValue *GVal = nullptr;
1149
1150 // See if the global was forward referenced, if so, use the global.
1151 if (!Name.empty()) {
1152 GVal = M->getNamedValue(Name);
1153 if (GVal) {
1154 if (!ForwardRefVals.erase(Name))
1155 return error(NameLoc, "redefinition of global '@" + Name + "'");
1156 }
1157 } else {
1158 auto I = ForwardRefValIDs.find(NumberedVals.size());
1159 if (I != ForwardRefValIDs.end()) {
1160 GVal = I->second.first;
1161 ForwardRefValIDs.erase(I);
1162 }
1163 }
1164
1165 GlobalVariable *GV;
1166 if (!GVal) {
1167 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1168 Name, nullptr, GlobalVariable::NotThreadLocal,
1169 AddrSpace);
1170 } else {
1171 if (GVal->getValueType() != Ty)
1172 return error(
1173 TyLoc,
1174 "forward reference and definition of global have different types");
1175
1176 GV = cast<GlobalVariable>(GVal);
1177
1178 // Move the forward-reference to the correct spot in the module.
1179 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1180 }
1181
1182 if (Name.empty())
1183 NumberedVals.push_back(GV);
1184
1185 // Set the parsed properties on the global.
1186 if (Init)
1187 GV->setInitializer(Init);
1188 GV->setConstant(IsConstant);
1189 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1190 maybeSetDSOLocal(DSOLocal, *GV);
1191 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1192 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1193 GV->setExternallyInitialized(IsExternallyInitialized);
1194 GV->setThreadLocalMode(TLM);
1195 GV->setUnnamedAddr(UnnamedAddr);
1196
1197 // parse attributes on the global.
1198 while (Lex.getKind() == lltok::comma) {
1199 Lex.Lex();
1200
1201 if (Lex.getKind() == lltok::kw_section) {
1202 Lex.Lex();
1203 GV->setSection(Lex.getStrVal());
1204 if (parseToken(lltok::StringConstant, "expected global section string"))
1205 return true;
1206 } else if (Lex.getKind() == lltok::kw_partition) {
1207 Lex.Lex();
1208 GV->setPartition(Lex.getStrVal());
1209 if (parseToken(lltok::StringConstant, "expected partition string"))
1210 return true;
1211 } else if (Lex.getKind() == lltok::kw_align) {
1212 MaybeAlign Alignment;
1213 if (parseOptionalAlignment(Alignment))
1214 return true;
1215 GV->setAlignment(Alignment);
1216 } else if (Lex.getKind() == lltok::MetadataVar) {
1217 if (parseGlobalObjectMetadataAttachment(*GV))
1218 return true;
1219 } else {
1220 Comdat *C;
1221 if (parseOptionalComdat(Name, C))
1222 return true;
1223 if (C)
1224 GV->setComdat(C);
1225 else
1226 return tokError("unknown global variable property!");
1227 }
1228 }
1229
1230 AttrBuilder Attrs;
1231 LocTy BuiltinLoc;
1232 std::vector<unsigned> FwdRefAttrGrps;
1233 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1234 return true;
1235 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1236 GV->setAttributes(AttributeSet::get(Context, Attrs));
1237 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1238 }
1239
1240 return false;
1241}
1242
1243/// parseUnnamedAttrGrp
1244/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1245bool LLParser::parseUnnamedAttrGrp() {
1246 assert(Lex.getKind() == lltok::kw_attributes);
1247 LocTy AttrGrpLoc = Lex.getLoc();
1248 Lex.Lex();
1249
1250 if (Lex.getKind() != lltok::AttrGrpID)
1251 return tokError("expected attribute group id");
1252
1253 unsigned VarID = Lex.getUIntVal();
1254 std::vector<unsigned> unused;
1255 LocTy BuiltinLoc;
1256 Lex.Lex();
1257
1258 if (parseToken(lltok::equal, "expected '=' here") ||
1259 parseToken(lltok::lbrace, "expected '{' here") ||
1260 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1261 BuiltinLoc) ||
1262 parseToken(lltok::rbrace, "expected end of attribute group"))
1263 return true;
1264
1265 if (!NumberedAttrBuilders[VarID].hasAttributes())
1266 return error(AttrGrpLoc, "attribute group has no attributes");
1267
1268 return false;
1269}
1270
1271/// parseFnAttributeValuePairs
1272/// ::= <attr> | <attr> '=' <value>
1273bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1274 std::vector<unsigned> &FwdRefAttrGrps,
1275 bool inAttrGrp, LocTy &BuiltinLoc) {
1276 bool HaveError = false;
1277
1278 B.clear();
1279
1280 while (true) {
1281 lltok::Kind Token = Lex.getKind();
1282 if (Token == lltok::kw_builtin)
1283 BuiltinLoc = Lex.getLoc();
1284 switch (Token) {
1285 default:
1286 if (!inAttrGrp) return HaveError;
1287 return error(Lex.getLoc(), "unterminated attribute group");
1288 case lltok::rbrace:
1289 // Finished.
1290 return false;
1291
1292 case lltok::AttrGrpID: {
1293 // Allow a function to reference an attribute group:
1294 //
1295 // define void @foo() #1 { ... }
1296 if (inAttrGrp)
1297 HaveError |= error(
1298 Lex.getLoc(),
1299 "cannot have an attribute group reference in an attribute group");
1300
1301 unsigned AttrGrpNum = Lex.getUIntVal();
1302 if (inAttrGrp) break;
1303
1304 // Save the reference to the attribute group. We'll fill it in later.
1305 FwdRefAttrGrps.push_back(AttrGrpNum);
1306 break;
1307 }
1308 // Target-dependent attributes:
1309 case lltok::StringConstant: {
1310 if (parseStringAttribute(B))
1311 return true;
1312 continue;
1313 }
1314
1315 // Target-independent attributes:
1316 case lltok::kw_align: {
1317 // As a hack, we allow function alignment to be initially parsed as an
1318 // attribute on a function declaration/definition or added to an attribute
1319 // group and later moved to the alignment field.
1320 MaybeAlign Alignment;
1321 if (inAttrGrp) {
1322 Lex.Lex();
1323 uint32_t Value = 0;
1324 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1325 return true;
1326 Alignment = Align(Value);
1327 } else {
1328 if (parseOptionalAlignment(Alignment))
1329 return true;
1330 }
1331 B.addAlignmentAttr(Alignment);
1332 continue;
1333 }
1334 case lltok::kw_alignstack: {
1335 unsigned Alignment;
1336 if (inAttrGrp) {
1337 Lex.Lex();
1338 if (parseToken(lltok::equal, "expected '=' here") ||
1339 parseUInt32(Alignment))
1340 return true;
1341 } else {
1342 if (parseOptionalStackAlignment(Alignment))
1343 return true;
1344 }
1345 B.addStackAlignmentAttr(Alignment);
1346 continue;
1347 }
1348 case lltok::kw_allocsize: {
1349 unsigned ElemSizeArg;
1350 Optional<unsigned> NumElemsArg;
1351 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1352 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1353 return true;
1354 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1355 continue;
1356 }
1357 case lltok::kw_vscale_range: {
1358 unsigned MinValue, MaxValue;
1359 // inAttrGrp doesn't matter; we only support vscale_range(a[, b])
1360 if (parseVScaleRangeArguments(MinValue, MaxValue))
1361 return true;
1362 B.addVScaleRangeAttr(MinValue, MaxValue);
1363 continue;
1364 }
1365 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1366 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1367 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1368 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1369 case lltok::kw_hot: B.addAttribute(Attribute::Hot); break;
1370 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1371 case lltok::kw_inaccessiblememonly:
1372 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1373 case lltok::kw_inaccessiblemem_or_argmemonly:
1374 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1375 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1376 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1377 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1378 case lltok::kw_mustprogress:
1379 B.addAttribute(Attribute::MustProgress);
1380 break;
1381 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1382 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1383 case lltok::kw_nocallback:
1384 B.addAttribute(Attribute::NoCallback);
1385 break;
1386 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1387 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1388 case lltok::kw_noimplicitfloat:
1389 B.addAttribute(Attribute::NoImplicitFloat); break;
1390 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1391 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1392 case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break;
1393 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1394 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1395 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1396 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1397 case lltok::kw_noprofile: B.addAttribute(Attribute::NoProfile); break;
1398 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1399 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1400 case lltok::kw_null_pointer_is_valid:
1401 B.addAttribute(Attribute::NullPointerIsValid); break;
1402 case lltok::kw_optforfuzzing:
1403 B.addAttribute(Attribute::OptForFuzzing); break;
1404 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1405 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1406 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1407 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1408 case lltok::kw_returns_twice:
1409 B.addAttribute(Attribute::ReturnsTwice); break;
1410 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1411 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1412 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1413 case lltok::kw_sspstrong:
1414 B.addAttribute(Attribute::StackProtectStrong); break;
1415 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1416 case lltok::kw_shadowcallstack:
1417 B.addAttribute(Attribute::ShadowCallStack); break;
1418 case lltok::kw_sanitize_address:
1419 B.addAttribute(Attribute::SanitizeAddress); break;
1420 case lltok::kw_sanitize_hwaddress:
1421 B.addAttribute(Attribute::SanitizeHWAddress); break;
1422 case lltok::kw_sanitize_memtag:
1423 B.addAttribute(Attribute::SanitizeMemTag); break;
1424 case lltok::kw_sanitize_thread:
1425 B.addAttribute(Attribute::SanitizeThread); break;
1426 case lltok::kw_sanitize_memory:
1427 B.addAttribute(Attribute::SanitizeMemory); break;
1428 case lltok::kw_speculative_load_hardening:
1429 B.addAttribute(Attribute::SpeculativeLoadHardening);
1430 break;
1431 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1432 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1433 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1434 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1435 case lltok::kw_preallocated: {
1436 Type *Ty;
1437 if (parsePreallocated(Ty))
1438 return true;
1439 B.addPreallocatedAttr(Ty);
1440 break;
1441 }
1442
1443 // error handling.
1444 case lltok::kw_inreg:
1445 case lltok::kw_signext:
1446 case lltok::kw_zeroext:
1447 HaveError |=
1448 error(Lex.getLoc(), "invalid use of attribute on a function");
1449 break;
1450 case lltok::kw_byval:
1451 case lltok::kw_dereferenceable:
1452 case lltok::kw_dereferenceable_or_null:
1453 case lltok::kw_inalloca:
1454 case lltok::kw_nest:
1455 case lltok::kw_noalias:
1456 case lltok::kw_noundef:
1457 case lltok::kw_nocapture:
1458 case lltok::kw_nonnull:
1459 case lltok::kw_returned:
1460 case lltok::kw_sret:
1461 case lltok::kw_swifterror:
1462 case lltok::kw_swiftself:
1463 case lltok::kw_immarg:
1464 case lltok::kw_byref:
1465 HaveError |=
1466 error(Lex.getLoc(),
1467 "invalid use of parameter-only attribute on a function");
1468 break;
1469 }
1470
1471 // parsePreallocated() consumes token
1472 if (Token != lltok::kw_preallocated)
1473 Lex.Lex();
1474 }
1475}
1476
1477//===----------------------------------------------------------------------===//
1478// GlobalValue Reference/Resolution Routines.
1479//===----------------------------------------------------------------------===//
1480
1481static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1482 const std::string &Name) {
1483 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1484 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1485 PTy->getAddressSpace(), Name, M);
1486 else
1487 return new GlobalVariable(*M, PTy->getElementType(), false,
1488 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1489 nullptr, GlobalVariable::NotThreadLocal,
1490 PTy->getAddressSpace());
1491}
1492
1493Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1494 Value *Val, bool IsCall) {
1495 if (Val->getType() == Ty)
1496 return Val;
1497 // For calls we also accept variables in the program address space.
1498 Type *SuggestedTy = Ty;
1499 if (IsCall && isa<PointerType>(Ty)) {
1500 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1501 M->getDataLayout().getProgramAddressSpace());
1502 SuggestedTy = TyInProgAS;
1503 if (Val->getType() == TyInProgAS)
1504 return Val;
1505 }
1506 if (Ty->isLabelTy())
1507 error(Loc, "'" + Name + "' is not a basic block");
1508 else
1509 error(Loc, "'" + Name + "' defined with type '" +
1510 getTypeString(Val->getType()) + "' but expected '" +
1511 getTypeString(SuggestedTy) + "'");
1512 return nullptr;
1513}
1514
1515/// getGlobalVal - Get a value with the specified name or ID, creating a
1516/// forward reference record if needed. This can return null if the value
1517/// exists but does not have the right type.
1518GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1519 LocTy Loc, bool IsCall) {
1520 PointerType *PTy = dyn_cast<PointerType>(Ty);
1521 if (!PTy) {
1522 error(Loc, "global variable reference must have pointer type");
1523 return nullptr;
1524 }
1525
1526 // Look this name up in the normal function symbol table.
1527 GlobalValue *Val =
1528 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1529
1530 // If this is a forward reference for the value, see if we already created a
1531 // forward ref record.
1532 if (!Val) {
1533 auto I = ForwardRefVals.find(Name);
1534 if (I != ForwardRefVals.end())
1535 Val = I->second.first;
1536 }
1537
1538 // If we have the value in the symbol table or fwd-ref table, return it.
1539 if (Val)
1540 return cast_or_null<GlobalValue>(
1541 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1542
1543 // Otherwise, create a new forward reference for this value and remember it.
1544 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1545 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1546 return FwdVal;
1547}
1548
1549GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1550 bool IsCall) {
1551 PointerType *PTy = dyn_cast<PointerType>(Ty);
1552 if (!PTy) {
1553 error(Loc, "global variable reference must have pointer type");
1554 return nullptr;
1555 }
1556
1557 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1558
1559 // If this is a forward reference for the value, see if we already created a
1560 // forward ref record.
1561 if (!Val) {
1562 auto I = ForwardRefValIDs.find(ID);
1563 if (I != ForwardRefValIDs.end())
1564 Val = I->second.first;
1565 }
1566
1567 // If we have the value in the symbol table or fwd-ref table, return it.
1568 if (Val)
1569 return cast_or_null<GlobalValue>(
1570 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1571
1572 // Otherwise, create a new forward reference for this value and remember it.
1573 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1574 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1575 return FwdVal;
1576}
1577
1578//===----------------------------------------------------------------------===//
1579// Comdat Reference/Resolution Routines.
1580//===----------------------------------------------------------------------===//
1581
1582Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1583 // Look this name up in the comdat symbol table.
1584 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1585 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1586 if (I != ComdatSymTab.end())
1587 return &I->second;
1588
1589 // Otherwise, create a new forward reference for this value and remember it.
1590 Comdat *C = M->getOrInsertComdat(Name);
1591 ForwardRefComdats[Name] = Loc;
1592 return C;
1593}
1594
1595//===----------------------------------------------------------------------===//
1596// Helper Routines.
1597//===----------------------------------------------------------------------===//
1598
1599/// parseToken - If the current token has the specified kind, eat it and return
1600/// success. Otherwise, emit the specified error and return failure.
1601bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1602 if (Lex.getKind() != T)
1603 return tokError(ErrMsg);
1604 Lex.Lex();
1605 return false;
1606}
1607
1608/// parseStringConstant
1609/// ::= StringConstant
1610bool LLParser::parseStringConstant(std::string &Result) {
1611 if (Lex.getKind() != lltok::StringConstant)
1612 return tokError("expected string constant");
1613 Result = Lex.getStrVal();
1614 Lex.Lex();
1615 return false;
1616}
1617
1618/// parseUInt32
1619/// ::= uint32
1620bool LLParser::parseUInt32(uint32_t &Val) {
1621 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1622 return tokError("expected integer");
1623 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1624 if (Val64 != unsigned(Val64))
1625 return tokError("expected 32-bit integer (too large)");
1626 Val = Val64;
1627 Lex.Lex();
1628 return false;
1629}
1630
1631/// parseUInt64
1632/// ::= uint64
1633bool LLParser::parseUInt64(uint64_t &Val) {
1634 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1635 return tokError("expected integer");
1636 Val = Lex.getAPSIntVal().getLimitedValue();
1637 Lex.Lex();
1638 return false;
1639}
1640
1641/// parseTLSModel
1642/// := 'localdynamic'
1643/// := 'initialexec'
1644/// := 'localexec'
1645bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1646 switch (Lex.getKind()) {
1647 default:
1648 return tokError("expected localdynamic, initialexec or localexec");
1649 case lltok::kw_localdynamic:
1650 TLM = GlobalVariable::LocalDynamicTLSModel;
1651 break;
1652 case lltok::kw_initialexec:
1653 TLM = GlobalVariable::InitialExecTLSModel;
1654 break;
1655 case lltok::kw_localexec:
1656 TLM = GlobalVariable::LocalExecTLSModel;
1657 break;
1658 }
1659
1660 Lex.Lex();
1661 return false;
1662}
1663
1664/// parseOptionalThreadLocal
1665/// := /*empty*/
1666/// := 'thread_local'
1667/// := 'thread_local' '(' tlsmodel ')'
1668bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1669 TLM = GlobalVariable::NotThreadLocal;
1670 if (!EatIfPresent(lltok::kw_thread_local))
1671 return false;
1672
1673 TLM = GlobalVariable::GeneralDynamicTLSModel;
1674 if (Lex.getKind() == lltok::lparen) {
1675 Lex.Lex();
1676 return parseTLSModel(TLM) ||
1677 parseToken(lltok::rparen, "expected ')' after thread local model");
1678 }
1679 return false;
1680}
1681
1682/// parseOptionalAddrSpace
1683/// := /*empty*/
1684/// := 'addrspace' '(' uint32 ')'
1685bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1686 AddrSpace = DefaultAS;
1687 if (!EatIfPresent(lltok::kw_addrspace))
1688 return false;
1689 return parseToken(lltok::lparen, "expected '(' in address space") ||
1690 parseUInt32(AddrSpace) ||
1691 parseToken(lltok::rparen, "expected ')' in address space");
1692}
1693
1694/// parseStringAttribute
1695/// := StringConstant
1696/// := StringConstant '=' StringConstant
1697bool LLParser::parseStringAttribute(AttrBuilder &B) {
1698 std::string Attr = Lex.getStrVal();
1699 Lex.Lex();
1700 std::string Val;
1701 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1702 return true;
1703 B.addAttribute(Attr, Val);
1704 return false;
1705}
1706
1707/// parseOptionalParamAttrs - parse a potentially empty list of parameter
1708/// attributes.
1709bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) {
1710 bool HaveError = false;
1711
1712 B.clear();
1713
1714 while (true) {
1715 lltok::Kind Token = Lex.getKind();
1716 switch (Token) {
1717 default: // End of attributes.
1718 return HaveError;
1719 case lltok::StringConstant: {
1720 if (parseStringAttribute(B))
1721 return true;
1722 continue;
1723 }
1724 case lltok::kw_align: {
1725 MaybeAlign Alignment;
1726 if (parseOptionalAlignment(Alignment, true))
1727 return true;
1728 B.addAlignmentAttr(Alignment);
1729 continue;
1730 }
1731 case lltok::kw_alignstack: {
1732 unsigned Alignment;
1733 if (parseOptionalStackAlignment(Alignment))
1734 return true;
1735 B.addStackAlignmentAttr(Alignment);
1736 continue;
1737 }
1738 case lltok::kw_byval: {
1739 Type *Ty;
1740 if (parseRequiredTypeAttr(Ty, lltok::kw_byval))
1741 return true;
1742 B.addByValAttr(Ty);
1743 continue;
1744 }
1745 case lltok::kw_sret: {
1746 Type *Ty;
1747 if (parseRequiredTypeAttr(Ty, lltok::kw_sret))
1748 return true;
1749 B.addStructRetAttr(Ty);
1750 continue;
1751 }
1752 case lltok::kw_preallocated: {
1753 Type *Ty;
1754 if (parsePreallocated(Ty))
1755 return true;
1756 B.addPreallocatedAttr(Ty);
1757 continue;
1758 }
1759 case lltok::kw_inalloca: {
1760 Type *Ty;
1761 if (parseInalloca(Ty))
1762 return true;
1763 B.addInAllocaAttr(Ty);
1764 continue;
1765 }
1766 case lltok::kw_dereferenceable: {
1767 uint64_t Bytes;
1768 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1769 return true;
1770 B.addDereferenceableAttr(Bytes);
1771 continue;
1772 }
1773 case lltok::kw_dereferenceable_or_null: {
1774 uint64_t Bytes;
1775 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1776 return true;
1777 B.addDereferenceableOrNullAttr(Bytes);
1778 continue;
1779 }
1780 case lltok::kw_byref: {
1781 Type *Ty;
1782 if (parseByRef(Ty))
1783 return true;
1784 B.addByRefAttr(Ty);
1785 continue;
1786 }
1787 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1788 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1789 case lltok::kw_noundef:
1790 B.addAttribute(Attribute::NoUndef);
1791 break;
1792 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1793 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1794 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1795 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1796 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1797 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1798 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1799 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1800 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1801 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1802 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1803 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1804 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1805
1806 case lltok::kw_alwaysinline:
1807 case lltok::kw_argmemonly:
1808 case lltok::kw_builtin:
1809 case lltok::kw_inlinehint:
1810 case lltok::kw_jumptable:
1811 case lltok::kw_minsize:
1812 case lltok::kw_mustprogress:
1813 case lltok::kw_naked:
1814 case lltok::kw_nobuiltin:
1815 case lltok::kw_noduplicate:
1816 case lltok::kw_noimplicitfloat:
1817 case lltok::kw_noinline:
1818 case lltok::kw_nonlazybind:
1819 case lltok::kw_nomerge:
1820 case lltok::kw_noprofile:
1821 case lltok::kw_noredzone:
1822 case lltok::kw_noreturn:
1823 case lltok::kw_nocf_check:
1824 case lltok::kw_nounwind:
1825 case lltok::kw_optforfuzzing:
1826 case lltok::kw_optnone:
1827 case lltok::kw_optsize:
1828 case lltok::kw_returns_twice:
1829 case lltok::kw_sanitize_address:
1830 case lltok::kw_sanitize_hwaddress:
1831 case lltok::kw_sanitize_memtag:
1832 case lltok::kw_sanitize_memory:
1833 case lltok::kw_sanitize_thread:
1834 case lltok::kw_speculative_load_hardening:
1835 case lltok::kw_ssp:
1836 case lltok::kw_sspreq:
1837 case lltok::kw_sspstrong:
1838 case lltok::kw_safestack:
1839 case lltok::kw_shadowcallstack:
1840 case lltok::kw_strictfp:
1841 case lltok::kw_uwtable:
1842 case lltok::kw_vscale_range:
1843 HaveError |=
1844 error(Lex.getLoc(), "invalid use of function-only attribute");
1845 break;
1846 }
1847
1848 Lex.Lex();
1849 }
1850}
1851
1852/// parseOptionalReturnAttrs - parse a potentially empty list of return
1853/// attributes.
1854bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) {
1855 bool HaveError = false;
1856
1857 B.clear();
1858
1859 while (true) {
1860 lltok::Kind Token = Lex.getKind();
1861 switch (Token) {
1862 default: // End of attributes.
1863 return HaveError;
1864 case lltok::StringConstant: {
1865 if (parseStringAttribute(B))
1866 return true;
1867 continue;
1868 }
1869 case lltok::kw_dereferenceable: {
1870 uint64_t Bytes;
1871 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1872 return true;
1873 B.addDereferenceableAttr(Bytes);
1874 continue;
1875 }
1876 case lltok::kw_dereferenceable_or_null: {
1877 uint64_t Bytes;
1878 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1879 return true;
1880 B.addDereferenceableOrNullAttr(Bytes);
1881 continue;
1882 }
1883 case lltok::kw_align: {
1884 MaybeAlign Alignment;
1885 if (parseOptionalAlignment(Alignment))
1886 return true;
1887 B.addAlignmentAttr(Alignment);
1888 continue;
1889 }
1890 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1891 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1892 case lltok::kw_noundef:
1893 B.addAttribute(Attribute::NoUndef);
1894 break;
1895 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1896 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1897 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1898
1899 // error handling.
1900 case lltok::kw_byval:
1901 case lltok::kw_inalloca:
1902 case lltok::kw_nest:
1903 case lltok::kw_nocapture:
1904 case lltok::kw_returned:
1905 case lltok::kw_sret:
1906 case lltok::kw_swifterror:
1907 case lltok::kw_swiftself:
1908 case lltok::kw_immarg:
1909 case lltok::kw_byref:
1910 HaveError |=
1911 error(Lex.getLoc(), "invalid use of parameter-only attribute");
1912 break;
1913
1914 case lltok::kw_alignstack:
1915 case lltok::kw_alwaysinline:
1916 case lltok::kw_argmemonly:
1917 case lltok::kw_builtin:
1918 case lltok::kw_cold:
1919 case lltok::kw_inlinehint:
1920 case lltok::kw_jumptable:
1921 case lltok::kw_minsize:
1922 case lltok::kw_mustprogress:
1923 case lltok::kw_naked:
1924 case lltok::kw_nobuiltin:
1925 case lltok::kw_noduplicate:
1926 case lltok::kw_noimplicitfloat:
1927 case lltok::kw_noinline:
1928 case lltok::kw_nonlazybind:
1929 case lltok::kw_nomerge:
1930 case lltok::kw_noprofile:
1931 case lltok::kw_noredzone:
1932 case lltok::kw_noreturn:
1933 case lltok::kw_nocf_check:
1934 case lltok::kw_nounwind:
1935 case lltok::kw_optforfuzzing:
1936 case lltok::kw_optnone:
1937 case lltok::kw_optsize:
1938 case lltok::kw_returns_twice:
1939 case lltok::kw_sanitize_address:
1940 case lltok::kw_sanitize_hwaddress:
1941 case lltok::kw_sanitize_memtag:
1942 case lltok::kw_sanitize_memory:
1943 case lltok::kw_sanitize_thread:
1944 case lltok::kw_speculative_load_hardening:
1945 case lltok::kw_ssp:
1946 case lltok::kw_sspreq:
1947 case lltok::kw_sspstrong:
1948 case lltok::kw_safestack:
1949 case lltok::kw_shadowcallstack:
1950 case lltok::kw_strictfp:
1951 case lltok::kw_uwtable:
1952 case lltok::kw_vscale_range:
1953 HaveError |=
1954 error(Lex.getLoc(), "invalid use of function-only attribute");
1955 break;
1956 case lltok::kw_readnone:
1957 case lltok::kw_readonly:
1958 HaveError |=
1959 error(Lex.getLoc(), "invalid use of attribute on return type");
1960 break;
1961 case lltok::kw_preallocated:
1962 HaveError |=
1963 error(Lex.getLoc(),
1964 "invalid use of parameter-only/call site-only attribute");
1965 break;
1966 }
1967
1968 Lex.Lex();
1969 }
1970}
1971
1972static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1973 HasLinkage = true;
1974 switch (Kind) {
1975 default:
1976 HasLinkage = false;
1977 return GlobalValue::ExternalLinkage;
1978 case lltok::kw_private:
1979 return GlobalValue::PrivateLinkage;
1980 case lltok::kw_internal:
1981 return GlobalValue::InternalLinkage;
1982 case lltok::kw_weak:
1983 return GlobalValue::WeakAnyLinkage;
1984 case lltok::kw_weak_odr:
1985 return GlobalValue::WeakODRLinkage;
1986 case lltok::kw_linkonce:
1987 return GlobalValue::LinkOnceAnyLinkage;
1988 case lltok::kw_linkonce_odr:
1989 return GlobalValue::LinkOnceODRLinkage;
1990 case lltok::kw_available_externally:
1991 return GlobalValue::AvailableExternallyLinkage;
1992 case lltok::kw_appending:
1993 return GlobalValue::AppendingLinkage;
1994 case lltok::kw_common:
1995 return GlobalValue::CommonLinkage;
1996 case lltok::kw_extern_weak:
1997 return GlobalValue::ExternalWeakLinkage;
1998 case lltok::kw_external:
1999 return GlobalValue::ExternalLinkage;
2000 }
2001}
2002
2003/// parseOptionalLinkage
2004/// ::= /*empty*/
2005/// ::= 'private'
2006/// ::= 'internal'
2007/// ::= 'weak'
2008/// ::= 'weak_odr'
2009/// ::= 'linkonce'
2010/// ::= 'linkonce_odr'
2011/// ::= 'available_externally'
2012/// ::= 'appending'
2013/// ::= 'common'
2014/// ::= 'extern_weak'
2015/// ::= 'external'
2016bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2017 unsigned &Visibility,
2018 unsigned &DLLStorageClass, bool &DSOLocal) {
2019 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2020 if (HasLinkage)
2021 Lex.Lex();
2022 parseOptionalDSOLocal(DSOLocal);
2023 parseOptionalVisibility(Visibility);
2024 parseOptionalDLLStorageClass(DLLStorageClass);
2025
2026 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2027 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2028 }
2029
2030 return false;
2031}
2032
2033void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2034 switch (Lex.getKind()) {
2035 default:
2036 DSOLocal = false;
2037 break;
2038 case lltok::kw_dso_local:
2039 DSOLocal = true;
2040 Lex.Lex();
2041 break;
2042 case lltok::kw_dso_preemptable:
2043 DSOLocal = false;
2044 Lex.Lex();
2045 break;
2046 }
2047}
2048
2049/// parseOptionalVisibility
2050/// ::= /*empty*/
2051/// ::= 'default'
2052/// ::= 'hidden'
2053/// ::= 'protected'
2054///
2055void LLParser::parseOptionalVisibility(unsigned &Res) {
2056 switch (Lex.getKind()) {
2057 default:
2058 Res = GlobalValue::DefaultVisibility;
2059 return;
2060 case lltok::kw_default:
2061 Res = GlobalValue::DefaultVisibility;
2062 break;
2063 case lltok::kw_hidden:
2064 Res = GlobalValue::HiddenVisibility;
2065 break;
2066 case lltok::kw_protected:
2067 Res = GlobalValue::ProtectedVisibility;
2068 break;
2069 }
2070 Lex.Lex();
2071}
2072
2073/// parseOptionalDLLStorageClass
2074/// ::= /*empty*/
2075/// ::= 'dllimport'
2076/// ::= 'dllexport'
2077///
2078void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2079 switch (Lex.getKind()) {
2080 default:
2081 Res = GlobalValue::DefaultStorageClass;
2082 return;
2083 case lltok::kw_dllimport:
2084 Res = GlobalValue::DLLImportStorageClass;
2085 break;
2086 case lltok::kw_dllexport:
2087 Res = GlobalValue::DLLExportStorageClass;
2088 break;
2089 }
2090 Lex.Lex();
2091}
2092
2093/// parseOptionalCallingConv
2094/// ::= /*empty*/
2095/// ::= 'ccc'
2096/// ::= 'fastcc'
2097/// ::= 'intel_ocl_bicc'
2098/// ::= 'coldcc'
2099/// ::= 'cfguard_checkcc'
2100/// ::= 'x86_stdcallcc'
2101/// ::= 'x86_fastcallcc'
2102/// ::= 'x86_thiscallcc'
2103/// ::= 'x86_vectorcallcc'
2104/// ::= 'arm_apcscc'
2105/// ::= 'arm_aapcscc'
2106/// ::= 'arm_aapcs_vfpcc'
2107/// ::= 'aarch64_vector_pcs'
2108/// ::= 'aarch64_sve_vector_pcs'
2109/// ::= 'msp430_intrcc'
2110/// ::= 'avr_intrcc'
2111/// ::= 'avr_signalcc'
2112/// ::= 'ptx_kernel'
2113/// ::= 'ptx_device'
2114/// ::= 'spir_func'
2115/// ::= 'spir_kernel'
2116/// ::= 'x86_64_sysvcc'
2117/// ::= 'win64cc'
2118/// ::= 'webkit_jscc'
2119/// ::= 'anyregcc'
2120/// ::= 'preserve_mostcc'
2121/// ::= 'preserve_allcc'
2122/// ::= 'ghccc'
2123/// ::= 'swiftcc'
2124/// ::= 'x86_intrcc'
2125/// ::= 'hhvmcc'
2126/// ::= 'hhvm_ccc'
2127/// ::= 'cxx_fast_tlscc'
2128/// ::= 'amdgpu_vs'
2129/// ::= 'amdgpu_ls'
2130/// ::= 'amdgpu_hs'
2131/// ::= 'amdgpu_es'
2132/// ::= 'amdgpu_gs'
2133/// ::= 'amdgpu_ps'
2134/// ::= 'amdgpu_cs'
2135/// ::= 'amdgpu_kernel'
2136/// ::= 'tailcc'
2137/// ::= 'cc' UINT
2138///
2139bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2140 switch (Lex.getKind()) {
2141 default: CC = CallingConv::C; return false;
2142 case lltok::kw_ccc: CC = CallingConv::C; break;
2143 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2144 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2145 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2146 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
2147 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2148 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
2149 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2150 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2151 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2152 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
2153 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2154 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2155 case lltok::kw_aarch64_sve_vector_pcs:
2156 CC = CallingConv::AArch64_SVE_VectorCall;
2157 break;
2158 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
2159 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2160 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
2161 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
2162 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
2163 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
2164 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2165 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2166 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
2167 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2168 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
2169 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2170 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2171 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2172 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2173 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2174 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2175 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
2176 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
2177 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2178 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2179 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
2180 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2181 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2182 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2183 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2184 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2185 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2186 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2187 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2188 case lltok::kw_cc: {
2189 Lex.Lex();
2190 return parseUInt32(CC);
2191 }
2192 }
2193
2194 Lex.Lex();
2195 return false;
2196}
2197
2198/// parseMetadataAttachment
2199/// ::= !dbg !42
2200bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2201 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2202
2203 std::string Name = Lex.getStrVal();
2204 Kind = M->getMDKindID(Name);
2205 Lex.Lex();
2206
2207 return parseMDNode(MD);
2208}
2209
2210/// parseInstructionMetadata
2211/// ::= !dbg !42 (',' !dbg !57)*
2212bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2213 do {
2214 if (Lex.getKind() != lltok::MetadataVar)
2215 return tokError("expected metadata after comma");
2216
2217 unsigned MDK;
2218 MDNode *N;
2219 if (parseMetadataAttachment(MDK, N))
2220 return true;
2221
2222 Inst.setMetadata(MDK, N);
2223 if (MDK == LLVMContext::MD_tbaa)
2224 InstsWithTBAATag.push_back(&Inst);
2225
2226 // If this is the end of the list, we're done.
2227 } while (EatIfPresent(lltok::comma));
2228 return false;
2229}
2230
2231/// parseGlobalObjectMetadataAttachment
2232/// ::= !dbg !57
2233bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2234 unsigned MDK;
2235 MDNode *N;
2236 if (parseMetadataAttachment(MDK, N))
2237 return true;
2238
2239 GO.addMetadata(MDK, *N);
2240 return false;
2241}
2242
2243/// parseOptionalFunctionMetadata
2244/// ::= (!dbg !57)*
2245bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2246 while (Lex.getKind() == lltok::MetadataVar)
2247 if (parseGlobalObjectMetadataAttachment(F))
2248 return true;
2249 return false;
2250}
2251
2252/// parseOptionalAlignment
2253/// ::= /* empty */
2254/// ::= 'align' 4
2255bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2256 Alignment = None;
2257 if (!EatIfPresent(lltok::kw_align))
2258 return false;
2259 LocTy AlignLoc = Lex.getLoc();
2260 uint32_t Value = 0;
2261
2262 LocTy ParenLoc = Lex.getLoc();
2263 bool HaveParens = false;
2264 if (AllowParens) {
2265 if (EatIfPresent(lltok::lparen))
2266 HaveParens = true;
2267 }
2268
2269 if (parseUInt32(Value))
2270 return true;
2271
2272 if (HaveParens && !EatIfPresent(lltok::rparen))
2273 return error(ParenLoc, "expected ')'");
2274
2275 if (!isPowerOf2_32(Value))
2276 return error(AlignLoc, "alignment is not a power of two");
2277 if (Value > Value::MaximumAlignment)
2278 return error(AlignLoc, "huge alignments are not supported yet");
2279 Alignment = Align(Value);
2280 return false;
2281}
2282
2283/// parseOptionalDerefAttrBytes
2284/// ::= /* empty */
2285/// ::= AttrKind '(' 4 ')'
2286///
2287/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2288bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2289 uint64_t &Bytes) {
2290 assert((AttrKind == lltok::kw_dereferenceable ||
2291 AttrKind == lltok::kw_dereferenceable_or_null) &&
2292 "contract!");
2293
2294 Bytes = 0;
2295 if (!EatIfPresent(AttrKind))
2296 return false;
2297 LocTy ParenLoc = Lex.getLoc();
2298 if (!EatIfPresent(lltok::lparen))
2299 return error(ParenLoc, "expected '('");
2300 LocTy DerefLoc = Lex.getLoc();
2301 if (parseUInt64(Bytes))
2302 return true;
2303 ParenLoc = Lex.getLoc();
2304 if (!EatIfPresent(lltok::rparen))
2305 return error(ParenLoc, "expected ')'");
2306 if (!Bytes)
2307 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2308 return false;
2309}
2310
2311/// parseOptionalCommaAlign
2312/// ::=
2313/// ::= ',' align 4
2314///
2315/// This returns with AteExtraComma set to true if it ate an excess comma at the
2316/// end.
2317bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2318 bool &AteExtraComma) {
2319 AteExtraComma = false;
2320 while (EatIfPresent(lltok::comma)) {
2321 // Metadata at the end is an early exit.
2322 if (Lex.getKind() == lltok::MetadataVar) {
2323 AteExtraComma = true;
2324 return false;
2325 }
2326
2327 if (Lex.getKind() != lltok::kw_align)
2328 return error(Lex.getLoc(), "expected metadata or 'align'");
2329
2330 if (parseOptionalAlignment(Alignment))
2331 return true;
2332 }
2333
2334 return false;
2335}
2336
2337/// parseOptionalCommaAddrSpace
2338/// ::=
2339/// ::= ',' addrspace(1)
2340///
2341/// This returns with AteExtraComma set to true if it ate an excess comma at the
2342/// end.
2343bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2344 bool &AteExtraComma) {
2345 AteExtraComma = false;
2346 while (EatIfPresent(lltok::comma)) {
2347 // Metadata at the end is an early exit.
2348 if (Lex.getKind() == lltok::MetadataVar) {
2349 AteExtraComma = true;
2350 return false;
2351 }
2352
2353 Loc = Lex.getLoc();
2354 if (Lex.getKind() != lltok::kw_addrspace)
2355 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2356
2357 if (parseOptionalAddrSpace(AddrSpace))
2358 return true;
2359 }
2360
2361 return false;
2362}
2363
2364bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2365 Optional<unsigned> &HowManyArg) {
2366 Lex.Lex();
2367
2368 auto StartParen = Lex.getLoc();
2369 if (!EatIfPresent(lltok::lparen))
2370 return error(StartParen, "expected '('");
2371
2372 if (parseUInt32(BaseSizeArg))
2373 return true;
2374
2375 if (EatIfPresent(lltok::comma)) {
2376 auto HowManyAt = Lex.getLoc();
2377 unsigned HowMany;
2378 if (parseUInt32(HowMany))
2379 return true;
2380 if (HowMany == BaseSizeArg)
2381 return error(HowManyAt,
2382 "'allocsize' indices can't refer to the same parameter");
2383 HowManyArg = HowMany;
2384 } else
2385 HowManyArg = None;
2386
2387 auto EndParen = Lex.getLoc();
2388 if (!EatIfPresent(lltok::rparen))
2389 return error(EndParen, "expected ')'");
2390 return false;
2391}
2392
2393bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2394 unsigned &MaxValue) {
2395 Lex.Lex();
2396
2397 auto StartParen = Lex.getLoc();
2398 if (!EatIfPresent(lltok::lparen))
2399 return error(StartParen, "expected '('");
2400
2401 if (parseUInt32(MinValue))
2402 return true;
2403
2404 if (EatIfPresent(lltok::comma)) {
2405 if (parseUInt32(MaxValue))
2406 return true;
2407 } else
2408 MaxValue = MinValue;
2409
2410 auto EndParen = Lex.getLoc();
2411 if (!EatIfPresent(lltok::rparen))
2412 return error(EndParen, "expected ')'");
2413 return false;
2414}
2415
2416/// parseScopeAndOrdering
2417/// if isAtomic: ::= SyncScope? AtomicOrdering
2418/// else: ::=
2419///
2420/// This sets Scope and Ordering to the parsed values.
2421bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2422 AtomicOrdering &Ordering) {
2423 if (!IsAtomic)
2424 return false;
2425
2426 return parseScope(SSID) || parseOrdering(Ordering);
2427}
2428
2429/// parseScope
2430/// ::= syncscope("singlethread" | "<target scope>")?
2431///
2432/// This sets synchronization scope ID to the ID of the parsed value.
2433bool LLParser::parseScope(SyncScope::ID &SSID) {
2434 SSID = SyncScope::System;
2435 if (EatIfPresent(lltok::kw_syncscope)) {
2436 auto StartParenAt = Lex.getLoc();
2437 if (!EatIfPresent(lltok::lparen))
2438 return error(StartParenAt, "Expected '(' in syncscope");
2439
2440 std::string SSN;
2441 auto SSNAt = Lex.getLoc();
2442 if (parseStringConstant(SSN))
2443 return error(SSNAt, "Expected synchronization scope name");
2444
2445 auto EndParenAt = Lex.getLoc();
2446 if (!EatIfPresent(lltok::rparen))
2447 return error(EndParenAt, "Expected ')' in syncscope");
2448
2449 SSID = Context.getOrInsertSyncScopeID(SSN);
2450 }
2451
2452 return false;
2453}
2454
2455/// parseOrdering
2456/// ::= AtomicOrdering
2457///
2458/// This sets Ordering to the parsed value.
2459bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2460 switch (Lex.getKind()) {
2461 default:
2462 return tokError("Expected ordering on atomic instruction");
2463 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2464 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2465 // Not specified yet:
2466 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2467 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2468 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2469 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2470 case lltok::kw_seq_cst:
2471 Ordering = AtomicOrdering::SequentiallyConsistent;
2472 break;
2473 }
2474 Lex.Lex();
2475 return false;
2476}
2477
2478/// parseOptionalStackAlignment
2479/// ::= /* empty */
2480/// ::= 'alignstack' '(' 4 ')'
2481bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2482 Alignment = 0;
2483 if (!EatIfPresent(lltok::kw_alignstack))
2484 return false;
2485 LocTy ParenLoc = Lex.getLoc();
2486 if (!EatIfPresent(lltok::lparen))
2487 return error(ParenLoc, "expected '('");
2488 LocTy AlignLoc = Lex.getLoc();
2489 if (parseUInt32(Alignment))
2490 return true;
2491 ParenLoc = Lex.getLoc();
2492 if (!EatIfPresent(lltok::rparen))
2493 return error(ParenLoc, "expected ')'");
2494 if (!isPowerOf2_32(Alignment))
2495 return error(AlignLoc, "stack alignment is not a power of two");
2496 return false;
2497}
2498
2499/// parseIndexList - This parses the index list for an insert/extractvalue
2500/// instruction. This sets AteExtraComma in the case where we eat an extra
2501/// comma at the end of the line and find that it is followed by metadata.
2502/// Clients that don't allow metadata can call the version of this function that
2503/// only takes one argument.
2504///
2505/// parseIndexList
2506/// ::= (',' uint32)+
2507///
2508bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2509 bool &AteExtraComma) {
2510 AteExtraComma = false;
2511
2512 if (Lex.getKind() != lltok::comma)
2513 return tokError("expected ',' as start of index list");
2514
2515 while (EatIfPresent(lltok::comma)) {
2516 if (Lex.getKind() == lltok::MetadataVar) {
2517 if (Indices.empty())
2518 return tokError("expected index");
2519 AteExtraComma = true;
2520 return false;
2521 }
2522 unsigned Idx = 0;
2523 if (parseUInt32(Idx))
2524 return true;
2525 Indices.push_back(Idx);
2526 }
2527
2528 return false;
2529}
2530
2531//===----------------------------------------------------------------------===//
2532// Type Parsing.
2533//===----------------------------------------------------------------------===//
2534
2535/// parseType - parse a type.
2536bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2537 SMLoc TypeLoc = Lex.getLoc();
2538 switch (Lex.getKind()) {
2539 default:
2540 return tokError(Msg);
2541 case lltok::Type:
2542 // Type ::= 'float' | 'void' (etc)
2543 Result = Lex.getTyVal();
2544 Lex.Lex();
2545 break;
2546 case lltok::lbrace:
2547 // Type ::= StructType
2548 if (parseAnonStructType(Result, false))
2549 return true;
2550 break;
2551 case lltok::lsquare:
2552 // Type ::= '[' ... ']'
2553 Lex.Lex(); // eat the lsquare.
2554 if (parseArrayVectorType(Result, false))
2555 return true;
2556 break;
2557 case lltok::less: // Either vector or packed struct.
2558 // Type ::= '<' ... '>'
2559 Lex.Lex();
2560 if (Lex.getKind() == lltok::lbrace) {
2561 if (parseAnonStructType(Result, true) ||
2562 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2563 return true;
2564 } else if (parseArrayVectorType(Result, true))
2565 return true;
2566 break;
2567 case lltok::LocalVar: {
2568 // Type ::= %foo
2569 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2570
2571 // If the type hasn't been defined yet, create a forward definition and
2572 // remember where that forward def'n was seen (in case it never is defined).
2573 if (!Entry.first) {
2574 Entry.first = StructType::create(Context, Lex.getStrVal());
2575 Entry.second = Lex.getLoc();
2576 }
2577 Result = Entry.first;
2578 Lex.Lex();
2579 break;
2580 }
2581
2582 case lltok::LocalVarID: {
2583 // Type ::= %4
2584 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2585
2586 // If the type hasn't been defined yet, create a forward definition and
2587 // remember where that forward def'n was seen (in case it never is defined).
2588 if (!Entry.first) {
2589 Entry.first = StructType::create(Context);
2590 Entry.second = Lex.getLoc();
2591 }
2592 Result = Entry.first;
2593 Lex.Lex();
2594 break;
2595 }
2596 }
2597
2598 // parse the type suffixes.
2599 while (true) {
2600 switch (Lex.getKind()) {
2601 // End of type.
2602 default:
2603 if (!AllowVoid && Result->isVoidTy())
2604 return error(TypeLoc, "void type only allowed for function results");
2605 return false;
2606
2607 // Type ::= Type '*'
2608 case lltok::star:
2609 if (Result->isLabelTy())
2610 return tokError("basic block pointers are invalid");
2611 if (Result->isVoidTy())
2612 return tokError("pointers to void are invalid - use i8* instead");
2613 if (!PointerType::isValidElementType(Result))
2614 return tokError("pointer to this type is invalid");
2615 Result = PointerType::getUnqual(Result);
2616 Lex.Lex();
2617 break;
2618
2619 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2620 case lltok::kw_addrspace: {
2621 if (Result->isLabelTy())
2622 return tokError("basic block pointers are invalid");
2623 if (Result->isVoidTy())
2624 return tokError("pointers to void are invalid; use i8* instead");
2625 if (!PointerType::isValidElementType(Result))
2626 return tokError("pointer to this type is invalid");
2627 unsigned AddrSpace;
2628 if (parseOptionalAddrSpace(AddrSpace) ||
2629 parseToken(lltok::star, "expected '*' in address space"))
2630 return true;
2631
2632 Result = PointerType::get(Result, AddrSpace);
2633 break;
2634 }
2635
2636 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2637 case lltok::lparen:
2638 if (parseFunctionType(Result))
2639 return true;
2640 break;
2641 }
2642 }
2643}
2644
2645/// parseParameterList
2646/// ::= '(' ')'
2647/// ::= '(' Arg (',' Arg)* ')'
2648/// Arg
2649/// ::= Type OptionalAttributes Value OptionalAttributes
2650bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2651 PerFunctionState &PFS, bool IsMustTailCall,
2652 bool InVarArgsFunc) {
2653 if (parseToken(lltok::lparen, "expected '(' in call"))
2654 return true;
2655
2656 while (Lex.getKind() != lltok::rparen) {
2657 // If this isn't the first argument, we need a comma.
2658 if (!ArgList.empty() &&
2659 parseToken(lltok::comma, "expected ',' in argument list"))
2660 return true;
2661
2662 // parse an ellipsis if this is a musttail call in a variadic function.
2663 if (Lex.getKind() == lltok::dotdotdot) {
2664 const char *Msg = "unexpected ellipsis in argument list for ";
2665 if (!IsMustTailCall)
2666 return tokError(Twine(Msg) + "non-musttail call");
2667 if (!InVarArgsFunc)
2668 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2669 Lex.Lex(); // Lex the '...', it is purely for readability.
2670 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2671 }
2672
2673 // parse the argument.
2674 LocTy ArgLoc;
2675 Type *ArgTy = nullptr;
2676 AttrBuilder ArgAttrs;
2677 Value *V;
2678 if (parseType(ArgTy, ArgLoc))
2679 return true;
2680
2681 if (ArgTy->isMetadataTy()) {
2682 if (parseMetadataAsValue(V, PFS))
2683 return true;
2684 } else {
2685 // Otherwise, handle normal operands.
2686 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2687 return true;
2688 }
2689 ArgList.push_back(ParamInfo(
2690 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2691 }
2692
2693 if (IsMustTailCall && InVarArgsFunc)
2694 return tokError("expected '...' at end of argument list for musttail call "
2695 "in varargs function");
2696
2697 Lex.Lex(); // Lex the ')'.
2698 return false;
2699}
2700
2701/// parseRequiredTypeAttr
2702/// ::= attrname(<ty>)
2703bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) {
2704 Result = nullptr;
2705 if (!EatIfPresent(AttrName))
2706 return true;
2707 if (!EatIfPresent(lltok::lparen))
2708 return error(Lex.getLoc(), "expected '('");
2709 if (parseType(Result))
2710 return true;
2711 if (!EatIfPresent(lltok::rparen))
2712 return error(Lex.getLoc(), "expected ')'");
2713 return false;
2714}
2715
2716/// parsePreallocated
2717/// ::= preallocated(<ty>)
2718bool LLParser::parsePreallocated(Type *&Result) {
2719 return parseRequiredTypeAttr(Result, lltok::kw_preallocated);
2720}
2721
2722/// parseInalloca
2723/// ::= inalloca(<ty>)
2724bool LLParser::parseInalloca(Type *&Result) {
2725 return parseRequiredTypeAttr(Result, lltok::kw_inalloca);
2726}
2727
2728/// parseByRef
2729/// ::= byref(<type>)
2730bool LLParser::parseByRef(Type *&Result) {
2731 return parseRequiredTypeAttr(Result, lltok::kw_byref);
2732}
2733
2734/// parseOptionalOperandBundles
2735/// ::= /*empty*/
2736/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2737///
2738/// OperandBundle
2739/// ::= bundle-tag '(' ')'
2740/// ::= bundle-tag '(' Type Value [, Typ