1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This class implements the parser for assembly files.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/Dwarf.h"
25 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeView.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDirectives.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCParser/AsmCond.h"
37 #include "llvm/MC/MCParser/AsmLexer.h"
38 #include "llvm/MC/MCParser/MCAsmLexer.h"
39 #include "llvm/MC/MCParser/MCAsmParser.h"
40 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
41 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
42 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
43 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/MC/MCSection.h"
46 #include "llvm/MC/MCStreamer.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/MC/MCTargetOptions.h"
49 #include "llvm/MC/MCValue.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MD5.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/SMLoc.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/raw_ostream.h"
75 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
77 static cl::opt
<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden
,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
83 /// Helper types for tracking macro definitions.
84 typedef std::vector
<AsmToken
> MCAsmMacroArgument
;
85 typedef std::vector
<MCAsmMacroArgument
> MCAsmMacroArguments
;
87 /// Helper class for storing information about an active macro
89 struct MacroInstantiation
{
90 /// The location of the instantiation.
91 SMLoc InstantiationLoc
;
93 /// The buffer where parsing should resume upon instantiation completion.
96 /// The location where parsing should resume upon instantiation completion.
99 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth
;
103 MacroInstantiation(SMLoc IL
, int EB
, SMLoc EL
, size_t CondStackDepth
);
106 struct ParseStatementInfo
{
107 /// The parsed operands from the last parsed statement.
108 SmallVector
<std::unique_ptr
<MCParsedAsmOperand
>, 8> ParsedOperands
;
110 /// The opcode from the last parsed instruction.
111 unsigned Opcode
= ~0U;
113 /// Was there an error parsing the inline assembly?
114 bool ParseError
= false;
116 SmallVectorImpl
<AsmRewrite
> *AsmRewrites
= nullptr;
118 ParseStatementInfo() = delete;
119 ParseStatementInfo(SmallVectorImpl
<AsmRewrite
> *rewrites
)
120 : AsmRewrites(rewrites
) {}
123 /// The concrete assembly parser instance.
124 class AsmParser
: public MCAsmParser
{
129 const MCAsmInfo
&MAI
;
131 SourceMgr::DiagHandlerTy SavedDiagHandler
;
132 void *SavedDiagContext
;
133 std::unique_ptr
<MCAsmParserExtension
> PlatformParser
;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState
;
140 std::vector
<AsmCond
> TheCondStack
;
142 /// maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap
<ExtensionDirectiveHandler
> ExtensionDirectiveMap
;
147 /// Stack of active macro instantiations.
148 std::vector
<MacroInstantiation
*> ActiveMacros
;
150 /// List of bodies of anonymous macros.
151 std::deque
<MCAsmMacro
> MacroLikeBodies
;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabledFlag
: 1;
156 /// Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations
;
159 /// The values from the last parsed cpp hash file line comment if any.
160 struct CppHashInfoTy
{
165 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {}
167 CppHashInfoTy CppHashInfo
;
169 /// The filename from the first cpp hash file line comment, if any.
170 StringRef FirstCppHashFilename
;
172 /// List of forward directional labels for diagnosis at the end.
173 SmallVector
<std::tuple
<SMLoc
, CppHashInfoTy
, MCSymbol
*>, 4> DirLabels
;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect
= ~0U;
178 /// is Darwin compatibility enabled?
179 bool IsDarwin
= false;
181 /// Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm
= false;
184 /// Did we already inform the user about inconsistent MD5 usage?
185 bool ReportedInconsistentMD5
= false;
187 // Is alt macro mode enabled.
188 bool AltMacroMode
= false;
191 AsmParser(SourceMgr
&SM
, MCContext
&Ctx
, MCStreamer
&Out
,
192 const MCAsmInfo
&MAI
, unsigned CB
);
193 AsmParser(const AsmParser
&) = delete;
194 AsmParser
&operator=(const AsmParser
&) = delete;
195 ~AsmParser() override
;
197 bool Run(bool NoInitialTextSection
, bool NoFinalize
= false) override
;
199 void addDirectiveHandler(StringRef Directive
,
200 ExtensionDirectiveHandler Handler
) override
{
201 ExtensionDirectiveMap
[Directive
] = Handler
;
204 void addAliasForDirective(StringRef Directive
, StringRef Alias
) override
{
205 DirectiveKindMap
[Directive
] = DirectiveKindMap
[Alias
];
208 /// @name MCAsmParser Interface
211 SourceMgr
&getSourceManager() override
{ return SrcMgr
; }
212 MCAsmLexer
&getLexer() override
{ return Lexer
; }
213 MCContext
&getContext() override
{ return Ctx
; }
214 MCStreamer
&getStreamer() override
{ return Out
; }
216 CodeViewContext
&getCVContext() { return Ctx
.getCVContext(); }
218 unsigned getAssemblerDialect() override
{
219 if (AssemblerDialect
== ~0U)
220 return MAI
.getAssemblerDialect();
222 return AssemblerDialect
;
224 void setAssemblerDialect(unsigned i
) override
{
225 AssemblerDialect
= i
;
228 void Note(SMLoc L
, const Twine
&Msg
, SMRange Range
= None
) override
;
229 bool Warning(SMLoc L
, const Twine
&Msg
, SMRange Range
= None
) override
;
230 bool printError(SMLoc L
, const Twine
&Msg
, SMRange Range
= None
) override
;
232 const AsmToken
&Lex() override
;
234 void setParsingInlineAsm(bool V
) override
{
235 ParsingInlineAsm
= V
;
236 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
237 // hex integer literals.
238 Lexer
.setLexMasmIntegers(V
);
240 bool isParsingInlineAsm() override
{ return ParsingInlineAsm
; }
242 bool parseMSInlineAsm(void *AsmLoc
, std::string
&AsmString
,
243 unsigned &NumOutputs
, unsigned &NumInputs
,
244 SmallVectorImpl
<std::pair
<void *,bool>> &OpDecls
,
245 SmallVectorImpl
<std::string
> &Constraints
,
246 SmallVectorImpl
<std::string
> &Clobbers
,
247 const MCInstrInfo
*MII
, const MCInstPrinter
*IP
,
248 MCAsmParserSemaCallback
&SI
) override
;
250 bool parseExpression(const MCExpr
*&Res
);
251 bool parseExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) override
;
252 bool parsePrimaryExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) override
;
253 bool parseParenExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) override
;
254 bool parseParenExprOfDepth(unsigned ParenDepth
, const MCExpr
*&Res
,
255 SMLoc
&EndLoc
) override
;
256 bool parseAbsoluteExpression(int64_t &Res
) override
;
258 /// Parse a floating point expression using the float \p Semantics
259 /// and set \p Res to the value.
260 bool parseRealValue(const fltSemantics
&Semantics
, APInt
&Res
);
262 /// Parse an identifier or string (as a quoted identifier)
263 /// and set \p Res to the identifier contents.
264 bool parseIdentifier(StringRef
&Res
) override
;
265 void eatToEndOfStatement() override
;
267 bool checkForValidSection() override
;
272 bool parseStatement(ParseStatementInfo
&Info
,
273 MCAsmParserSemaCallback
*SI
);
274 bool parseCurlyBlockScope(SmallVectorImpl
<AsmRewrite
>& AsmStrRewrites
);
275 bool parseCppHashLineFilenameComment(SMLoc L
);
277 void checkForBadMacro(SMLoc DirectiveLoc
, StringRef Name
, StringRef Body
,
278 ArrayRef
<MCAsmMacroParameter
> Parameters
);
279 bool expandMacro(raw_svector_ostream
&OS
, StringRef Body
,
280 ArrayRef
<MCAsmMacroParameter
> Parameters
,
281 ArrayRef
<MCAsmMacroArgument
> A
, bool EnableAtPseudoVariable
,
284 /// Are macros enabled in the parser?
285 bool areMacrosEnabled() {return MacrosEnabledFlag
;}
287 /// Control a flag in the parser that enables or disables macros.
288 void setMacrosEnabled(bool Flag
) {MacrosEnabledFlag
= Flag
;}
290 /// Are we inside a macro instantiation?
291 bool isInsideMacroInstantiation() {return !ActiveMacros
.empty();}
293 /// Handle entry to macro instantiation.
295 /// \param M The macro.
296 /// \param NameLoc Instantiation location.
297 bool handleMacroEntry(const MCAsmMacro
*M
, SMLoc NameLoc
);
299 /// Handle exit from macro instantiation.
300 void handleMacroExit();
302 /// Extract AsmTokens for a macro argument.
303 bool parseMacroArgument(MCAsmMacroArgument
&MA
, bool Vararg
);
305 /// Parse all macro arguments for a given macro.
306 bool parseMacroArguments(const MCAsmMacro
*M
, MCAsmMacroArguments
&A
);
308 void printMacroInstantiations();
309 void printMessage(SMLoc Loc
, SourceMgr::DiagKind Kind
, const Twine
&Msg
,
310 SMRange Range
= None
) const {
311 ArrayRef
<SMRange
> Ranges(Range
);
312 SrcMgr
.PrintMessage(Loc
, Kind
, Msg
, Ranges
);
314 static void DiagHandler(const SMDiagnostic
&Diag
, void *Context
);
316 /// Should we emit DWARF describing this assembler source? (Returns false if
317 /// the source has .file directives, which means we don't want to generate
318 /// info describing the assembler source itself.)
319 bool enabledGenDwarfForAssembly();
321 /// Enter the specified file. This returns true on failure.
322 bool enterIncludeFile(const std::string
&Filename
);
324 /// Process the specified file for the .incbin directive.
325 /// This returns true on failure.
326 bool processIncbinFile(const std::string
&Filename
, int64_t Skip
= 0,
327 const MCExpr
*Count
= nullptr, SMLoc Loc
= SMLoc());
329 /// Reset the current lexer position to that given by \p Loc. The
330 /// current token is not set; clients should ensure Lex() is called
333 /// \param InBuffer If not 0, should be the known buffer id that contains the
335 void jumpToLoc(SMLoc Loc
, unsigned InBuffer
= 0);
337 /// Parse up to the end of statement and a return the contents from the
338 /// current token until the end of the statement; the current token on exit
339 /// will be either the EndOfStatement or EOF.
340 StringRef
parseStringToEndOfStatement() override
;
342 /// Parse until the end of a statement or a comma is encountered,
343 /// return the contents from the current token up to the end or comma.
344 StringRef
parseStringToComma();
346 bool parseAssignment(StringRef Name
, bool allow_redef
,
347 bool NoDeadStrip
= false);
349 unsigned getBinOpPrecedence(AsmToken::TokenKind K
,
350 MCBinaryExpr::Opcode
&Kind
);
352 bool parseBinOpRHS(unsigned Precedence
, const MCExpr
*&Res
, SMLoc
&EndLoc
);
353 bool parseParenExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
);
354 bool parseBracketExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
);
356 bool parseRegisterOrRegisterNumber(int64_t &Register
, SMLoc DirectiveLoc
);
358 bool parseCVFunctionId(int64_t &FunctionId
, StringRef DirectiveName
);
359 bool parseCVFileId(int64_t &FileId
, StringRef DirectiveName
);
361 // Generic (target and platform independent) directive parsing.
363 DK_NO_DIRECTIVE
, // Placeholder
418 DK_BUNDLE_ALIGN_MODE
,
432 DK_WEAK_DEF_CAN_BE_HIDDEN
,
472 DK_CV_INLINE_SITE_ID
,
475 DK_CV_INLINE_LINETABLE
,
480 DK_CV_FILECHECKSUM_OFFSET
,
486 DK_CFI_DEF_CFA_OFFSET
,
487 DK_CFI_ADJUST_CFA_OFFSET
,
488 DK_CFI_DEF_CFA_REGISTER
,
493 DK_CFI_REMEMBER_STATE
,
494 DK_CFI_RESTORE_STATE
,
498 DK_CFI_RETURN_COLUMN
,
524 /// Maps directive name --> DirectiveKind enum, for
525 /// directives parsed by this class.
526 StringMap
<DirectiveKind
> DirectiveKindMap
;
528 // Codeview def_range type parsing.
529 enum CVDefRangeType
{
530 CVDR_DEFRANGE
= 0, // Placeholder
531 CVDR_DEFRANGE_REGISTER
,
532 CVDR_DEFRANGE_FRAMEPOINTER_REL
,
533 CVDR_DEFRANGE_SUBFIELD_REGISTER
,
534 CVDR_DEFRANGE_REGISTER_REL
537 /// Maps Codeview def_range types --> CVDefRangeType enum, for
538 /// Codeview def_range types parsed by this class.
539 StringMap
<CVDefRangeType
> CVDefRangeTypeMap
;
541 // ".ascii", ".asciz", ".string"
542 bool parseDirectiveAscii(StringRef IDVal
, bool ZeroTerminated
);
543 bool parseDirectiveReloc(SMLoc DirectiveLoc
); // ".reloc"
544 bool parseDirectiveValue(StringRef IDVal
,
545 unsigned Size
); // ".byte", ".long", ...
546 bool parseDirectiveOctaValue(StringRef IDVal
); // ".octa", ...
547 bool parseDirectiveRealValue(StringRef IDVal
,
548 const fltSemantics
&); // ".single", ...
549 bool parseDirectiveFill(); // ".fill"
550 bool parseDirectiveZero(); // ".zero"
551 // ".set", ".equ", ".equiv"
552 bool parseDirectiveSet(StringRef IDVal
, bool allow_redef
);
553 bool parseDirectiveOrg(); // ".org"
554 // ".align{,32}", ".p2align{,w,l}"
555 bool parseDirectiveAlign(bool IsPow2
, unsigned ValueSize
);
557 // ".file", ".line", ".loc", ".stabs"
558 bool parseDirectiveFile(SMLoc DirectiveLoc
);
559 bool parseDirectiveLine();
560 bool parseDirectiveLoc();
561 bool parseDirectiveStabs();
563 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
564 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
565 bool parseDirectiveCVFile();
566 bool parseDirectiveCVFuncId();
567 bool parseDirectiveCVInlineSiteId();
568 bool parseDirectiveCVLoc();
569 bool parseDirectiveCVLinetable();
570 bool parseDirectiveCVInlineLinetable();
571 bool parseDirectiveCVDefRange();
572 bool parseDirectiveCVString();
573 bool parseDirectiveCVStringTable();
574 bool parseDirectiveCVFileChecksums();
575 bool parseDirectiveCVFileChecksumOffset();
576 bool parseDirectiveCVFPOData();
579 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc
);
580 bool parseDirectiveCFIWindowSave();
581 bool parseDirectiveCFISections();
582 bool parseDirectiveCFIStartProc();
583 bool parseDirectiveCFIEndProc();
584 bool parseDirectiveCFIDefCfaOffset();
585 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc
);
586 bool parseDirectiveCFIAdjustCfaOffset();
587 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc
);
588 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc
);
589 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc
);
590 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality
);
591 bool parseDirectiveCFIRememberState();
592 bool parseDirectiveCFIRestoreState();
593 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc
);
594 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc
);
595 bool parseDirectiveCFIEscape();
596 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc
);
597 bool parseDirectiveCFISignalFrame();
598 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc
);
601 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc
);
602 bool parseDirectiveExitMacro(StringRef Directive
);
603 bool parseDirectiveEndMacro(StringRef Directive
);
604 bool parseDirectiveMacro(SMLoc DirectiveLoc
);
605 bool parseDirectiveMacrosOnOff(StringRef Directive
);
606 // alternate macro mode directives
607 bool parseDirectiveAltmacro(StringRef Directive
);
608 // ".bundle_align_mode"
609 bool parseDirectiveBundleAlignMode();
611 bool parseDirectiveBundleLock();
613 bool parseDirectiveBundleUnlock();
616 bool parseDirectiveSpace(StringRef IDVal
);
619 bool parseDirectiveDCB(StringRef IDVal
, unsigned Size
);
620 bool parseDirectiveRealDCB(StringRef IDVal
, const fltSemantics
&);
622 bool parseDirectiveDS(StringRef IDVal
, unsigned Size
);
624 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
625 bool parseDirectiveLEB128(bool Signed
);
627 /// Parse a directive like ".globl" which
628 /// accepts a single symbol (which should be a label or an external).
629 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr
);
631 bool parseDirectiveComm(bool IsLocal
); // ".comm" and ".lcomm"
633 bool parseDirectiveAbort(); // ".abort"
634 bool parseDirectiveInclude(); // ".include"
635 bool parseDirectiveIncbin(); // ".incbin"
637 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
638 bool parseDirectiveIf(SMLoc DirectiveLoc
, DirectiveKind DirKind
);
639 // ".ifb" or ".ifnb", depending on ExpectBlank.
640 bool parseDirectiveIfb(SMLoc DirectiveLoc
, bool ExpectBlank
);
641 // ".ifc" or ".ifnc", depending on ExpectEqual.
642 bool parseDirectiveIfc(SMLoc DirectiveLoc
, bool ExpectEqual
);
643 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
644 bool parseDirectiveIfeqs(SMLoc DirectiveLoc
, bool ExpectEqual
);
645 // ".ifdef" or ".ifndef", depending on expect_defined
646 bool parseDirectiveIfdef(SMLoc DirectiveLoc
, bool expect_defined
);
647 bool parseDirectiveElseIf(SMLoc DirectiveLoc
); // ".elseif"
648 bool parseDirectiveElse(SMLoc DirectiveLoc
); // ".else"
649 bool parseDirectiveEndIf(SMLoc DirectiveLoc
); // .endif
650 bool parseEscapedString(std::string
&Data
) override
;
652 const MCExpr
*applyModifierToExpr(const MCExpr
*E
,
653 MCSymbolRefExpr::VariantKind Variant
);
655 // Macro-like directives
656 MCAsmMacro
*parseMacroLikeBody(SMLoc DirectiveLoc
);
657 void instantiateMacroLikeBody(MCAsmMacro
*M
, SMLoc DirectiveLoc
,
658 raw_svector_ostream
&OS
);
659 bool parseDirectiveRept(SMLoc DirectiveLoc
, StringRef Directive
);
660 bool parseDirectiveIrp(SMLoc DirectiveLoc
); // ".irp"
661 bool parseDirectiveIrpc(SMLoc DirectiveLoc
); // ".irpc"
662 bool parseDirectiveEndr(SMLoc DirectiveLoc
); // ".endr"
664 // "_emit" or "__emit"
665 bool parseDirectiveMSEmit(SMLoc DirectiveLoc
, ParseStatementInfo
&Info
,
669 bool parseDirectiveMSAlign(SMLoc DirectiveLoc
, ParseStatementInfo
&Info
);
672 bool parseDirectiveEnd(SMLoc DirectiveLoc
);
674 // ".err" or ".error"
675 bool parseDirectiveError(SMLoc DirectiveLoc
, bool WithMessage
);
678 bool parseDirectiveWarning(SMLoc DirectiveLoc
);
680 // .print <double-quotes-string>
681 bool parseDirectivePrint(SMLoc DirectiveLoc
);
683 // Directives to support address-significance tables.
684 bool parseDirectiveAddrsig();
685 bool parseDirectiveAddrsigSym();
687 void initializeDirectiveKindMap();
688 void initializeCVDefRangeTypeMap();
691 } // end anonymous namespace
695 extern MCAsmParserExtension
*createDarwinAsmParser();
696 extern MCAsmParserExtension
*createELFAsmParser();
697 extern MCAsmParserExtension
*createCOFFAsmParser();
698 extern MCAsmParserExtension
*createWasmAsmParser();
700 } // end namespace llvm
702 enum { DEFAULT_ADDRSPACE
= 0 };
704 AsmParser::AsmParser(SourceMgr
&SM
, MCContext
&Ctx
, MCStreamer
&Out
,
705 const MCAsmInfo
&MAI
, unsigned CB
= 0)
706 : Lexer(MAI
), Ctx(Ctx
), Out(Out
), MAI(MAI
), SrcMgr(SM
),
707 CurBuffer(CB
? CB
: SM
.getMainFileID()), MacrosEnabledFlag(true) {
709 // Save the old handler.
710 SavedDiagHandler
= SrcMgr
.getDiagHandler();
711 SavedDiagContext
= SrcMgr
.getDiagContext();
712 // Set our own handler which calls the saved handler.
713 SrcMgr
.setDiagHandler(DiagHandler
, this);
714 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
716 // Initialize the platform / file format parser.
717 switch (Ctx
.getObjectFileInfo()->getObjectFileType()) {
718 case MCObjectFileInfo::IsCOFF
:
719 PlatformParser
.reset(createCOFFAsmParser());
721 case MCObjectFileInfo::IsMachO
:
722 PlatformParser
.reset(createDarwinAsmParser());
725 case MCObjectFileInfo::IsELF
:
726 PlatformParser
.reset(createELFAsmParser());
728 case MCObjectFileInfo::IsWasm
:
729 PlatformParser
.reset(createWasmAsmParser());
731 case MCObjectFileInfo::IsXCOFF
:
733 "Need to implement createXCOFFAsmParser for XCOFF format.");
737 PlatformParser
->Initialize(*this);
738 initializeDirectiveKindMap();
739 initializeCVDefRangeTypeMap();
741 NumOfMacroInstantiations
= 0;
744 AsmParser::~AsmParser() {
745 assert((HadError
|| ActiveMacros
.empty()) &&
746 "Unexpected active macro instantiation!");
748 // Restore the saved diagnostics handler and context for use during
750 SrcMgr
.setDiagHandler(SavedDiagHandler
, SavedDiagContext
);
753 void AsmParser::printMacroInstantiations() {
754 // Print the active macro instantiation stack.
755 for (std::vector
<MacroInstantiation
*>::const_reverse_iterator
756 it
= ActiveMacros
.rbegin(),
757 ie
= ActiveMacros
.rend();
759 printMessage((*it
)->InstantiationLoc
, SourceMgr::DK_Note
,
760 "while in macro instantiation");
763 void AsmParser::Note(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
764 printPendingErrors();
765 printMessage(L
, SourceMgr::DK_Note
, Msg
, Range
);
766 printMacroInstantiations();
769 bool AsmParser::Warning(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
770 if(getTargetParser().getTargetOptions().MCNoWarn
)
772 if (getTargetParser().getTargetOptions().MCFatalWarnings
)
773 return Error(L
, Msg
, Range
);
774 printMessage(L
, SourceMgr::DK_Warning
, Msg
, Range
);
775 printMacroInstantiations();
779 bool AsmParser::printError(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
781 printMessage(L
, SourceMgr::DK_Error
, Msg
, Range
);
782 printMacroInstantiations();
786 bool AsmParser::enterIncludeFile(const std::string
&Filename
) {
787 std::string IncludedFile
;
789 SrcMgr
.AddIncludeFile(Filename
, Lexer
.getLoc(), IncludedFile
);
794 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
798 /// Process the specified .incbin file by searching for it in the include paths
799 /// then just emitting the byte contents of the file to the streamer. This
800 /// returns true on failure.
801 bool AsmParser::processIncbinFile(const std::string
&Filename
, int64_t Skip
,
802 const MCExpr
*Count
, SMLoc Loc
) {
803 std::string IncludedFile
;
805 SrcMgr
.AddIncludeFile(Filename
, Lexer
.getLoc(), IncludedFile
);
809 // Pick up the bytes from the file and emit them.
810 StringRef Bytes
= SrcMgr
.getMemoryBuffer(NewBuf
)->getBuffer();
811 Bytes
= Bytes
.drop_front(Skip
);
814 if (!Count
->evaluateAsAbsolute(Res
, getStreamer().getAssemblerPtr()))
815 return Error(Loc
, "expected absolute expression");
817 return Warning(Loc
, "negative count has no effect");
818 Bytes
= Bytes
.take_front(Res
);
820 getStreamer().EmitBytes(Bytes
);
824 void AsmParser::jumpToLoc(SMLoc Loc
, unsigned InBuffer
) {
825 CurBuffer
= InBuffer
? InBuffer
: SrcMgr
.FindBufferContainingLoc(Loc
);
826 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer(),
830 const AsmToken
&AsmParser::Lex() {
831 if (Lexer
.getTok().is(AsmToken::Error
))
832 Error(Lexer
.getErrLoc(), Lexer
.getErr());
834 // if it's a end of statement with a comment in it
835 if (getTok().is(AsmToken::EndOfStatement
)) {
836 // if this is a line comment output it.
837 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
838 getTok().getString().front() != '\r' && MAI
.preserveAsmComments())
839 Out
.addExplicitComment(Twine(getTok().getString()));
842 const AsmToken
*tok
= &Lexer
.Lex();
844 // Parse comments here to be deferred until end of next statement.
845 while (tok
->is(AsmToken::Comment
)) {
846 if (MAI
.preserveAsmComments())
847 Out
.addExplicitComment(Twine(tok
->getString()));
851 if (tok
->is(AsmToken::Eof
)) {
852 // If this is the end of an included file, pop the parent file off the
854 SMLoc ParentIncludeLoc
= SrcMgr
.getParentIncludeLoc(CurBuffer
);
855 if (ParentIncludeLoc
!= SMLoc()) {
856 jumpToLoc(ParentIncludeLoc
);
864 bool AsmParser::enabledGenDwarfForAssembly() {
865 // Check whether the user specified -g.
866 if (!getContext().getGenDwarfForAssembly())
868 // If we haven't encountered any .file directives (which would imply that
869 // the assembler source was produced with debug info already) then emit one
870 // describing the assembler source file itself.
871 if (getContext().getGenDwarfFileNumber() == 0) {
872 // Use the first #line directive for this, if any. It's preprocessed, so
873 // there is no checksum, and of course no source directive.
874 if (!FirstCppHashFilename
.empty())
875 getContext().setMCLineTableRootFile(/*CUID=*/0,
876 getContext().getCompilationDir(),
877 FirstCppHashFilename
,
878 /*Cksum=*/None
, /*Source=*/None
);
879 const MCDwarfFile
&RootFile
=
880 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
881 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
882 /*CUID=*/0, getContext().getCompilationDir(), RootFile
.Name
,
883 RootFile
.Checksum
, RootFile
.Source
));
888 bool AsmParser::Run(bool NoInitialTextSection
, bool NoFinalize
) {
889 // Create the initial section, if requested.
890 if (!NoInitialTextSection
)
891 Out
.InitSections(false);
897 AsmCond StartingCondState
= TheCondState
;
898 SmallVector
<AsmRewrite
, 4> AsmStrRewrites
;
900 // If we are generating dwarf for assembly source files save the initial text
901 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
902 // emitting any actual debug info yet and haven't had a chance to parse any
903 // embedded .file directives.)
904 if (getContext().getGenDwarfForAssembly()) {
905 MCSection
*Sec
= getStreamer().getCurrentSectionOnly();
906 if (!Sec
->getBeginSymbol()) {
907 MCSymbol
*SectionStartSym
= getContext().createTempSymbol();
908 getStreamer().EmitLabel(SectionStartSym
);
909 Sec
->setBeginSymbol(SectionStartSym
);
911 bool InsertResult
= getContext().addGenDwarfSection(Sec
);
912 assert(InsertResult
&& ".text section should not have debug info yet");
916 // While we have input, parse each statement.
917 while (Lexer
.isNot(AsmToken::Eof
)) {
918 ParseStatementInfo
Info(&AsmStrRewrites
);
919 if (!parseStatement(Info
, nullptr))
922 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
923 // for printing ErrMsg via Lex() only if no (presumably better) parser error
925 if (!hasPendingError() && Lexer
.getTok().is(AsmToken::Error
)) {
929 // parseStatement returned true so may need to emit an error.
930 printPendingErrors();
932 // Skipping to the next line if needed.
933 if (!getLexer().isAtStartOfStatement())
934 eatToEndOfStatement();
937 getTargetParser().onEndOfFile();
938 printPendingErrors();
940 // All errors should have been emitted.
941 assert(!hasPendingError() && "unexpected error from parseStatement");
943 getTargetParser().flushPendingInstructions(getStreamer());
945 if (TheCondState
.TheCond
!= StartingCondState
.TheCond
||
946 TheCondState
.Ignore
!= StartingCondState
.Ignore
)
947 printError(getTok().getLoc(), "unmatched .ifs or .elses");
948 // Check to see there are no empty DwarfFile slots.
949 const auto &LineTables
= getContext().getMCDwarfLineTables();
950 if (!LineTables
.empty()) {
952 for (const auto &File
: LineTables
.begin()->second
.getMCDwarfFiles()) {
953 if (File
.Name
.empty() && Index
!= 0)
954 printError(getTok().getLoc(), "unassigned file number: " +
956 " for .file directives");
961 // Check to see that all assembler local symbols were actually defined.
962 // Targets that don't do subsections via symbols may not want this, though,
963 // so conservatively exclude them. Only do this if we're finalizing, though,
964 // as otherwise we won't necessarilly have seen everything yet.
966 if (MAI
.hasSubsectionsViaSymbols()) {
967 for (const auto &TableEntry
: getContext().getSymbols()) {
968 MCSymbol
*Sym
= TableEntry
.getValue();
969 // Variable symbols may not be marked as defined, so check those
970 // explicitly. If we know it's a variable, we have a definition for
971 // the purposes of this check.
972 if (Sym
->isTemporary() && !Sym
->isVariable() && !Sym
->isDefined())
973 // FIXME: We would really like to refer back to where the symbol was
974 // first referenced for a source location. We need to add something
975 // to track that. Currently, we just point to the end of the file.
976 printError(getTok().getLoc(), "assembler local symbol '" +
977 Sym
->getName() + "' not defined");
981 // Temporary symbols like the ones for directional jumps don't go in the
982 // symbol table. They also need to be diagnosed in all (final) cases.
983 for (std::tuple
<SMLoc
, CppHashInfoTy
, MCSymbol
*> &LocSym
: DirLabels
) {
984 if (std::get
<2>(LocSym
)->isUndefined()) {
985 // Reset the state of any "# line file" directives we've seen to the
986 // context as it was at the diagnostic site.
987 CppHashInfo
= std::get
<1>(LocSym
);
988 printError(std::get
<0>(LocSym
), "directional label undefined");
993 // Finalize the output stream if there are no errors and if the client wants
995 if (!HadError
&& !NoFinalize
)
998 return HadError
|| getContext().hadError();
1001 bool AsmParser::checkForValidSection() {
1002 if (!ParsingInlineAsm
&& !getStreamer().getCurrentSectionOnly()) {
1003 Out
.InitSections(false);
1004 return Error(getTok().getLoc(),
1005 "expected section directive before assembly directive");
1010 /// Throw away the rest of the line for testing purposes.
1011 void AsmParser::eatToEndOfStatement() {
1012 while (Lexer
.isNot(AsmToken::EndOfStatement
) && Lexer
.isNot(AsmToken::Eof
))
1016 if (Lexer
.is(AsmToken::EndOfStatement
))
1020 StringRef
AsmParser::parseStringToEndOfStatement() {
1021 const char *Start
= getTok().getLoc().getPointer();
1023 while (Lexer
.isNot(AsmToken::EndOfStatement
) && Lexer
.isNot(AsmToken::Eof
))
1026 const char *End
= getTok().getLoc().getPointer();
1027 return StringRef(Start
, End
- Start
);
1030 StringRef
AsmParser::parseStringToComma() {
1031 const char *Start
= getTok().getLoc().getPointer();
1033 while (Lexer
.isNot(AsmToken::EndOfStatement
) &&
1034 Lexer
.isNot(AsmToken::Comma
) && Lexer
.isNot(AsmToken::Eof
))
1037 const char *End
= getTok().getLoc().getPointer();
1038 return StringRef(Start
, End
- Start
);
1041 /// Parse a paren expression and return it.
1042 /// NOTE: This assumes the leading '(' has already been consumed.
1044 /// parenexpr ::= expr)
1046 bool AsmParser::parseParenExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1047 if (parseExpression(Res
))
1049 if (Lexer
.isNot(AsmToken::RParen
))
1050 return TokError("expected ')' in parentheses expression");
1051 EndLoc
= Lexer
.getTok().getEndLoc();
1056 /// Parse a bracket expression and return it.
1057 /// NOTE: This assumes the leading '[' has already been consumed.
1059 /// bracketexpr ::= expr]
1061 bool AsmParser::parseBracketExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1062 if (parseExpression(Res
))
1064 EndLoc
= getTok().getEndLoc();
1065 if (parseToken(AsmToken::RBrac
, "expected ']' in brackets expression"))
1070 /// Parse a primary expression and return it.
1071 /// primaryexpr ::= (parenexpr
1072 /// primaryexpr ::= symbol
1073 /// primaryexpr ::= number
1074 /// primaryexpr ::= '.'
1075 /// primaryexpr ::= ~,+,- primaryexpr
1076 bool AsmParser::parsePrimaryExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1077 SMLoc FirstTokenLoc
= getLexer().getLoc();
1078 AsmToken::TokenKind FirstTokenKind
= Lexer
.getKind();
1079 switch (FirstTokenKind
) {
1081 return TokError("unknown token in expression");
1082 // If we have an error assume that we've already handled it.
1083 case AsmToken::Error
:
1085 case AsmToken::Exclaim
:
1086 Lex(); // Eat the operator.
1087 if (parsePrimaryExpr(Res
, EndLoc
))
1089 Res
= MCUnaryExpr::createLNot(Res
, getContext(), FirstTokenLoc
);
1091 case AsmToken::Dollar
:
1093 case AsmToken::String
:
1094 case AsmToken::Identifier
: {
1095 StringRef Identifier
;
1096 if (parseIdentifier(Identifier
)) {
1097 // We may have failed but $ may be a valid token.
1098 if (getTok().is(AsmToken::Dollar
)) {
1099 if (Lexer
.getMAI().getDollarIsPC()) {
1101 // This is a '$' reference, which references the current PC. Emit a
1102 // temporary label to the streamer and refer to it.
1103 MCSymbol
*Sym
= Ctx
.createTempSymbol();
1105 Res
= MCSymbolRefExpr::create(Sym
, MCSymbolRefExpr::VK_None
,
1107 EndLoc
= FirstTokenLoc
;
1110 return Error(FirstTokenLoc
, "invalid token in expression");
1113 // Parse symbol variant
1114 std::pair
<StringRef
, StringRef
> Split
;
1115 if (!MAI
.useParensForSymbolVariant()) {
1116 if (FirstTokenKind
== AsmToken::String
) {
1117 if (Lexer
.is(AsmToken::At
)) {
1119 SMLoc AtLoc
= getLexer().getLoc();
1121 if (parseIdentifier(VName
))
1122 return Error(AtLoc
, "expected symbol variant after '@'");
1124 Split
= std::make_pair(Identifier
, VName
);
1127 Split
= Identifier
.split('@');
1129 } else if (Lexer
.is(AsmToken::LParen
)) {
1132 parseIdentifier(VName
);
1134 if (parseToken(AsmToken::RParen
,
1135 "unexpected token in variant, expected ')'"))
1137 Split
= std::make_pair(Identifier
, VName
);
1140 EndLoc
= SMLoc::getFromPointer(Identifier
.end());
1142 // This is a symbol reference.
1143 StringRef SymbolName
= Identifier
;
1144 if (SymbolName
.empty())
1145 return Error(getLexer().getLoc(), "expected a symbol reference");
1147 MCSymbolRefExpr::VariantKind Variant
= MCSymbolRefExpr::VK_None
;
1149 // Lookup the symbol variant if used.
1150 if (!Split
.second
.empty()) {
1151 Variant
= MCSymbolRefExpr::getVariantKindForName(Split
.second
);
1152 if (Variant
!= MCSymbolRefExpr::VK_Invalid
) {
1153 SymbolName
= Split
.first
;
1154 } else if (MAI
.doesAllowAtInName() && !MAI
.useParensForSymbolVariant()) {
1155 Variant
= MCSymbolRefExpr::VK_None
;
1157 return Error(SMLoc::getFromPointer(Split
.second
.begin()),
1158 "invalid variant '" + Split
.second
+ "'");
1162 MCSymbol
*Sym
= getContext().getInlineAsmLabel(SymbolName
);
1164 Sym
= getContext().getOrCreateSymbol(SymbolName
);
1166 // If this is an absolute variable reference, substitute it now to preserve
1167 // semantics in the face of reassignment.
1168 if (Sym
->isVariable()) {
1169 auto V
= Sym
->getVariableValue(/*SetUsed*/ false);
1170 bool DoInline
= isa
<MCConstantExpr
>(V
) && !Variant
;
1171 if (auto TV
= dyn_cast
<MCTargetExpr
>(V
))
1172 DoInline
= TV
->inlineAssignedExpr();
1175 return Error(EndLoc
, "unexpected modifier on variable reference");
1176 Res
= Sym
->getVariableValue(/*SetUsed*/ false);
1181 // Otherwise create a symbol ref.
1182 Res
= MCSymbolRefExpr::create(Sym
, Variant
, getContext(), FirstTokenLoc
);
1185 case AsmToken::BigNum
:
1186 return TokError("literal value out of range for directive");
1187 case AsmToken::Integer
: {
1188 SMLoc Loc
= getTok().getLoc();
1189 int64_t IntVal
= getTok().getIntVal();
1190 Res
= MCConstantExpr::create(IntVal
, getContext());
1191 EndLoc
= Lexer
.getTok().getEndLoc();
1192 Lex(); // Eat token.
1193 // Look for 'b' or 'f' following an Integer as a directional label
1194 if (Lexer
.getKind() == AsmToken::Identifier
) {
1195 StringRef IDVal
= getTok().getString();
1196 // Lookup the symbol variant if used.
1197 std::pair
<StringRef
, StringRef
> Split
= IDVal
.split('@');
1198 MCSymbolRefExpr::VariantKind Variant
= MCSymbolRefExpr::VK_None
;
1199 if (Split
.first
.size() != IDVal
.size()) {
1200 Variant
= MCSymbolRefExpr::getVariantKindForName(Split
.second
);
1201 if (Variant
== MCSymbolRefExpr::VK_Invalid
)
1202 return TokError("invalid variant '" + Split
.second
+ "'");
1203 IDVal
= Split
.first
;
1205 if (IDVal
== "f" || IDVal
== "b") {
1207 Ctx
.getDirectionalLocalSymbol(IntVal
, IDVal
== "b");
1208 Res
= MCSymbolRefExpr::create(Sym
, Variant
, getContext());
1209 if (IDVal
== "b" && Sym
->isUndefined())
1210 return Error(Loc
, "directional label undefined");
1211 DirLabels
.push_back(std::make_tuple(Loc
, CppHashInfo
, Sym
));
1212 EndLoc
= Lexer
.getTok().getEndLoc();
1213 Lex(); // Eat identifier.
1218 case AsmToken::Real
: {
1219 APFloat
RealVal(APFloat::IEEEdouble(), getTok().getString());
1220 uint64_t IntVal
= RealVal
.bitcastToAPInt().getZExtValue();
1221 Res
= MCConstantExpr::create(IntVal
, getContext());
1222 EndLoc
= Lexer
.getTok().getEndLoc();
1223 Lex(); // Eat token.
1226 case AsmToken::Dot
: {
1227 // This is a '.' reference, which references the current PC. Emit a
1228 // temporary label to the streamer and refer to it.
1229 MCSymbol
*Sym
= Ctx
.createTempSymbol();
1231 Res
= MCSymbolRefExpr::create(Sym
, MCSymbolRefExpr::VK_None
, getContext());
1232 EndLoc
= Lexer
.getTok().getEndLoc();
1233 Lex(); // Eat identifier.
1236 case AsmToken::LParen
:
1237 Lex(); // Eat the '('.
1238 return parseParenExpr(Res
, EndLoc
);
1239 case AsmToken::LBrac
:
1240 if (!PlatformParser
->HasBracketExpressions())
1241 return TokError("brackets expression not supported on this target");
1242 Lex(); // Eat the '['.
1243 return parseBracketExpr(Res
, EndLoc
);
1244 case AsmToken::Minus
:
1245 Lex(); // Eat the operator.
1246 if (parsePrimaryExpr(Res
, EndLoc
))
1248 Res
= MCUnaryExpr::createMinus(Res
, getContext(), FirstTokenLoc
);
1250 case AsmToken::Plus
:
1251 Lex(); // Eat the operator.
1252 if (parsePrimaryExpr(Res
, EndLoc
))
1254 Res
= MCUnaryExpr::createPlus(Res
, getContext(), FirstTokenLoc
);
1256 case AsmToken::Tilde
:
1257 Lex(); // Eat the operator.
1258 if (parsePrimaryExpr(Res
, EndLoc
))
1260 Res
= MCUnaryExpr::createNot(Res
, getContext(), FirstTokenLoc
);
1262 // MIPS unary expression operators. The lexer won't generate these tokens if
1263 // MCAsmInfo::HasMipsExpressions is false for the target.
1264 case AsmToken::PercentCall16
:
1265 case AsmToken::PercentCall_Hi
:
1266 case AsmToken::PercentCall_Lo
:
1267 case AsmToken::PercentDtprel_Hi
:
1268 case AsmToken::PercentDtprel_Lo
:
1269 case AsmToken::PercentGot
:
1270 case AsmToken::PercentGot_Disp
:
1271 case AsmToken::PercentGot_Hi
:
1272 case AsmToken::PercentGot_Lo
:
1273 case AsmToken::PercentGot_Ofst
:
1274 case AsmToken::PercentGot_Page
:
1275 case AsmToken::PercentGottprel
:
1276 case AsmToken::PercentGp_Rel
:
1277 case AsmToken::PercentHi
:
1278 case AsmToken::PercentHigher
:
1279 case AsmToken::PercentHighest
:
1280 case AsmToken::PercentLo
:
1281 case AsmToken::PercentNeg
:
1282 case AsmToken::PercentPcrel_Hi
:
1283 case AsmToken::PercentPcrel_Lo
:
1284 case AsmToken::PercentTlsgd
:
1285 case AsmToken::PercentTlsldm
:
1286 case AsmToken::PercentTprel_Hi
:
1287 case AsmToken::PercentTprel_Lo
:
1288 Lex(); // Eat the operator.
1289 if (Lexer
.isNot(AsmToken::LParen
))
1290 return TokError("expected '(' after operator");
1291 Lex(); // Eat the operator.
1292 if (parseExpression(Res
, EndLoc
))
1294 if (Lexer
.isNot(AsmToken::RParen
))
1295 return TokError("expected ')'");
1296 Lex(); // Eat the operator.
1297 Res
= getTargetParser().createTargetUnaryExpr(Res
, FirstTokenKind
, Ctx
);
1302 bool AsmParser::parseExpression(const MCExpr
*&Res
) {
1304 return parseExpression(Res
, EndLoc
);
1308 AsmParser::applyModifierToExpr(const MCExpr
*E
,
1309 MCSymbolRefExpr::VariantKind Variant
) {
1310 // Ask the target implementation about this expression first.
1311 const MCExpr
*NewE
= getTargetParser().applyModifierToExpr(E
, Variant
, Ctx
);
1314 // Recurse over the given expression, rebuilding it to apply the given variant
1315 // if there is exactly one symbol.
1316 switch (E
->getKind()) {
1317 case MCExpr::Target
:
1318 case MCExpr::Constant
:
1321 case MCExpr::SymbolRef
: {
1322 const MCSymbolRefExpr
*SRE
= cast
<MCSymbolRefExpr
>(E
);
1324 if (SRE
->getKind() != MCSymbolRefExpr::VK_None
) {
1325 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1326 "' (already modified)");
1330 return MCSymbolRefExpr::create(&SRE
->getSymbol(), Variant
, getContext());
1333 case MCExpr::Unary
: {
1334 const MCUnaryExpr
*UE
= cast
<MCUnaryExpr
>(E
);
1335 const MCExpr
*Sub
= applyModifierToExpr(UE
->getSubExpr(), Variant
);
1338 return MCUnaryExpr::create(UE
->getOpcode(), Sub
, getContext());
1341 case MCExpr::Binary
: {
1342 const MCBinaryExpr
*BE
= cast
<MCBinaryExpr
>(E
);
1343 const MCExpr
*LHS
= applyModifierToExpr(BE
->getLHS(), Variant
);
1344 const MCExpr
*RHS
= applyModifierToExpr(BE
->getRHS(), Variant
);
1354 return MCBinaryExpr::create(BE
->getOpcode(), LHS
, RHS
, getContext());
1358 llvm_unreachable("Invalid expression kind!");
1361 /// This function checks if the next token is <string> type or arithmetic.
1362 /// string that begin with character '<' must end with character '>'.
1363 /// otherwise it is arithmetics.
1364 /// If the function returns a 'true' value,
1365 /// the End argument will be filled with the last location pointed to the '>'
1368 /// There is a gap between the AltMacro's documentation and the single quote
1369 /// implementation. GCC does not fully support this feature and so we will not
1371 /// TODO: Adding single quote as a string.
1372 static bool isAltmacroString(SMLoc
&StrLoc
, SMLoc
&EndLoc
) {
1373 assert((StrLoc
.getPointer() != nullptr) &&
1374 "Argument to the function cannot be a NULL value");
1375 const char *CharPtr
= StrLoc
.getPointer();
1376 while ((*CharPtr
!= '>') && (*CharPtr
!= '\n') && (*CharPtr
!= '\r') &&
1377 (*CharPtr
!= '\0')) {
1378 if (*CharPtr
== '!')
1382 if (*CharPtr
== '>') {
1383 EndLoc
= StrLoc
.getFromPointer(CharPtr
+ 1);
1389 /// creating a string without the escape characters '!'.
1390 static std::string
altMacroString(StringRef AltMacroStr
) {
1392 for (size_t Pos
= 0; Pos
< AltMacroStr
.size(); Pos
++) {
1393 if (AltMacroStr
[Pos
] == '!')
1395 Res
+= AltMacroStr
[Pos
];
1400 /// Parse an expression and return it.
1402 /// expr ::= expr &&,|| expr -> lowest.
1403 /// expr ::= expr |,^,&,! expr
1404 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1405 /// expr ::= expr <<,>> expr
1406 /// expr ::= expr +,- expr
1407 /// expr ::= expr *,/,% expr -> highest.
1408 /// expr ::= primaryexpr
1410 bool AsmParser::parseExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1411 // Parse the expression.
1413 if (getTargetParser().parsePrimaryExpr(Res
, EndLoc
) ||
1414 parseBinOpRHS(1, Res
, EndLoc
))
1417 // As a special case, we support 'a op b @ modifier' by rewriting the
1418 // expression to include the modifier. This is inefficient, but in general we
1419 // expect users to use 'a@modifier op b'.
1420 if (Lexer
.getKind() == AsmToken::At
) {
1423 if (Lexer
.isNot(AsmToken::Identifier
))
1424 return TokError("unexpected symbol modifier following '@'");
1426 MCSymbolRefExpr::VariantKind Variant
=
1427 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1428 if (Variant
== MCSymbolRefExpr::VK_Invalid
)
1429 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1431 const MCExpr
*ModifiedRes
= applyModifierToExpr(Res
, Variant
);
1433 return TokError("invalid modifier '" + getTok().getIdentifier() +
1434 "' (no symbols present)");
1441 // Try to constant fold it up front, if possible. Do not exploit
1444 if (Res
->evaluateAsAbsolute(Value
))
1445 Res
= MCConstantExpr::create(Value
, getContext());
1450 bool AsmParser::parseParenExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1452 return parseParenExpr(Res
, EndLoc
) || parseBinOpRHS(1, Res
, EndLoc
);
1455 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth
, const MCExpr
*&Res
,
1457 if (parseParenExpr(Res
, EndLoc
))
1460 for (; ParenDepth
> 0; --ParenDepth
) {
1461 if (parseBinOpRHS(1, Res
, EndLoc
))
1464 // We don't Lex() the last RParen.
1465 // This is the same behavior as parseParenExpression().
1466 if (ParenDepth
- 1 > 0) {
1467 EndLoc
= getTok().getEndLoc();
1468 if (parseToken(AsmToken::RParen
,
1469 "expected ')' in parentheses expression"))
1476 bool AsmParser::parseAbsoluteExpression(int64_t &Res
) {
1479 SMLoc StartLoc
= Lexer
.getLoc();
1480 if (parseExpression(Expr
))
1483 if (!Expr
->evaluateAsAbsolute(Res
, getStreamer().getAssemblerPtr()))
1484 return Error(StartLoc
, "expected absolute expression");
1489 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K
,
1490 MCBinaryExpr::Opcode
&Kind
,
1491 bool ShouldUseLogicalShr
) {
1494 return 0; // not a binop.
1496 // Lowest Precedence: &&, ||
1497 case AsmToken::AmpAmp
:
1498 Kind
= MCBinaryExpr::LAnd
;
1500 case AsmToken::PipePipe
:
1501 Kind
= MCBinaryExpr::LOr
;
1504 // Low Precedence: |, &, ^
1506 // FIXME: gas seems to support '!' as an infix operator?
1507 case AsmToken::Pipe
:
1508 Kind
= MCBinaryExpr::Or
;
1510 case AsmToken::Caret
:
1511 Kind
= MCBinaryExpr::Xor
;
1514 Kind
= MCBinaryExpr::And
;
1517 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1518 case AsmToken::EqualEqual
:
1519 Kind
= MCBinaryExpr::EQ
;
1521 case AsmToken::ExclaimEqual
:
1522 case AsmToken::LessGreater
:
1523 Kind
= MCBinaryExpr::NE
;
1525 case AsmToken::Less
:
1526 Kind
= MCBinaryExpr::LT
;
1528 case AsmToken::LessEqual
:
1529 Kind
= MCBinaryExpr::LTE
;
1531 case AsmToken::Greater
:
1532 Kind
= MCBinaryExpr::GT
;
1534 case AsmToken::GreaterEqual
:
1535 Kind
= MCBinaryExpr::GTE
;
1538 // Intermediate Precedence: <<, >>
1539 case AsmToken::LessLess
:
1540 Kind
= MCBinaryExpr::Shl
;
1542 case AsmToken::GreaterGreater
:
1543 Kind
= ShouldUseLogicalShr
? MCBinaryExpr::LShr
: MCBinaryExpr::AShr
;
1546 // High Intermediate Precedence: +, -
1547 case AsmToken::Plus
:
1548 Kind
= MCBinaryExpr::Add
;
1550 case AsmToken::Minus
:
1551 Kind
= MCBinaryExpr::Sub
;
1554 // Highest Precedence: *, /, %
1555 case AsmToken::Star
:
1556 Kind
= MCBinaryExpr::Mul
;
1558 case AsmToken::Slash
:
1559 Kind
= MCBinaryExpr::Div
;
1561 case AsmToken::Percent
:
1562 Kind
= MCBinaryExpr::Mod
;
1567 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K
,
1568 MCBinaryExpr::Opcode
&Kind
,
1569 bool ShouldUseLogicalShr
) {
1572 return 0; // not a binop.
1574 // Lowest Precedence: &&, ||
1575 case AsmToken::AmpAmp
:
1576 Kind
= MCBinaryExpr::LAnd
;
1578 case AsmToken::PipePipe
:
1579 Kind
= MCBinaryExpr::LOr
;
1582 // Low Precedence: ==, !=, <>, <, <=, >, >=
1583 case AsmToken::EqualEqual
:
1584 Kind
= MCBinaryExpr::EQ
;
1586 case AsmToken::ExclaimEqual
:
1587 case AsmToken::LessGreater
:
1588 Kind
= MCBinaryExpr::NE
;
1590 case AsmToken::Less
:
1591 Kind
= MCBinaryExpr::LT
;
1593 case AsmToken::LessEqual
:
1594 Kind
= MCBinaryExpr::LTE
;
1596 case AsmToken::Greater
:
1597 Kind
= MCBinaryExpr::GT
;
1599 case AsmToken::GreaterEqual
:
1600 Kind
= MCBinaryExpr::GTE
;
1603 // Low Intermediate Precedence: +, -
1604 case AsmToken::Plus
:
1605 Kind
= MCBinaryExpr::Add
;
1607 case AsmToken::Minus
:
1608 Kind
= MCBinaryExpr::Sub
;
1611 // High Intermediate Precedence: |, &, ^
1613 // FIXME: gas seems to support '!' as an infix operator?
1614 case AsmToken::Pipe
:
1615 Kind
= MCBinaryExpr::Or
;
1617 case AsmToken::Caret
:
1618 Kind
= MCBinaryExpr::Xor
;
1621 Kind
= MCBinaryExpr::And
;
1624 // Highest Precedence: *, /, %, <<, >>
1625 case AsmToken::Star
:
1626 Kind
= MCBinaryExpr::Mul
;
1628 case AsmToken::Slash
:
1629 Kind
= MCBinaryExpr::Div
;
1631 case AsmToken::Percent
:
1632 Kind
= MCBinaryExpr::Mod
;
1634 case AsmToken::LessLess
:
1635 Kind
= MCBinaryExpr::Shl
;
1637 case AsmToken::GreaterGreater
:
1638 Kind
= ShouldUseLogicalShr
? MCBinaryExpr::LShr
: MCBinaryExpr::AShr
;
1643 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K
,
1644 MCBinaryExpr::Opcode
&Kind
) {
1645 bool ShouldUseLogicalShr
= MAI
.shouldUseLogicalShr();
1646 return IsDarwin
? getDarwinBinOpPrecedence(K
, Kind
, ShouldUseLogicalShr
)
1647 : getGNUBinOpPrecedence(K
, Kind
, ShouldUseLogicalShr
);
1650 /// Parse all binary operators with precedence >= 'Precedence'.
1651 /// Res contains the LHS of the expression on input.
1652 bool AsmParser::parseBinOpRHS(unsigned Precedence
, const MCExpr
*&Res
,
1654 SMLoc StartLoc
= Lexer
.getLoc();
1656 MCBinaryExpr::Opcode Kind
= MCBinaryExpr::Add
;
1657 unsigned TokPrec
= getBinOpPrecedence(Lexer
.getKind(), Kind
);
1659 // If the next token is lower precedence than we are allowed to eat, return
1660 // successfully with what we ate already.
1661 if (TokPrec
< Precedence
)
1666 // Eat the next primary expression.
1668 if (getTargetParser().parsePrimaryExpr(RHS
, EndLoc
))
1671 // If BinOp binds less tightly with RHS than the operator after RHS, let
1672 // the pending operator take RHS as its LHS.
1673 MCBinaryExpr::Opcode Dummy
;
1674 unsigned NextTokPrec
= getBinOpPrecedence(Lexer
.getKind(), Dummy
);
1675 if (TokPrec
< NextTokPrec
&& parseBinOpRHS(TokPrec
+ 1, RHS
, EndLoc
))
1678 // Merge LHS and RHS according to operator.
1679 Res
= MCBinaryExpr::create(Kind
, Res
, RHS
, getContext(), StartLoc
);
1684 /// ::= EndOfStatement
1685 /// ::= Label* Directive ...Operands... EndOfStatement
1686 /// ::= Label* Identifier OperandList* EndOfStatement
1687 bool AsmParser::parseStatement(ParseStatementInfo
&Info
,
1688 MCAsmParserSemaCallback
*SI
) {
1689 assert(!hasPendingError() && "parseStatement started with pending error");
1690 // Eat initial spaces and comments
1691 while (Lexer
.is(AsmToken::Space
))
1693 if (Lexer
.is(AsmToken::EndOfStatement
)) {
1694 // if this is a line comment we can drop it safely
1695 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1696 getTok().getString().front() == '\n')
1701 // Statements always start with an identifier.
1702 AsmToken ID
= getTok();
1703 SMLoc IDLoc
= ID
.getLoc();
1705 int64_t LocalLabelVal
= -1;
1706 if (Lexer
.is(AsmToken::HashDirective
))
1707 return parseCppHashLineFilenameComment(IDLoc
);
1708 // Allow an integer followed by a ':' as a directional local label.
1709 if (Lexer
.is(AsmToken::Integer
)) {
1710 LocalLabelVal
= getTok().getIntVal();
1711 if (LocalLabelVal
< 0) {
1712 if (!TheCondState
.Ignore
) {
1713 Lex(); // always eat a token
1714 return Error(IDLoc
, "unexpected token at start of statement");
1718 IDVal
= getTok().getString();
1719 Lex(); // Consume the integer token to be used as an identifier token.
1720 if (Lexer
.getKind() != AsmToken::Colon
) {
1721 if (!TheCondState
.Ignore
) {
1722 Lex(); // always eat a token
1723 return Error(IDLoc
, "unexpected token at start of statement");
1727 } else if (Lexer
.is(AsmToken::Dot
)) {
1728 // Treat '.' as a valid identifier in this context.
1731 } else if (Lexer
.is(AsmToken::LCurly
)) {
1732 // Treat '{' as a valid identifier in this context.
1736 } else if (Lexer
.is(AsmToken::RCurly
)) {
1737 // Treat '}' as a valid identifier in this context.
1740 } else if (Lexer
.is(AsmToken::Star
) &&
1741 getTargetParser().starIsStartOfStatement()) {
1742 // Accept '*' as a valid start of statement.
1745 } else if (parseIdentifier(IDVal
)) {
1746 if (!TheCondState
.Ignore
) {
1747 Lex(); // always eat a token
1748 return Error(IDLoc
, "unexpected token at start of statement");
1753 // Handle conditional assembly here before checking for skipping. We
1754 // have to do this so that .endif isn't skipped in a ".if 0" block for
1756 StringMap
<DirectiveKind
>::const_iterator DirKindIt
=
1757 DirectiveKindMap
.find(IDVal
);
1758 DirectiveKind DirKind
= (DirKindIt
== DirectiveKindMap
.end())
1761 : DirKindIt
->getValue();
1772 return parseDirectiveIf(IDLoc
, DirKind
);
1774 return parseDirectiveIfb(IDLoc
, true);
1776 return parseDirectiveIfb(IDLoc
, false);
1778 return parseDirectiveIfc(IDLoc
, true);
1780 return parseDirectiveIfeqs(IDLoc
, true);
1782 return parseDirectiveIfc(IDLoc
, false);
1784 return parseDirectiveIfeqs(IDLoc
, false);
1786 return parseDirectiveIfdef(IDLoc
, true);
1789 return parseDirectiveIfdef(IDLoc
, false);
1791 return parseDirectiveElseIf(IDLoc
);
1793 return parseDirectiveElse(IDLoc
);
1795 return parseDirectiveEndIf(IDLoc
);
1798 // Ignore the statement if in the middle of inactive conditional
1800 if (TheCondState
.Ignore
) {
1801 eatToEndOfStatement();
1805 // FIXME: Recurse on local labels?
1807 // See what kind of statement we have.
1808 switch (Lexer
.getKind()) {
1809 case AsmToken::Colon
: {
1810 if (!getTargetParser().isLabel(ID
))
1812 if (checkForValidSection())
1815 // identifier ':' -> Label.
1818 // Diagnose attempt to use '.' as a label.
1820 return Error(IDLoc
, "invalid use of pseudo-symbol '.' as a label");
1822 // Diagnose attempt to use a variable as a label.
1824 // FIXME: Diagnostics. Note the location of the definition as a label.
1825 // FIXME: This doesn't diagnose assignment to a symbol which has been
1826 // implicitly marked as external.
1828 if (LocalLabelVal
== -1) {
1829 if (ParsingInlineAsm
&& SI
) {
1830 StringRef RewrittenLabel
=
1831 SI
->LookupInlineAsmLabel(IDVal
, getSourceManager(), IDLoc
, true);
1832 assert(!RewrittenLabel
.empty() &&
1833 "We should have an internal name here.");
1834 Info
.AsmRewrites
->emplace_back(AOK_Label
, IDLoc
, IDVal
.size(),
1836 IDVal
= RewrittenLabel
;
1838 Sym
= getContext().getOrCreateSymbol(IDVal
);
1840 Sym
= Ctx
.createDirectionalLocalSymbol(LocalLabelVal
);
1841 // End of Labels should be treated as end of line for lexing
1842 // purposes but that information is not available to the Lexer who
1843 // does not understand Labels. This may cause us to see a Hash
1844 // here instead of a preprocessor line comment.
1845 if (getTok().is(AsmToken::Hash
)) {
1846 StringRef CommentStr
= parseStringToEndOfStatement();
1848 Lexer
.UnLex(AsmToken(AsmToken::EndOfStatement
, CommentStr
));
1851 // Consume any end of statement token, if present, to avoid spurious
1852 // AddBlankLine calls().
1853 if (getTok().is(AsmToken::EndOfStatement
)) {
1857 getTargetParser().doBeforeLabelEmit(Sym
);
1860 if (!getTargetParser().isParsingInlineAsm())
1861 Out
.EmitLabel(Sym
, IDLoc
);
1863 // If we are generating dwarf for assembly source files then gather the
1864 // info to make a dwarf label entry for this label if needed.
1865 if (enabledGenDwarfForAssembly())
1866 MCGenDwarfLabelEntry::Make(Sym
, &getStreamer(), getSourceManager(),
1869 getTargetParser().onLabelParsed(Sym
);
1874 case AsmToken::Equal
:
1875 if (!getTargetParser().equalIsAsmAssignment())
1877 // identifier '=' ... -> assignment statement
1880 return parseAssignment(IDVal
, true);
1882 default: // Normal instruction or directive.
1886 // If macros are enabled, check to see if this is a macro instantiation.
1887 if (areMacrosEnabled())
1888 if (const MCAsmMacro
*M
= getContext().lookupMacro(IDVal
)) {
1889 return handleMacroEntry(M
, IDLoc
);
1892 // Otherwise, we have a normal instruction or directive.
1894 // Directives start with "."
1895 if (IDVal
.startswith(".") && IDVal
!= ".") {
1896 // There are several entities interested in parsing directives:
1898 // 1. The target-specific assembly parser. Some directives are target
1899 // specific or may potentially behave differently on certain targets.
1900 // 2. Asm parser extensions. For example, platform-specific parsers
1901 // (like the ELF parser) register themselves as extensions.
1902 // 3. The generic directive parser implemented by this class. These are
1903 // all the directives that behave in a target and platform independent
1904 // manner, or at least have a default behavior that's shared between
1905 // all targets and platforms.
1907 getTargetParser().flushPendingInstructions(getStreamer());
1909 SMLoc StartTokLoc
= getTok().getLoc();
1910 bool TPDirectiveReturn
= getTargetParser().ParseDirective(ID
);
1912 if (hasPendingError())
1914 // Currently the return value should be true if we are
1915 // uninterested but as this is at odds with the standard parsing
1916 // convention (return true = error) we have instances of a parsed
1917 // directive that fails returning true as an error. Catch these
1918 // cases as best as possible errors here.
1919 if (TPDirectiveReturn
&& StartTokLoc
!= getTok().getLoc())
1921 // Return if we did some parsing or believe we succeeded.
1922 if (!TPDirectiveReturn
|| StartTokLoc
!= getTok().getLoc())
1925 // Next, check the extension directive map to see if any extension has
1926 // registered itself to parse this directive.
1927 std::pair
<MCAsmParserExtension
*, DirectiveHandler
> Handler
=
1928 ExtensionDirectiveMap
.lookup(IDVal
);
1930 return (*Handler
.second
)(Handler
.first
, IDVal
, IDLoc
);
1932 // Finally, if no one else is interested in this directive, it must be
1933 // generic and familiar to this class.
1939 return parseDirectiveSet(IDVal
, true);
1941 return parseDirectiveSet(IDVal
, false);
1943 return parseDirectiveAscii(IDVal
, false);
1946 return parseDirectiveAscii(IDVal
, true);
1949 return parseDirectiveValue(IDVal
, 1);
1955 return parseDirectiveValue(IDVal
, 2);
1960 return parseDirectiveValue(IDVal
, 4);
1963 return parseDirectiveValue(IDVal
, 8);
1965 return parseDirectiveValue(
1966 IDVal
, getContext().getAsmInfo()->getCodePointerSize());
1968 return parseDirectiveOctaValue(IDVal
);
1972 return parseDirectiveRealValue(IDVal
, APFloat::IEEEsingle());
1975 return parseDirectiveRealValue(IDVal
, APFloat::IEEEdouble());
1977 bool IsPow2
= !getContext().getAsmInfo()->getAlignmentIsInBytes();
1978 return parseDirectiveAlign(IsPow2
, /*ExprSize=*/1);
1981 bool IsPow2
= !getContext().getAsmInfo()->getAlignmentIsInBytes();
1982 return parseDirectiveAlign(IsPow2
, /*ExprSize=*/4);
1985 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1987 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1989 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1991 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1993 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1995 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1997 return parseDirectiveOrg();
1999 return parseDirectiveFill();
2001 return parseDirectiveZero();
2003 eatToEndOfStatement(); // .extern is the default, ignore it.
2007 return parseDirectiveSymbolAttribute(MCSA_Global
);
2008 case DK_LAZY_REFERENCE
:
2009 return parseDirectiveSymbolAttribute(MCSA_LazyReference
);
2010 case DK_NO_DEAD_STRIP
:
2011 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip
);
2012 case DK_SYMBOL_RESOLVER
:
2013 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver
);
2014 case DK_PRIVATE_EXTERN
:
2015 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern
);
2017 return parseDirectiveSymbolAttribute(MCSA_Reference
);
2018 case DK_WEAK_DEFINITION
:
2019 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition
);
2020 case DK_WEAK_REFERENCE
:
2021 return parseDirectiveSymbolAttribute(MCSA_WeakReference
);
2022 case DK_WEAK_DEF_CAN_BE_HIDDEN
:
2023 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate
);
2025 return parseDirectiveSymbolAttribute(MCSA_Cold
);
2028 return parseDirectiveComm(/*IsLocal=*/false);
2030 return parseDirectiveComm(/*IsLocal=*/true);
2032 return parseDirectiveAbort();
2034 return parseDirectiveInclude();
2036 return parseDirectiveIncbin();
2039 return TokError(Twine(IDVal
) +
2040 " not currently supported for this target");
2042 return parseDirectiveRept(IDLoc
, IDVal
);
2044 return parseDirectiveIrp(IDLoc
);
2046 return parseDirectiveIrpc(IDLoc
);
2048 return parseDirectiveEndr(IDLoc
);
2049 case DK_BUNDLE_ALIGN_MODE
:
2050 return parseDirectiveBundleAlignMode();
2051 case DK_BUNDLE_LOCK
:
2052 return parseDirectiveBundleLock();
2053 case DK_BUNDLE_UNLOCK
:
2054 return parseDirectiveBundleUnlock();
2056 return parseDirectiveLEB128(true);
2058 return parseDirectiveLEB128(false);
2061 return parseDirectiveSpace(IDVal
);
2063 return parseDirectiveFile(IDLoc
);
2065 return parseDirectiveLine();
2067 return parseDirectiveLoc();
2069 return parseDirectiveStabs();
2071 return parseDirectiveCVFile();
2073 return parseDirectiveCVFuncId();
2074 case DK_CV_INLINE_SITE_ID
:
2075 return parseDirectiveCVInlineSiteId();
2077 return parseDirectiveCVLoc();
2078 case DK_CV_LINETABLE
:
2079 return parseDirectiveCVLinetable();
2080 case DK_CV_INLINE_LINETABLE
:
2081 return parseDirectiveCVInlineLinetable();
2082 case DK_CV_DEF_RANGE
:
2083 return parseDirectiveCVDefRange();
2085 return parseDirectiveCVString();
2086 case DK_CV_STRINGTABLE
:
2087 return parseDirectiveCVStringTable();
2088 case DK_CV_FILECHECKSUMS
:
2089 return parseDirectiveCVFileChecksums();
2090 case DK_CV_FILECHECKSUM_OFFSET
:
2091 return parseDirectiveCVFileChecksumOffset();
2092 case DK_CV_FPO_DATA
:
2093 return parseDirectiveCVFPOData();
2094 case DK_CFI_SECTIONS
:
2095 return parseDirectiveCFISections();
2096 case DK_CFI_STARTPROC
:
2097 return parseDirectiveCFIStartProc();
2098 case DK_CFI_ENDPROC
:
2099 return parseDirectiveCFIEndProc();
2100 case DK_CFI_DEF_CFA
:
2101 return parseDirectiveCFIDefCfa(IDLoc
);
2102 case DK_CFI_DEF_CFA_OFFSET
:
2103 return parseDirectiveCFIDefCfaOffset();
2104 case DK_CFI_ADJUST_CFA_OFFSET
:
2105 return parseDirectiveCFIAdjustCfaOffset();
2106 case DK_CFI_DEF_CFA_REGISTER
:
2107 return parseDirectiveCFIDefCfaRegister(IDLoc
);
2109 return parseDirectiveCFIOffset(IDLoc
);
2110 case DK_CFI_REL_OFFSET
:
2111 return parseDirectiveCFIRelOffset(IDLoc
);
2112 case DK_CFI_PERSONALITY
:
2113 return parseDirectiveCFIPersonalityOrLsda(true);
2115 return parseDirectiveCFIPersonalityOrLsda(false);
2116 case DK_CFI_REMEMBER_STATE
:
2117 return parseDirectiveCFIRememberState();
2118 case DK_CFI_RESTORE_STATE
:
2119 return parseDirectiveCFIRestoreState();
2120 case DK_CFI_SAME_VALUE
:
2121 return parseDirectiveCFISameValue(IDLoc
);
2122 case DK_CFI_RESTORE
:
2123 return parseDirectiveCFIRestore(IDLoc
);
2125 return parseDirectiveCFIEscape();
2126 case DK_CFI_RETURN_COLUMN
:
2127 return parseDirectiveCFIReturnColumn(IDLoc
);
2128 case DK_CFI_SIGNAL_FRAME
:
2129 return parseDirectiveCFISignalFrame();
2130 case DK_CFI_UNDEFINED
:
2131 return parseDirectiveCFIUndefined(IDLoc
);
2132 case DK_CFI_REGISTER
:
2133 return parseDirectiveCFIRegister(IDLoc
);
2134 case DK_CFI_WINDOW_SAVE
:
2135 return parseDirectiveCFIWindowSave();
2138 return parseDirectiveMacrosOnOff(IDVal
);
2140 return parseDirectiveMacro(IDLoc
);
2143 return parseDirectiveAltmacro(IDVal
);
2145 return parseDirectiveExitMacro(IDVal
);
2148 return parseDirectiveEndMacro(IDVal
);
2150 return parseDirectivePurgeMacro(IDLoc
);
2152 return parseDirectiveEnd(IDLoc
);
2154 return parseDirectiveError(IDLoc
, false);
2156 return parseDirectiveError(IDLoc
, true);
2158 return parseDirectiveWarning(IDLoc
);
2160 return parseDirectiveReloc(IDLoc
);
2163 return parseDirectiveDCB(IDVal
, 2);
2165 return parseDirectiveDCB(IDVal
, 1);
2167 return parseDirectiveRealDCB(IDVal
, APFloat::IEEEdouble());
2169 return parseDirectiveDCB(IDVal
, 4);
2171 return parseDirectiveRealDCB(IDVal
, APFloat::IEEEsingle());
2174 return TokError(Twine(IDVal
) +
2175 " not currently supported for this target");
2178 return parseDirectiveDS(IDVal
, 2);
2180 return parseDirectiveDS(IDVal
, 1);
2182 return parseDirectiveDS(IDVal
, 8);
2185 return parseDirectiveDS(IDVal
, 4);
2188 return parseDirectiveDS(IDVal
, 12);
2190 return parseDirectivePrint(IDLoc
);
2192 return parseDirectiveAddrsig();
2193 case DK_ADDRSIG_SYM
:
2194 return parseDirectiveAddrsigSym();
2197 return Error(IDLoc
, "unknown directive");
2200 // __asm _emit or __asm __emit
2201 if (ParsingInlineAsm
&& (IDVal
== "_emit" || IDVal
== "__emit" ||
2202 IDVal
== "_EMIT" || IDVal
== "__EMIT"))
2203 return parseDirectiveMSEmit(IDLoc
, Info
, IDVal
.size());
2206 if (ParsingInlineAsm
&& (IDVal
== "align" || IDVal
== "ALIGN"))
2207 return parseDirectiveMSAlign(IDLoc
, Info
);
2209 if (ParsingInlineAsm
&& (IDVal
== "even" || IDVal
== "EVEN"))
2210 Info
.AsmRewrites
->emplace_back(AOK_EVEN
, IDLoc
, 4);
2211 if (checkForValidSection())
2214 // Canonicalize the opcode to lower case.
2215 std::string OpcodeStr
= IDVal
.lower();
2216 ParseInstructionInfo
IInfo(Info
.AsmRewrites
);
2217 bool ParseHadError
= getTargetParser().ParseInstruction(IInfo
, OpcodeStr
, ID
,
2218 Info
.ParsedOperands
);
2219 Info
.ParseError
= ParseHadError
;
2221 // Dump the parsed representation, if requested.
2222 if (getShowParsedOperands()) {
2223 SmallString
<256> Str
;
2224 raw_svector_ostream
OS(Str
);
2225 OS
<< "parsed instruction: [";
2226 for (unsigned i
= 0; i
!= Info
.ParsedOperands
.size(); ++i
) {
2229 Info
.ParsedOperands
[i
]->print(OS
);
2233 printMessage(IDLoc
, SourceMgr::DK_Note
, OS
.str());
2236 // Fail even if ParseInstruction erroneously returns false.
2237 if (hasPendingError() || ParseHadError
)
2240 // If we are generating dwarf for the current section then generate a .loc
2241 // directive for the instruction.
2242 if (!ParseHadError
&& enabledGenDwarfForAssembly() &&
2243 getContext().getGenDwarfSectionSyms().count(
2244 getStreamer().getCurrentSectionOnly())) {
2246 if (ActiveMacros
.empty())
2247 Line
= SrcMgr
.FindLineNumber(IDLoc
, CurBuffer
);
2249 Line
= SrcMgr
.FindLineNumber(ActiveMacros
.front()->InstantiationLoc
,
2250 ActiveMacros
.front()->ExitBuffer
);
2252 // If we previously parsed a cpp hash file line comment then make sure the
2253 // current Dwarf File is for the CppHashFilename if not then emit the
2254 // Dwarf File table for it and adjust the line number for the .loc.
2255 if (!CppHashInfo
.Filename
.empty()) {
2256 unsigned FileNumber
= getStreamer().EmitDwarfFileDirective(
2257 0, StringRef(), CppHashInfo
.Filename
);
2258 getContext().setGenDwarfFileNumber(FileNumber
);
2260 unsigned CppHashLocLineNo
=
2261 SrcMgr
.FindLineNumber(CppHashInfo
.Loc
, CppHashInfo
.Buf
);
2262 Line
= CppHashInfo
.LineNumber
- 1 + (Line
- CppHashLocLineNo
);
2265 getStreamer().EmitDwarfLocDirective(
2266 getContext().getGenDwarfFileNumber(), Line
, 0,
2267 DWARF2_LINE_DEFAULT_IS_STMT
? DWARF2_FLAG_IS_STMT
: 0, 0, 0,
2271 // If parsing succeeded, match the instruction.
2272 if (!ParseHadError
) {
2274 if (getTargetParser().MatchAndEmitInstruction(
2275 IDLoc
, Info
.Opcode
, Info
.ParsedOperands
, Out
, ErrorInfo
,
2276 getTargetParser().isParsingInlineAsm()))
2282 // Parse and erase curly braces marking block start/end
2284 AsmParser::parseCurlyBlockScope(SmallVectorImpl
<AsmRewrite
> &AsmStrRewrites
) {
2285 // Identify curly brace marking block start/end
2286 if (Lexer
.isNot(AsmToken::LCurly
) && Lexer
.isNot(AsmToken::RCurly
))
2289 SMLoc StartLoc
= Lexer
.getLoc();
2290 Lex(); // Eat the brace
2291 if (Lexer
.is(AsmToken::EndOfStatement
))
2292 Lex(); // Eat EndOfStatement following the brace
2294 // Erase the block start/end brace from the output asm string
2295 AsmStrRewrites
.emplace_back(AOK_Skip
, StartLoc
, Lexer
.getLoc().getPointer() -
2296 StartLoc
.getPointer());
2300 /// parseCppHashLineFilenameComment as this:
2301 /// ::= # number "filename"
2302 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L
) {
2303 Lex(); // Eat the hash token.
2304 // Lexer only ever emits HashDirective if it fully formed if it's
2305 // done the checking already so this is an internal error.
2306 assert(getTok().is(AsmToken::Integer
) &&
2307 "Lexing Cpp line comment: Expected Integer");
2308 int64_t LineNumber
= getTok().getIntVal();
2310 assert(getTok().is(AsmToken::String
) &&
2311 "Lexing Cpp line comment: Expected String");
2312 StringRef Filename
= getTok().getString();
2315 // Get rid of the enclosing quotes.
2316 Filename
= Filename
.substr(1, Filename
.size() - 2);
2318 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2319 // and possibly DWARF file info.
2320 CppHashInfo
.Loc
= L
;
2321 CppHashInfo
.Filename
= Filename
;
2322 CppHashInfo
.LineNumber
= LineNumber
;
2323 CppHashInfo
.Buf
= CurBuffer
;
2324 if (FirstCppHashFilename
.empty())
2325 FirstCppHashFilename
= Filename
;
2329 /// will use the last parsed cpp hash line filename comment
2330 /// for the Filename and LineNo if any in the diagnostic.
2331 void AsmParser::DiagHandler(const SMDiagnostic
&Diag
, void *Context
) {
2332 const AsmParser
*Parser
= static_cast<const AsmParser
*>(Context
);
2333 raw_ostream
&OS
= errs();
2335 const SourceMgr
&DiagSrcMgr
= *Diag
.getSourceMgr();
2336 SMLoc DiagLoc
= Diag
.getLoc();
2337 unsigned DiagBuf
= DiagSrcMgr
.FindBufferContainingLoc(DiagLoc
);
2338 unsigned CppHashBuf
=
2339 Parser
->SrcMgr
.FindBufferContainingLoc(Parser
->CppHashInfo
.Loc
);
2341 // Like SourceMgr::printMessage() we need to print the include stack if any
2342 // before printing the message.
2343 unsigned DiagCurBuffer
= DiagSrcMgr
.FindBufferContainingLoc(DiagLoc
);
2344 if (!Parser
->SavedDiagHandler
&& DiagCurBuffer
&&
2345 DiagCurBuffer
!= DiagSrcMgr
.getMainFileID()) {
2346 SMLoc ParentIncludeLoc
= DiagSrcMgr
.getParentIncludeLoc(DiagCurBuffer
);
2347 DiagSrcMgr
.PrintIncludeStack(ParentIncludeLoc
, OS
);
2350 // If we have not parsed a cpp hash line filename comment or the source
2351 // manager changed or buffer changed (like in a nested include) then just
2352 // print the normal diagnostic using its Filename and LineNo.
2353 if (!Parser
->CppHashInfo
.LineNumber
|| &DiagSrcMgr
!= &Parser
->SrcMgr
||
2354 DiagBuf
!= CppHashBuf
) {
2355 if (Parser
->SavedDiagHandler
)
2356 Parser
->SavedDiagHandler(Diag
, Parser
->SavedDiagContext
);
2358 Diag
.print(nullptr, OS
);
2362 // Use the CppHashFilename and calculate a line number based on the
2363 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2364 // for the diagnostic.
2365 const std::string
&Filename
= Parser
->CppHashInfo
.Filename
;
2367 int DiagLocLineNo
= DiagSrcMgr
.FindLineNumber(DiagLoc
, DiagBuf
);
2368 int CppHashLocLineNo
=
2369 Parser
->SrcMgr
.FindLineNumber(Parser
->CppHashInfo
.Loc
, CppHashBuf
);
2371 Parser
->CppHashInfo
.LineNumber
- 1 + (DiagLocLineNo
- CppHashLocLineNo
);
2373 SMDiagnostic
NewDiag(*Diag
.getSourceMgr(), Diag
.getLoc(), Filename
, LineNo
,
2374 Diag
.getColumnNo(), Diag
.getKind(), Diag
.getMessage(),
2375 Diag
.getLineContents(), Diag
.getRanges());
2377 if (Parser
->SavedDiagHandler
)
2378 Parser
->SavedDiagHandler(NewDiag
, Parser
->SavedDiagContext
);
2380 NewDiag
.print(nullptr, OS
);
2383 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2384 // difference being that that function accepts '@' as part of identifiers and
2385 // we can't do that. AsmLexer.cpp should probably be changed to handle
2386 // '@' as a special case when needed.
2387 static bool isIdentifierChar(char c
) {
2388 return isalnum(static_cast<unsigned char>(c
)) || c
== '_' || c
== '$' ||
2392 bool AsmParser::expandMacro(raw_svector_ostream
&OS
, StringRef Body
,
2393 ArrayRef
<MCAsmMacroParameter
> Parameters
,
2394 ArrayRef
<MCAsmMacroArgument
> A
,
2395 bool EnableAtPseudoVariable
, SMLoc L
) {
2396 unsigned NParameters
= Parameters
.size();
2397 bool HasVararg
= NParameters
? Parameters
.back().Vararg
: false;
2398 if ((!IsDarwin
|| NParameters
!= 0) && NParameters
!= A
.size())
2399 return Error(L
, "Wrong number of arguments");
2401 // A macro without parameters is handled differently on Darwin:
2402 // gas accepts no arguments and does no substitutions
2403 while (!Body
.empty()) {
2404 // Scan for the next substitution.
2405 std::size_t End
= Body
.size(), Pos
= 0;
2406 for (; Pos
!= End
; ++Pos
) {
2407 // Check for a substitution or escape.
2408 if (IsDarwin
&& !NParameters
) {
2409 // This macro has no parameters, look for $0, $1, etc.
2410 if (Body
[Pos
] != '$' || Pos
+ 1 == End
)
2413 char Next
= Body
[Pos
+ 1];
2414 if (Next
== '$' || Next
== 'n' ||
2415 isdigit(static_cast<unsigned char>(Next
)))
2418 // This macro has parameters, look for \foo, \bar, etc.
2419 if (Body
[Pos
] == '\\' && Pos
+ 1 != End
)
2425 OS
<< Body
.slice(0, Pos
);
2427 // Check if we reached the end.
2431 if (IsDarwin
&& !NParameters
) {
2432 switch (Body
[Pos
+ 1]) {
2438 // $n => number of arguments
2443 // $[0-9] => argument
2445 // Missing arguments are ignored.
2446 unsigned Index
= Body
[Pos
+ 1] - '0';
2447 if (Index
>= A
.size())
2450 // Otherwise substitute with the token values, with spaces eliminated.
2451 for (const AsmToken
&Token
: A
[Index
])
2452 OS
<< Token
.getString();
2458 unsigned I
= Pos
+ 1;
2460 // Check for the \@ pseudo-variable.
2461 if (EnableAtPseudoVariable
&& Body
[I
] == '@' && I
+ 1 != End
)
2464 while (isIdentifierChar(Body
[I
]) && I
+ 1 != End
)
2467 const char *Begin
= Body
.data() + Pos
+ 1;
2468 StringRef
Argument(Begin
, I
- (Pos
+ 1));
2471 if (Argument
== "@") {
2472 OS
<< NumOfMacroInstantiations
;
2475 for (; Index
< NParameters
; ++Index
)
2476 if (Parameters
[Index
].Name
== Argument
)
2479 if (Index
== NParameters
) {
2480 if (Body
[Pos
+ 1] == '(' && Body
[Pos
+ 2] == ')')
2483 OS
<< '\\' << Argument
;
2487 bool VarargParameter
= HasVararg
&& Index
== (NParameters
- 1);
2488 for (const AsmToken
&Token
: A
[Index
])
2489 // For altmacro mode, you can write '%expr'.
2490 // The prefix '%' evaluates the expression 'expr'
2491 // and uses the result as a string (e.g. replace %(1+2) with the
2493 // Here, we identify the integer token which is the result of the
2494 // absolute expression evaluation and replace it with its string
2496 if (AltMacroMode
&& Token
.getString().front() == '%' &&
2497 Token
.is(AsmToken::Integer
))
2498 // Emit an integer value to the buffer.
2499 OS
<< Token
.getIntVal();
2500 // Only Token that was validated as a string and begins with '<'
2501 // is considered altMacroString!!!
2502 else if (AltMacroMode
&& Token
.getString().front() == '<' &&
2503 Token
.is(AsmToken::String
)) {
2504 OS
<< altMacroString(Token
.getStringContents());
2506 // We expect no quotes around the string's contents when
2507 // parsing for varargs.
2508 else if (Token
.isNot(AsmToken::String
) || VarargParameter
)
2509 OS
<< Token
.getString();
2511 OS
<< Token
.getStringContents();
2513 Pos
+= 1 + Argument
.size();
2517 // Update the scan point.
2518 Body
= Body
.substr(Pos
);
2524 MacroInstantiation::MacroInstantiation(SMLoc IL
, int EB
, SMLoc EL
,
2525 size_t CondStackDepth
)
2526 : InstantiationLoc(IL
), ExitBuffer(EB
), ExitLoc(EL
),
2527 CondStackDepth(CondStackDepth
) {}
2529 static bool isOperator(AsmToken::TokenKind kind
) {
2533 case AsmToken::Plus
:
2534 case AsmToken::Minus
:
2535 case AsmToken::Tilde
:
2536 case AsmToken::Slash
:
2537 case AsmToken::Star
:
2539 case AsmToken::Equal
:
2540 case AsmToken::EqualEqual
:
2541 case AsmToken::Pipe
:
2542 case AsmToken::PipePipe
:
2543 case AsmToken::Caret
:
2545 case AsmToken::AmpAmp
:
2546 case AsmToken::Exclaim
:
2547 case AsmToken::ExclaimEqual
:
2548 case AsmToken::Less
:
2549 case AsmToken::LessEqual
:
2550 case AsmToken::LessLess
:
2551 case AsmToken::LessGreater
:
2552 case AsmToken::Greater
:
2553 case AsmToken::GreaterEqual
:
2554 case AsmToken::GreaterGreater
:
2561 class AsmLexerSkipSpaceRAII
{
2563 AsmLexerSkipSpaceRAII(AsmLexer
&Lexer
, bool SkipSpace
) : Lexer(Lexer
) {
2564 Lexer
.setSkipSpace(SkipSpace
);
2567 ~AsmLexerSkipSpaceRAII() {
2568 Lexer
.setSkipSpace(true);
2575 } // end anonymous namespace
2577 bool AsmParser::parseMacroArgument(MCAsmMacroArgument
&MA
, bool Vararg
) {
2580 if (Lexer
.isNot(AsmToken::EndOfStatement
)) {
2581 StringRef Str
= parseStringToEndOfStatement();
2582 MA
.emplace_back(AsmToken::String
, Str
);
2587 unsigned ParenLevel
= 0;
2589 // Darwin doesn't use spaces to delmit arguments.
2590 AsmLexerSkipSpaceRAII
ScopedSkipSpace(Lexer
, IsDarwin
);
2596 if (Lexer
.is(AsmToken::Eof
) || Lexer
.is(AsmToken::Equal
))
2597 return TokError("unexpected token in macro instantiation");
2599 if (ParenLevel
== 0) {
2601 if (Lexer
.is(AsmToken::Comma
))
2604 if (Lexer
.is(AsmToken::Space
)) {
2606 Lexer
.Lex(); // Eat spaces
2609 // Spaces can delimit parameters, but could also be part an expression.
2610 // If the token after a space is an operator, add the token and the next
2611 // one into this argument
2613 if (isOperator(Lexer
.getKind())) {
2614 MA
.push_back(getTok());
2617 // Whitespace after an operator can be ignored.
2618 if (Lexer
.is(AsmToken::Space
))
2628 // handleMacroEntry relies on not advancing the lexer here
2629 // to be able to fill in the remaining default parameter values
2630 if (Lexer
.is(AsmToken::EndOfStatement
))
2633 // Adjust the current parentheses level.
2634 if (Lexer
.is(AsmToken::LParen
))
2636 else if (Lexer
.is(AsmToken::RParen
) && ParenLevel
)
2639 // Append the token to the current argument list.
2640 MA
.push_back(getTok());
2644 if (ParenLevel
!= 0)
2645 return TokError("unbalanced parentheses in macro argument");
2649 // Parse the macro instantiation arguments.
2650 bool AsmParser::parseMacroArguments(const MCAsmMacro
*M
,
2651 MCAsmMacroArguments
&A
) {
2652 const unsigned NParameters
= M
? M
->Parameters
.size() : 0;
2653 bool NamedParametersFound
= false;
2654 SmallVector
<SMLoc
, 4> FALocs
;
2656 A
.resize(NParameters
);
2657 FALocs
.resize(NParameters
);
2659 // Parse two kinds of macro invocations:
2660 // - macros defined without any parameters accept an arbitrary number of them
2661 // - macros defined with parameters accept at most that many of them
2662 bool HasVararg
= NParameters
? M
->Parameters
.back().Vararg
: false;
2663 for (unsigned Parameter
= 0; !NParameters
|| Parameter
< NParameters
;
2665 SMLoc IDLoc
= Lexer
.getLoc();
2666 MCAsmMacroParameter FA
;
2668 if (Lexer
.is(AsmToken::Identifier
) && Lexer
.peekTok().is(AsmToken::Equal
)) {
2669 if (parseIdentifier(FA
.Name
))
2670 return Error(IDLoc
, "invalid argument identifier for formal argument");
2672 if (Lexer
.isNot(AsmToken::Equal
))
2673 return TokError("expected '=' after formal parameter identifier");
2677 NamedParametersFound
= true;
2679 bool Vararg
= HasVararg
&& Parameter
== (NParameters
- 1);
2681 if (NamedParametersFound
&& FA
.Name
.empty())
2682 return Error(IDLoc
, "cannot mix positional and keyword arguments");
2684 SMLoc StrLoc
= Lexer
.getLoc();
2686 if (AltMacroMode
&& Lexer
.is(AsmToken::Percent
)) {
2687 const MCExpr
*AbsoluteExp
;
2691 if (parseExpression(AbsoluteExp
, EndLoc
))
2693 if (!AbsoluteExp
->evaluateAsAbsolute(Value
,
2694 getStreamer().getAssemblerPtr()))
2695 return Error(StrLoc
, "expected absolute expression");
2696 const char *StrChar
= StrLoc
.getPointer();
2697 const char *EndChar
= EndLoc
.getPointer();
2698 AsmToken
newToken(AsmToken::Integer
,
2699 StringRef(StrChar
, EndChar
- StrChar
), Value
);
2700 FA
.Value
.push_back(newToken
);
2701 } else if (AltMacroMode
&& Lexer
.is(AsmToken::Less
) &&
2702 isAltmacroString(StrLoc
, EndLoc
)) {
2703 const char *StrChar
= StrLoc
.getPointer();
2704 const char *EndChar
= EndLoc
.getPointer();
2705 jumpToLoc(EndLoc
, CurBuffer
);
2706 /// Eat from '<' to '>'
2708 AsmToken
newToken(AsmToken::String
,
2709 StringRef(StrChar
, EndChar
- StrChar
));
2710 FA
.Value
.push_back(newToken
);
2711 } else if(parseMacroArgument(FA
.Value
, Vararg
))
2714 unsigned PI
= Parameter
;
2715 if (!FA
.Name
.empty()) {
2717 for (FAI
= 0; FAI
< NParameters
; ++FAI
)
2718 if (M
->Parameters
[FAI
].Name
== FA
.Name
)
2721 if (FAI
>= NParameters
) {
2722 assert(M
&& "expected macro to be defined");
2723 return Error(IDLoc
, "parameter named '" + FA
.Name
+
2724 "' does not exist for macro '" + M
->Name
+ "'");
2729 if (!FA
.Value
.empty()) {
2734 if (FALocs
.size() <= PI
)
2735 FALocs
.resize(PI
+ 1);
2737 FALocs
[PI
] = Lexer
.getLoc();
2740 // At the end of the statement, fill in remaining arguments that have
2741 // default values. If there aren't any, then the next argument is
2742 // required but missing
2743 if (Lexer
.is(AsmToken::EndOfStatement
)) {
2744 bool Failure
= false;
2745 for (unsigned FAI
= 0; FAI
< NParameters
; ++FAI
) {
2746 if (A
[FAI
].empty()) {
2747 if (M
->Parameters
[FAI
].Required
) {
2748 Error(FALocs
[FAI
].isValid() ? FALocs
[FAI
] : Lexer
.getLoc(),
2749 "missing value for required parameter "
2750 "'" + M
->Parameters
[FAI
].Name
+ "' in macro '" + M
->Name
+ "'");
2754 if (!M
->Parameters
[FAI
].Value
.empty())
2755 A
[FAI
] = M
->Parameters
[FAI
].Value
;
2761 if (Lexer
.is(AsmToken::Comma
))
2765 return TokError("too many positional arguments");
2768 bool AsmParser::handleMacroEntry(const MCAsmMacro
*M
, SMLoc NameLoc
) {
2769 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2770 // eliminate this, although we should protect against infinite loops.
2771 unsigned MaxNestingDepth
= AsmMacroMaxNestingDepth
;
2772 if (ActiveMacros
.size() == MaxNestingDepth
) {
2773 std::ostringstream MaxNestingDepthError
;
2774 MaxNestingDepthError
<< "macros cannot be nested more than "
2775 << MaxNestingDepth
<< " levels deep."
2776 << " Use -asm-macro-max-nesting-depth to increase "
2778 return TokError(MaxNestingDepthError
.str());
2781 MCAsmMacroArguments A
;
2782 if (parseMacroArguments(M
, A
))
2785 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2786 // to hold the macro body with substitutions.
2787 SmallString
<256> Buf
;
2788 StringRef Body
= M
->Body
;
2789 raw_svector_ostream
OS(Buf
);
2791 if (expandMacro(OS
, Body
, M
->Parameters
, A
, true, getTok().getLoc()))
2794 // We include the .endmacro in the buffer as our cue to exit the macro
2796 OS
<< ".endmacro\n";
2798 std::unique_ptr
<MemoryBuffer
> Instantiation
=
2799 MemoryBuffer::getMemBufferCopy(OS
.str(), "<instantiation>");
2801 // Create the macro instantiation object and add to the current macro
2802 // instantiation stack.
2803 MacroInstantiation
*MI
= new MacroInstantiation(
2804 NameLoc
, CurBuffer
, getTok().getLoc(), TheCondStack
.size());
2805 ActiveMacros
.push_back(MI
);
2807 ++NumOfMacroInstantiations
;
2809 // Jump to the macro instantiation and prime the lexer.
2810 CurBuffer
= SrcMgr
.AddNewSourceBuffer(std::move(Instantiation
), SMLoc());
2811 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
2817 void AsmParser::handleMacroExit() {
2818 // Jump to the EndOfStatement we should return to, and consume it.
2819 jumpToLoc(ActiveMacros
.back()->ExitLoc
, ActiveMacros
.back()->ExitBuffer
);
2822 // Pop the instantiation entry.
2823 delete ActiveMacros
.back();
2824 ActiveMacros
.pop_back();
2827 bool AsmParser::parseAssignment(StringRef Name
, bool allow_redef
,
2830 const MCExpr
*Value
;
2831 if (MCParserUtils::parseAssignmentExpression(Name
, allow_redef
, *this, Sym
,
2836 // In the case where we parse an expression starting with a '.', we will
2837 // not generate an error, nor will we create a symbol. In this case we
2838 // should just return out.
2842 // Do the assignment.
2843 Out
.EmitAssignment(Sym
, Value
);
2845 Out
.EmitSymbolAttribute(Sym
, MCSA_NoDeadStrip
);
2850 /// parseIdentifier:
2853 bool AsmParser::parseIdentifier(StringRef
&Res
) {
2854 // The assembler has relaxed rules for accepting identifiers, in particular we
2855 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2856 // separate tokens. At this level, we have already lexed so we cannot (currently)
2857 // handle this as a context dependent token, instead we detect adjacent tokens
2858 // and return the combined identifier.
2859 if (Lexer
.is(AsmToken::Dollar
) || Lexer
.is(AsmToken::At
)) {
2860 SMLoc PrefixLoc
= getLexer().getLoc();
2862 // Consume the prefix character, and check for a following identifier.
2865 Lexer
.peekTokens(Buf
, false);
2867 if (Buf
[0].isNot(AsmToken::Identifier
))
2870 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2871 if (PrefixLoc
.getPointer() + 1 != Buf
[0].getLoc().getPointer())
2875 Lexer
.Lex(); // Lexer's Lex guarantees consecutive token.
2876 // Construct the joined identifier and consume the token.
2878 StringRef(PrefixLoc
.getPointer(), getTok().getIdentifier().size() + 1);
2879 Lex(); // Parser Lex to maintain invariants.
2883 if (Lexer
.isNot(AsmToken::Identifier
) && Lexer
.isNot(AsmToken::String
))
2886 Res
= getTok().getIdentifier();
2888 Lex(); // Consume the identifier token.
2893 /// parseDirectiveSet:
2894 /// ::= .equ identifier ',' expression
2895 /// ::= .equiv identifier ',' expression
2896 /// ::= .set identifier ',' expression
2897 bool AsmParser::parseDirectiveSet(StringRef IDVal
, bool allow_redef
) {
2899 if (check(parseIdentifier(Name
), "expected identifier") ||
2900 parseToken(AsmToken::Comma
) || parseAssignment(Name
, allow_redef
, true))
2901 return addErrorSuffix(" in '" + Twine(IDVal
) + "' directive");
2905 bool AsmParser::parseEscapedString(std::string
&Data
) {
2906 if (check(getTok().isNot(AsmToken::String
), "expected string"))
2910 StringRef Str
= getTok().getStringContents();
2911 for (unsigned i
= 0, e
= Str
.size(); i
!= e
; ++i
) {
2912 if (Str
[i
] != '\\') {
2917 // Recognize escaped characters. Note that this escape semantics currently
2918 // loosely follows Darwin 'as'.
2921 return TokError("unexpected backslash at end of string");
2923 // Recognize hex sequences similarly to GNU 'as'.
2924 if (Str
[i
] == 'x' || Str
[i
] == 'X') {
2925 size_t length
= Str
.size();
2926 if (i
+ 1 >= length
|| !isHexDigit(Str
[i
+ 1]))
2927 return TokError("invalid hexadecimal escape sequence");
2929 // Consume hex characters. GNU 'as' reads all hexadecimal characters and
2930 // then truncates to the lower 16 bits. Seems reasonable.
2932 while (i
+ 1 < length
&& isHexDigit(Str
[i
+ 1]))
2933 Value
= Value
* 16 + hexDigitValue(Str
[++i
]);
2935 Data
+= (unsigned char)(Value
& 0xFF);
2939 // Recognize octal sequences.
2940 if ((unsigned)(Str
[i
] - '0') <= 7) {
2941 // Consume up to three octal characters.
2942 unsigned Value
= Str
[i
] - '0';
2944 if (i
+ 1 != e
&& ((unsigned)(Str
[i
+ 1] - '0')) <= 7) {
2946 Value
= Value
* 8 + (Str
[i
] - '0');
2948 if (i
+ 1 != e
&& ((unsigned)(Str
[i
+ 1] - '0')) <= 7) {
2950 Value
= Value
* 8 + (Str
[i
] - '0');
2955 return TokError("invalid octal escape sequence (out of range)");
2957 Data
+= (unsigned char)Value
;
2961 // Otherwise recognize individual escapes.
2964 // Just reject invalid escape sequences for now.
2965 return TokError("invalid escape sequence (unrecognized character)");
2967 case 'b': Data
+= '\b'; break;
2968 case 'f': Data
+= '\f'; break;
2969 case 'n': Data
+= '\n'; break;
2970 case 'r': Data
+= '\r'; break;
2971 case 't': Data
+= '\t'; break;
2972 case '"': Data
+= '"'; break;
2973 case '\\': Data
+= '\\'; break;
2981 /// parseDirectiveAscii:
2982 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2983 bool AsmParser::parseDirectiveAscii(StringRef IDVal
, bool ZeroTerminated
) {
2984 auto parseOp
= [&]() -> bool {
2986 if (checkForValidSection() || parseEscapedString(Data
))
2988 getStreamer().EmitBytes(Data
);
2990 getStreamer().EmitBytes(StringRef("\0", 1));
2994 if (parseMany(parseOp
))
2995 return addErrorSuffix(" in '" + Twine(IDVal
) + "' directive");
2999 /// parseDirectiveReloc
3000 /// ::= .reloc expression , identifier [ , expression ]
3001 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc
) {
3002 const MCExpr
*Offset
;
3003 const MCExpr
*Expr
= nullptr;
3004 int64_t OffsetValue
;
3005 SMLoc OffsetLoc
= Lexer
.getTok().getLoc();
3007 if (parseExpression(Offset
))
3010 if ((Offset
->evaluateAsAbsolute(OffsetValue
,
3011 getStreamer().getAssemblerPtr()) &&
3012 check(OffsetValue
< 0, OffsetLoc
, "expression is negative")) ||
3013 (check(Offset
->getKind() != llvm::MCExpr::Constant
&&
3014 Offset
->getKind() != llvm::MCExpr::SymbolRef
,
3015 OffsetLoc
, "expected non-negative number or a label")) ||
3016 (parseToken(AsmToken::Comma
, "expected comma") ||
3017 check(getTok().isNot(AsmToken::Identifier
), "expected relocation name")))
3020 SMLoc NameLoc
= Lexer
.getTok().getLoc();
3021 StringRef Name
= Lexer
.getTok().getIdentifier();
3024 if (Lexer
.is(AsmToken::Comma
)) {
3026 SMLoc ExprLoc
= Lexer
.getLoc();
3027 if (parseExpression(Expr
))
3031 if (!Expr
->evaluateAsRelocatable(Value
, nullptr, nullptr))
3032 return Error(ExprLoc
, "expression must be relocatable");
3035 if (parseToken(AsmToken::EndOfStatement
,
3036 "unexpected token in .reloc directive"))
3039 const MCTargetAsmParser
&MCT
= getTargetParser();
3040 const MCSubtargetInfo
&STI
= MCT
.getSTI();
3041 if (getStreamer().EmitRelocDirective(*Offset
, Name
, Expr
, DirectiveLoc
, STI
))
3042 return Error(NameLoc
, "unknown relocation name");
3047 /// parseDirectiveValue
3048 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
3049 bool AsmParser::parseDirectiveValue(StringRef IDVal
, unsigned Size
) {
3050 auto parseOp
= [&]() -> bool {
3051 const MCExpr
*Value
;
3052 SMLoc ExprLoc
= getLexer().getLoc();
3053 if (checkForValidSection() || parseExpression(Value
))
3055 // Special case constant expressions to match code generator.
3056 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3057 assert(Size
<= 8 && "Invalid size");
3058 uint64_t IntValue
= MCE
->getValue();
3059 if (!isUIntN(8 * Size
, IntValue
) && !isIntN(8 * Size
, IntValue
))
3060 return Error(ExprLoc
, "out of range literal value");
3061 getStreamer().EmitIntValue(IntValue
, Size
);
3063 getStreamer().EmitValue(Value
, Size
, ExprLoc
);
3067 if (parseMany(parseOp
))
3068 return addErrorSuffix(" in '" + Twine(IDVal
) + "' directive");
3072 static bool parseHexOcta(AsmParser
&Asm
, uint64_t &hi
, uint64_t &lo
) {
3073 if (Asm
.getTok().isNot(AsmToken::Integer
) &&
3074 Asm
.getTok().isNot(AsmToken::BigNum
))
3075 return Asm
.TokError("unknown token in expression");
3076 SMLoc ExprLoc
= Asm
.getTok().getLoc();
3077 APInt IntValue
= Asm
.getTok().getAPIntVal();
3079 if (!IntValue
.isIntN(128))
3080 return Asm
.Error(ExprLoc
, "out of range literal value");
3081 if (!IntValue
.isIntN(64)) {
3082 hi
= IntValue
.getHiBits(IntValue
.getBitWidth() - 64).getZExtValue();
3083 lo
= IntValue
.getLoBits(64).getZExtValue();
3086 lo
= IntValue
.getZExtValue();
3091 /// ParseDirectiveOctaValue
3092 /// ::= .octa [ hexconstant (, hexconstant)* ]
3094 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal
) {
3095 auto parseOp
= [&]() -> bool {
3096 if (checkForValidSection())
3099 if (parseHexOcta(*this, hi
, lo
))
3101 if (MAI
.isLittleEndian()) {
3102 getStreamer().EmitIntValue(lo
, 8);
3103 getStreamer().EmitIntValue(hi
, 8);
3105 getStreamer().EmitIntValue(hi
, 8);
3106 getStreamer().EmitIntValue(lo
, 8);
3111 if (parseMany(parseOp
))
3112 return addErrorSuffix(" in '" + Twine(IDVal
) + "' directive");
3116 bool AsmParser::parseRealValue(const fltSemantics
&Semantics
, APInt
&Res
) {
3117 // We don't truly support arithmetic on floating point expressions, so we
3118 // have to manually parse unary prefixes.
3120 if (getLexer().is(AsmToken::Minus
)) {
3123 } else if (getLexer().is(AsmToken::Plus
))
3126 if (Lexer
.is(AsmToken::Error
))
3127 return TokError(Lexer
.getErr());
3128 if (Lexer
.isNot(AsmToken::Integer
) && Lexer
.isNot(AsmToken::Real
) &&
3129 Lexer
.isNot(AsmToken::Identifier
))
3130 return TokError("unexpected token in directive");
3132 // Convert to an APFloat.
3133 APFloat
Value(Semantics
);
3134 StringRef IDVal
= getTok().getString();
3135 if (getLexer().is(AsmToken::Identifier
)) {
3136 if (!IDVal
.compare_lower("infinity") || !IDVal
.compare_lower("inf"))
3137 Value
= APFloat::getInf(Semantics
);
3138 else if (!IDVal
.compare_lower("nan"))
3139 Value
= APFloat::getNaN(Semantics
, false, ~0);
3141 return TokError("invalid floating point literal");
3142 } else if (Value
.convertFromString(IDVal
, APFloat::rmNearestTiesToEven
) ==
3143 APFloat::opInvalidOp
)
3144 return TokError("invalid floating point literal");
3148 // Consume the numeric token.
3151 Res
= Value
.bitcastToAPInt();
3156 /// parseDirectiveRealValue
3157 /// ::= (.single | .double) [ expression (, expression)* ]
3158 bool AsmParser::parseDirectiveRealValue(StringRef IDVal
,
3159 const fltSemantics
&Semantics
) {
3160 auto parseOp
= [&]() -> bool {
3162 if (checkForValidSection() || parseRealValue(Semantics
, AsInt
))
3164 getStreamer().EmitIntValue(AsInt
.getLimitedValue(),
3165 AsInt
.getBitWidth() / 8);
3169 if (parseMany(parseOp
))
3170 return addErrorSuffix(" in '" + Twine(IDVal
) + "' directive");
3174 /// parseDirectiveZero
3175 /// ::= .zero expression
3176 bool AsmParser::parseDirectiveZero() {
3177 SMLoc NumBytesLoc
= Lexer
.getLoc();
3178 const MCExpr
*NumBytes
;
3179 if (checkForValidSection() || parseExpression(NumBytes
))
3183 if (getLexer().is(AsmToken::Comma
)) {
3185 if (parseAbsoluteExpression(Val
))
3189 if (parseToken(AsmToken::EndOfStatement
,
3190 "unexpected token in '.zero' directive"))
3192 getStreamer().emitFill(*NumBytes
, Val
, NumBytesLoc
);
3197 /// parseDirectiveFill
3198 /// ::= .fill expression [ , expression [ , expression ] ]
3199 bool AsmParser::parseDirectiveFill() {
3200 SMLoc NumValuesLoc
= Lexer
.getLoc();
3201 const MCExpr
*NumValues
;
3202 if (checkForValidSection() || parseExpression(NumValues
))
3205 int64_t FillSize
= 1;
3206 int64_t FillExpr
= 0;
3208 SMLoc SizeLoc
, ExprLoc
;
3210 if (parseOptionalToken(AsmToken::Comma
)) {
3211 SizeLoc
= getTok().getLoc();
3212 if (parseAbsoluteExpression(FillSize
))
3214 if (parseOptionalToken(AsmToken::Comma
)) {
3215 ExprLoc
= getTok().getLoc();
3216 if (parseAbsoluteExpression(FillExpr
))
3220 if (parseToken(AsmToken::EndOfStatement
,
3221 "unexpected token in '.fill' directive"))
3225 Warning(SizeLoc
, "'.fill' directive with negative size has no effect");
3229 Warning(SizeLoc
, "'.fill' directive with size greater than 8 has been truncated to 8");
3233 if (!isUInt
<32>(FillExpr
) && FillSize
> 4)
3234 Warning(ExprLoc
, "'.fill' directive pattern has been truncated to 32-bits");
3236 getStreamer().emitFill(*NumValues
, FillSize
, FillExpr
, NumValuesLoc
);
3241 /// parseDirectiveOrg
3242 /// ::= .org expression [ , expression ]
3243 bool AsmParser::parseDirectiveOrg() {
3244 const MCExpr
*Offset
;
3245 SMLoc OffsetLoc
= Lexer
.getLoc();
3246 if (checkForValidSection() || parseExpression(Offset
))
3249 // Parse optional fill expression.
3250 int64_t FillExpr
= 0;
3251 if (parseOptionalToken(AsmToken::Comma
))
3252 if (parseAbsoluteExpression(FillExpr
))
3253 return addErrorSuffix(" in '.org' directive");
3254 if (parseToken(AsmToken::EndOfStatement
))
3255 return addErrorSuffix(" in '.org' directive");
3257 getStreamer().emitValueToOffset(Offset
, FillExpr
, OffsetLoc
);
3261 /// parseDirectiveAlign
3262 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3263 bool AsmParser::parseDirectiveAlign(bool IsPow2
, unsigned ValueSize
) {
3264 SMLoc AlignmentLoc
= getLexer().getLoc();
3267 bool HasFillExpr
= false;
3268 int64_t FillExpr
= 0;
3269 int64_t MaxBytesToFill
= 0;
3271 auto parseAlign
= [&]() -> bool {
3272 if (parseAbsoluteExpression(Alignment
))
3274 if (parseOptionalToken(AsmToken::Comma
)) {
3275 // The fill expression can be omitted while specifying a maximum number of
3276 // alignment bytes, e.g:
3278 if (getTok().isNot(AsmToken::Comma
)) {
3280 if (parseAbsoluteExpression(FillExpr
))
3283 if (parseOptionalToken(AsmToken::Comma
))
3284 if (parseTokenLoc(MaxBytesLoc
) ||
3285 parseAbsoluteExpression(MaxBytesToFill
))
3288 return parseToken(AsmToken::EndOfStatement
);
3291 if (checkForValidSection())
3292 return addErrorSuffix(" in directive");
3293 // Ignore empty '.p2align' directives for GNU-as compatibility
3294 if (IsPow2
&& (ValueSize
== 1) && getTok().is(AsmToken::EndOfStatement
)) {
3295 Warning(AlignmentLoc
, "p2align directive with no operand(s) is ignored");
3296 return parseToken(AsmToken::EndOfStatement
);
3299 return addErrorSuffix(" in directive");
3301 // Always emit an alignment here even if we thrown an error.
3302 bool ReturnVal
= false;
3304 // Compute alignment in bytes.
3306 // FIXME: Diagnose overflow.
3307 if (Alignment
>= 32) {
3308 ReturnVal
|= Error(AlignmentLoc
, "invalid alignment value");
3312 Alignment
= 1ULL << Alignment
;
3314 // Reject alignments that aren't either a power of two or zero,
3315 // for gas compatibility. Alignment of zero is silently rounded
3319 if (!isPowerOf2_64(Alignment
))
3320 ReturnVal
|= Error(AlignmentLoc
, "alignment must be a power of 2");
3323 // Diagnose non-sensical max bytes to align.
3324 if (MaxBytesLoc
.isValid()) {
3325 if (MaxBytesToFill
< 1) {
3326 ReturnVal
|= Error(MaxBytesLoc
,
3327 "alignment directive can never be satisfied in this "
3328 "many bytes, ignoring maximum bytes expression");
3332 if (MaxBytesToFill
>= Alignment
) {
3333 Warning(MaxBytesLoc
, "maximum bytes expression exceeds alignment and "
3339 // Check whether we should use optimal code alignment for this .align
3341 const MCSection
*Section
= getStreamer().getCurrentSectionOnly();
3342 assert(Section
&& "must have section to emit alignment");
3343 bool UseCodeAlign
= Section
->UseCodeAlign();
3344 if ((!HasFillExpr
|| Lexer
.getMAI().getTextAlignFillValue() == FillExpr
) &&
3345 ValueSize
== 1 && UseCodeAlign
) {
3346 getStreamer().EmitCodeAlignment(Alignment
, MaxBytesToFill
);
3348 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3349 getStreamer().EmitValueToAlignment(Alignment
, FillExpr
, ValueSize
,
3356 /// parseDirectiveFile
3357 /// ::= .file filename
3358 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3359 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc
) {
3360 // FIXME: I'm not sure what this is.
3361 int64_t FileNumber
= -1;
3362 if (getLexer().is(AsmToken::Integer
)) {
3363 FileNumber
= getTok().getIntVal();
3367 return TokError("negative file number");
3372 // Usually the directory and filename together, otherwise just the directory.
3373 // Allow the strings to have escaped octal character sequence.
3374 if (check(getTok().isNot(AsmToken::String
),
3375 "unexpected token in '.file' directive") ||
3376 parseEscapedString(Path
))
3379 StringRef Directory
;
3381 std::string FilenameData
;
3382 if (getLexer().is(AsmToken::String
)) {
3383 if (check(FileNumber
== -1,
3384 "explicit path specified, but no file number") ||
3385 parseEscapedString(FilenameData
))
3387 Filename
= FilenameData
;
3393 uint64_t MD5Hi
, MD5Lo
;
3394 bool HasMD5
= false;
3396 Optional
<StringRef
> Source
;
3397 bool HasSource
= false;
3398 std::string SourceString
;
3400 while (!parseOptionalToken(AsmToken::EndOfStatement
)) {
3402 if (check(getTok().isNot(AsmToken::Identifier
),
3403 "unexpected token in '.file' directive") ||
3404 parseIdentifier(Keyword
))
3406 if (Keyword
== "md5") {
3408 if (check(FileNumber
== -1,
3409 "MD5 checksum specified, but no file number") ||
3410 parseHexOcta(*this, MD5Hi
, MD5Lo
))
3412 } else if (Keyword
== "source") {
3414 if (check(FileNumber
== -1,
3415 "source specified, but no file number") ||
3416 check(getTok().isNot(AsmToken::String
),
3417 "unexpected token in '.file' directive") ||
3418 parseEscapedString(SourceString
))
3421 return TokError("unexpected token in '.file' directive");
3425 if (FileNumber
== -1) {
3426 // Ignore the directive if there is no number and the target doesn't support
3427 // numberless .file directives. This allows some portability of assembler
3428 // between different object file formats.
3429 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3430 getStreamer().EmitFileDirective(Filename
);
3432 // In case there is a -g option as well as debug info from directive .file,
3433 // we turn off the -g option, directly use the existing debug info instead.
3434 // Throw away any implicit file table for the assembler source.
3435 if (Ctx
.getGenDwarfForAssembly()) {
3436 Ctx
.getMCDwarfLineTable(0).resetFileTable();
3437 Ctx
.setGenDwarfForAssembly(false);
3440 Optional
<MD5::MD5Result
> CKMem
;
3443 for (unsigned i
= 0; i
!= 8; ++i
) {
3444 Sum
.Bytes
[i
] = uint8_t(MD5Hi
>> ((7 - i
) * 8));
3445 Sum
.Bytes
[i
+ 8] = uint8_t(MD5Lo
>> ((7 - i
) * 8));
3450 char *SourceBuf
= static_cast<char *>(Ctx
.allocate(SourceString
.size()));
3451 memcpy(SourceBuf
, SourceString
.data(), SourceString
.size());
3452 Source
= StringRef(SourceBuf
, SourceString
.size());
3454 if (FileNumber
== 0) {
3455 if (Ctx
.getDwarfVersion() < 5)
3456 return Warning(DirectiveLoc
, "file 0 not supported prior to DWARF-5");
3457 getStreamer().emitDwarfFile0Directive(Directory
, Filename
, CKMem
, Source
);
3459 Expected
<unsigned> FileNumOrErr
= getStreamer().tryEmitDwarfFileDirective(
3460 FileNumber
, Directory
, Filename
, CKMem
, Source
);
3462 return Error(DirectiveLoc
, toString(FileNumOrErr
.takeError()));
3464 // Alert the user if there are some .file directives with MD5 and some not.
3465 // But only do that once.
3466 if (!ReportedInconsistentMD5
&& !Ctx
.isDwarfMD5UsageConsistent(0)) {
3467 ReportedInconsistentMD5
= true;
3468 return Warning(DirectiveLoc
, "inconsistent use of MD5 checksums");
3475 /// parseDirectiveLine
3476 /// ::= .line [number]
3477 bool AsmParser::parseDirectiveLine() {
3479 if (getLexer().is(AsmToken::Integer
)) {
3480 if (parseIntToken(LineNumber
, "unexpected token in '.line' directive"))
3483 // FIXME: Do something with the .line.
3485 if (parseToken(AsmToken::EndOfStatement
,
3486 "unexpected token in '.line' directive"))
3492 /// parseDirectiveLoc
3493 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3494 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3495 /// The first number is a file number, must have been previously assigned with
3496 /// a .file directive, the second number is the line number and optionally the
3497 /// third number is a column position (zero if not specified). The remaining
3498 /// optional items are .loc sub-directives.
3499 bool AsmParser::parseDirectiveLoc() {
3500 int64_t FileNumber
= 0, LineNumber
= 0;
3501 SMLoc Loc
= getTok().getLoc();
3502 if (parseIntToken(FileNumber
, "unexpected token in '.loc' directive") ||
3503 check(FileNumber
< 1 && Ctx
.getDwarfVersion() < 5, Loc
,
3504 "file number less than one in '.loc' directive") ||
3505 check(!getContext().isValidDwarfFileNumber(FileNumber
), Loc
,
3506 "unassigned file number in '.loc' directive"))
3510 if (getLexer().is(AsmToken::Integer
)) {
3511 LineNumber
= getTok().getIntVal();
3513 return TokError("line number less than zero in '.loc' directive");
3517 int64_t ColumnPos
= 0;
3518 if (getLexer().is(AsmToken::Integer
)) {
3519 ColumnPos
= getTok().getIntVal();
3521 return TokError("column position less than zero in '.loc' directive");
3525 unsigned Flags
= DWARF2_LINE_DEFAULT_IS_STMT
? DWARF2_FLAG_IS_STMT
: 0;
3527 int64_t Discriminator
= 0;
3529 auto parseLocOp
= [&]() -> bool {
3531 SMLoc Loc
= getTok().getLoc();
3532 if (parseIdentifier(Name
))
3533 return TokError("unexpected token in '.loc' directive");
3535 if (Name
== "basic_block")
3536 Flags
|= DWARF2_FLAG_BASIC_BLOCK
;
3537 else if (Name
== "prologue_end")
3538 Flags
|= DWARF2_FLAG_PROLOGUE_END
;
3539 else if (Name
== "epilogue_begin")
3540 Flags
|= DWARF2_FLAG_EPILOGUE_BEGIN
;
3541 else if (Name
== "is_stmt") {
3542 Loc
= getTok().getLoc();
3543 const MCExpr
*Value
;
3544 if (parseExpression(Value
))
3546 // The expression must be the constant 0 or 1.
3547 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3548 int Value
= MCE
->getValue();
3550 Flags
&= ~DWARF2_FLAG_IS_STMT
;
3551 else if (Value
== 1)
3552 Flags
|= DWARF2_FLAG_IS_STMT
;
3554 return Error(Loc
, "is_stmt value not 0 or 1");
3556 return Error(Loc
, "is_stmt value not the constant value of 0 or 1");
3558 } else if (Name
== "isa") {
3559 Loc
= getTok().getLoc();
3560 const MCExpr
*Value
;
3561 if (parseExpression(Value
))
3563 // The expression must be a constant greater or equal to 0.
3564 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3565 int Value
= MCE
->getValue();
3567 return Error(Loc
, "isa number less than zero");
3570 return Error(Loc
, "isa number not a constant value");
3572 } else if (Name
== "discriminator") {
3573 if (parseAbsoluteExpression(Discriminator
))
3576 return Error(Loc
, "unknown sub-directive in '.loc' directive");
3581 if (parseMany(parseLocOp
, false /*hasComma*/))
3584 getStreamer().EmitDwarfLocDirective(FileNumber
, LineNumber
, ColumnPos
, Flags
,
3585 Isa
, Discriminator
, StringRef());
3590 /// parseDirectiveStabs
3591 /// ::= .stabs string, number, number, number
3592 bool AsmParser::parseDirectiveStabs() {
3593 return TokError("unsupported directive '.stabs'");
3596 /// parseDirectiveCVFile
3597 /// ::= .cv_file number filename [checksum] [checksumkind]
3598 bool AsmParser::parseDirectiveCVFile() {
3599 SMLoc FileNumberLoc
= getTok().getLoc();
3601 std::string Filename
;
3602 std::string Checksum
;
3603 int64_t ChecksumKind
= 0;
3605 if (parseIntToken(FileNumber
,
3606 "expected file number in '.cv_file' directive") ||
3607 check(FileNumber
< 1, FileNumberLoc
, "file number less than one") ||
3608 check(getTok().isNot(AsmToken::String
),
3609 "unexpected token in '.cv_file' directive") ||
3610 parseEscapedString(Filename
))
3612 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
3613 if (check(getTok().isNot(AsmToken::String
),
3614 "unexpected token in '.cv_file' directive") ||
3615 parseEscapedString(Checksum
) ||
3616 parseIntToken(ChecksumKind
,
3617 "expected checksum kind in '.cv_file' directive") ||
3618 parseToken(AsmToken::EndOfStatement
,
3619 "unexpected token in '.cv_file' directive"))
3623 Checksum
= fromHex(Checksum
);
3624 void *CKMem
= Ctx
.allocate(Checksum
.size(), 1);
3625 memcpy(CKMem
, Checksum
.data(), Checksum
.size());
3626 ArrayRef
<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem
),
3629 if (!getStreamer().EmitCVFileDirective(FileNumber
, Filename
, ChecksumAsBytes
,
3630 static_cast<uint8_t>(ChecksumKind
)))
3631 return Error(FileNumberLoc
, "file number already allocated");
3636 bool AsmParser::parseCVFunctionId(int64_t &FunctionId
,
3637 StringRef DirectiveName
) {
3639 return parseTokenLoc(Loc
) ||
3640 parseIntToken(FunctionId
, "expected function id in '" + DirectiveName
+
3642 check(FunctionId
< 0 || FunctionId
>= UINT_MAX
, Loc
,
3643 "expected function id within range [0, UINT_MAX)");
3646 bool AsmParser::parseCVFileId(int64_t &FileNumber
, StringRef DirectiveName
) {
3648 return parseTokenLoc(Loc
) ||
3649 parseIntToken(FileNumber
, "expected integer in '" + DirectiveName
+
3651 check(FileNumber
< 1, Loc
, "file number less than one in '" +
3652 DirectiveName
+ "' directive") ||
3653 check(!getCVContext().isValidFileNumber(FileNumber
), Loc
,
3654 "unassigned file number in '" + DirectiveName
+ "' directive");
3657 /// parseDirectiveCVFuncId
3658 /// ::= .cv_func_id FunctionId
3660 /// Introduces a function ID that can be used with .cv_loc.
3661 bool AsmParser::parseDirectiveCVFuncId() {
3662 SMLoc FunctionIdLoc
= getTok().getLoc();
3665 if (parseCVFunctionId(FunctionId
, ".cv_func_id") ||
3666 parseToken(AsmToken::EndOfStatement
,
3667 "unexpected token in '.cv_func_id' directive"))
3670 if (!getStreamer().EmitCVFuncIdDirective(FunctionId
))
3671 return Error(FunctionIdLoc
, "function id already allocated");
3676 /// parseDirectiveCVInlineSiteId
3677 /// ::= .cv_inline_site_id FunctionId
3679 /// "inlined_at" IAFile IALine [IACol]
3681 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3682 /// at" source location information for use in the line table of the caller,
3683 /// whether the caller is a real function or another inlined call site.
3684 bool AsmParser::parseDirectiveCVInlineSiteId() {
3685 SMLoc FunctionIdLoc
= getTok().getLoc();
3693 if (parseCVFunctionId(FunctionId
, ".cv_inline_site_id"))
3697 if (check((getLexer().isNot(AsmToken::Identifier
) ||
3698 getTok().getIdentifier() != "within"),
3699 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3704 if (parseCVFunctionId(IAFunc
, ".cv_inline_site_id"))
3708 if (check((getLexer().isNot(AsmToken::Identifier
) ||
3709 getTok().getIdentifier() != "inlined_at"),
3710 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3716 if (parseCVFileId(IAFile
, ".cv_inline_site_id") ||
3717 parseIntToken(IALine
, "expected line number after 'inlined_at'"))
3721 if (getLexer().is(AsmToken::Integer
)) {
3722 IACol
= getTok().getIntVal();
3726 if (parseToken(AsmToken::EndOfStatement
,
3727 "unexpected token in '.cv_inline_site_id' directive"))
3730 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId
, IAFunc
, IAFile
,
3731 IALine
, IACol
, FunctionIdLoc
))
3732 return Error(FunctionIdLoc
, "function id already allocated");
3737 /// parseDirectiveCVLoc
3738 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3740 /// The first number is a file number, must have been previously assigned with
3741 /// a .file directive, the second number is the line number and optionally the
3742 /// third number is a column position (zero if not specified). The remaining
3743 /// optional items are .loc sub-directives.
3744 bool AsmParser::parseDirectiveCVLoc() {
3745 SMLoc DirectiveLoc
= getTok().getLoc();
3746 int64_t FunctionId
, FileNumber
;
3747 if (parseCVFunctionId(FunctionId
, ".cv_loc") ||
3748 parseCVFileId(FileNumber
, ".cv_loc"))
3751 int64_t LineNumber
= 0;
3752 if (getLexer().is(AsmToken::Integer
)) {
3753 LineNumber
= getTok().getIntVal();
3755 return TokError("line number less than zero in '.cv_loc' directive");
3759 int64_t ColumnPos
= 0;
3760 if (getLexer().is(AsmToken::Integer
)) {
3761 ColumnPos
= getTok().getIntVal();
3763 return TokError("column position less than zero in '.cv_loc' directive");
3767 bool PrologueEnd
= false;
3768 uint64_t IsStmt
= 0;
3770 auto parseOp
= [&]() -> bool {
3772 SMLoc Loc
= getTok().getLoc();
3773 if (parseIdentifier(Name
))
3774 return TokError("unexpected token in '.cv_loc' directive");
3775 if (Name
== "prologue_end")
3777 else if (Name
== "is_stmt") {
3778 Loc
= getTok().getLoc();
3779 const MCExpr
*Value
;
3780 if (parseExpression(Value
))
3782 // The expression must be the constant 0 or 1.
3784 if (const auto *MCE
= dyn_cast
<MCConstantExpr
>(Value
))
3785 IsStmt
= MCE
->getValue();
3788 return Error(Loc
, "is_stmt value not 0 or 1");
3790 return Error(Loc
, "unknown sub-directive in '.cv_loc' directive");
3795 if (parseMany(parseOp
, false /*hasComma*/))
3798 getStreamer().EmitCVLocDirective(FunctionId
, FileNumber
, LineNumber
,
3799 ColumnPos
, PrologueEnd
, IsStmt
, StringRef(),
3804 /// parseDirectiveCVLinetable
3805 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3806 bool AsmParser::parseDirectiveCVLinetable() {
3808 StringRef FnStartName
, FnEndName
;
3809 SMLoc Loc
= getTok().getLoc();
3810 if (parseCVFunctionId(FunctionId
, ".cv_linetable") ||
3811 parseToken(AsmToken::Comma
,
3812 "unexpected token in '.cv_linetable' directive") ||
3813 parseTokenLoc(Loc
) || check(parseIdentifier(FnStartName
), Loc
,
3814 "expected identifier in directive") ||
3815 parseToken(AsmToken::Comma
,
3816 "unexpected token in '.cv_linetable' directive") ||
3817 parseTokenLoc(Loc
) || check(parseIdentifier(FnEndName
), Loc
,
3818 "expected identifier in directive"))
3821 MCSymbol
*FnStartSym
= getContext().getOrCreateSymbol(FnStartName
);
3822 MCSymbol
*FnEndSym
= getContext().getOrCreateSymbol(FnEndName
);
3824 getStreamer().EmitCVLinetableDirective(FunctionId
, FnStartSym
, FnEndSym
);
3828 /// parseDirectiveCVInlineLinetable
3829 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3830 bool AsmParser::parseDirectiveCVInlineLinetable() {
3831 int64_t PrimaryFunctionId
, SourceFileId
, SourceLineNum
;
3832 StringRef FnStartName
, FnEndName
;
3833 SMLoc Loc
= getTok().getLoc();
3834 if (parseCVFunctionId(PrimaryFunctionId
, ".cv_inline_linetable") ||
3835 parseTokenLoc(Loc
) ||
3838 "expected SourceField in '.cv_inline_linetable' directive") ||
3839 check(SourceFileId
<= 0, Loc
,
3840 "File id less than zero in '.cv_inline_linetable' directive") ||
3841 parseTokenLoc(Loc
) ||
3844 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3845 check(SourceLineNum
< 0, Loc
,
3846 "Line number less than zero in '.cv_inline_linetable' directive") ||
3847 parseTokenLoc(Loc
) || check(parseIdentifier(FnStartName
), Loc
,
3848 "expected identifier in directive") ||
3849 parseTokenLoc(Loc
) || check(parseIdentifier(FnEndName
), Loc
,
3850 "expected identifier in directive"))
3853 if (parseToken(AsmToken::EndOfStatement
, "Expected End of Statement"))
3856 MCSymbol
*FnStartSym
= getContext().getOrCreateSymbol(FnStartName
);
3857 MCSymbol
*FnEndSym
= getContext().getOrCreateSymbol(FnEndName
);
3858 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId
, SourceFileId
,
3859 SourceLineNum
, FnStartSym
,
3864 void AsmParser::initializeCVDefRangeTypeMap() {
3865 CVDefRangeTypeMap
["reg"] = CVDR_DEFRANGE_REGISTER
;
3866 CVDefRangeTypeMap
["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL
;
3867 CVDefRangeTypeMap
["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER
;
3868 CVDefRangeTypeMap
["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL
;
3871 /// parseDirectiveCVDefRange
3872 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3873 bool AsmParser::parseDirectiveCVDefRange() {
3875 std::vector
<std::pair
<const MCSymbol
*, const MCSymbol
*>> Ranges
;
3876 while (getLexer().is(AsmToken::Identifier
)) {
3877 Loc
= getLexer().getLoc();
3878 StringRef GapStartName
;
3879 if (parseIdentifier(GapStartName
))
3880 return Error(Loc
, "expected identifier in directive");
3881 MCSymbol
*GapStartSym
= getContext().getOrCreateSymbol(GapStartName
);
3883 Loc
= getLexer().getLoc();
3884 StringRef GapEndName
;
3885 if (parseIdentifier(GapEndName
))
3886 return Error(Loc
, "expected identifier in directive");
3887 MCSymbol
*GapEndSym
= getContext().getOrCreateSymbol(GapEndName
);
3889 Ranges
.push_back({GapStartSym
, GapEndSym
});
3892 StringRef CVDefRangeTypeStr
;
3895 "expected comma before def_range type in .cv_def_range directive") ||
3896 parseIdentifier(CVDefRangeTypeStr
))
3897 return Error(Loc
, "expected def_range type in directive");
3899 StringMap
<CVDefRangeType
>::const_iterator CVTypeIt
=
3900 CVDefRangeTypeMap
.find(CVDefRangeTypeStr
);
3901 CVDefRangeType CVDRType
= (CVTypeIt
== CVDefRangeTypeMap
.end())
3903 : CVTypeIt
->getValue();
3905 case CVDR_DEFRANGE_REGISTER
: {
3907 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
3908 ".cv_def_range directive") ||
3909 parseAbsoluteExpression(DRRegister
))
3910 return Error(Loc
, "expected register number");
3912 codeview::DefRangeRegisterHeader DRHdr
;
3913 DRHdr
.Register
= DRRegister
;
3914 DRHdr
.MayHaveNoName
= 0;
3915 getStreamer().EmitCVDefRangeDirective(Ranges
, DRHdr
);
3918 case CVDR_DEFRANGE_FRAMEPOINTER_REL
: {
3920 if (parseToken(AsmToken::Comma
,
3921 "expected comma before offset in .cv_def_range directive") ||
3922 parseAbsoluteExpression(DROffset
))
3923 return Error(Loc
, "expected offset value");
3925 codeview::DefRangeFramePointerRelHeader DRHdr
;
3926 DRHdr
.Offset
= DROffset
;
3927 getStreamer().EmitCVDefRangeDirective(Ranges
, DRHdr
);
3930 case CVDR_DEFRANGE_SUBFIELD_REGISTER
: {
3932 int64_t DROffsetInParent
;
3933 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
3934 ".cv_def_range directive") ||
3935 parseAbsoluteExpression(DRRegister
))
3936 return Error(Loc
, "expected register number");
3937 if (parseToken(AsmToken::Comma
,
3938 "expected comma before offset in .cv_def_range directive") ||
3939 parseAbsoluteExpression(DROffsetInParent
))
3940 return Error(Loc
, "expected offset value");
3942 codeview::DefRangeSubfieldRegisterHeader DRHdr
;
3943 DRHdr
.Register
= DRRegister
;
3944 DRHdr
.MayHaveNoName
= 0;
3945 DRHdr
.OffsetInParent
= DROffsetInParent
;
3946 getStreamer().EmitCVDefRangeDirective(Ranges
, DRHdr
);
3949 case CVDR_DEFRANGE_REGISTER_REL
: {
3952 int64_t DRBasePointerOffset
;
3953 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
3954 ".cv_def_range directive") ||
3955 parseAbsoluteExpression(DRRegister
))
3956 return Error(Loc
, "expected register value");
3959 "expected comma before flag value in .cv_def_range directive") ||
3960 parseAbsoluteExpression(DRFlags
))
3961 return Error(Loc
, "expected flag value");
3962 if (parseToken(AsmToken::Comma
, "expected comma before base pointer offset "
3963 "in .cv_def_range directive") ||
3964 parseAbsoluteExpression(DRBasePointerOffset
))
3965 return Error(Loc
, "expected base pointer offset value");
3967 codeview::DefRangeRegisterRelHeader DRHdr
;
3968 DRHdr
.Register
= DRRegister
;
3969 DRHdr
.Flags
= DRFlags
;
3970 DRHdr
.BasePointerOffset
= DRBasePointerOffset
;
3971 getStreamer().EmitCVDefRangeDirective(Ranges
, DRHdr
);
3975 return Error(Loc
, "unexpected def_range type in .cv_def_range directive");
3980 /// parseDirectiveCVString
3981 /// ::= .cv_stringtable "string"
3982 bool AsmParser::parseDirectiveCVString() {
3984 if (checkForValidSection() || parseEscapedString(Data
))
3985 return addErrorSuffix(" in '.cv_string' directive");
3987 // Put the string in the table and emit the offset.
3988 std::pair
<StringRef
, unsigned> Insertion
=
3989 getCVContext().addToStringTable(Data
);
3990 getStreamer().EmitIntValue(Insertion
.second
, 4);
3994 /// parseDirectiveCVStringTable
3995 /// ::= .cv_stringtable
3996 bool AsmParser::parseDirectiveCVStringTable() {
3997 getStreamer().EmitCVStringTableDirective();
4001 /// parseDirectiveCVFileChecksums
4002 /// ::= .cv_filechecksums
4003 bool AsmParser::parseDirectiveCVFileChecksums() {
4004 getStreamer().EmitCVFileChecksumsDirective();
4008 /// parseDirectiveCVFileChecksumOffset
4009 /// ::= .cv_filechecksumoffset fileno
4010 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4012 if (parseIntToken(FileNo
, "expected identifier in directive"))
4014 if (parseToken(AsmToken::EndOfStatement
, "Expected End of Statement"))
4016 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo
);
4020 /// parseDirectiveCVFPOData
4021 /// ::= .cv_fpo_data procsym
4022 bool AsmParser::parseDirectiveCVFPOData() {
4023 SMLoc DirLoc
= getLexer().getLoc();
4025 if (parseIdentifier(ProcName
))
4026 return TokError("expected symbol name");
4027 if (parseEOL("unexpected tokens"))
4028 return addErrorSuffix(" in '.cv_fpo_data' directive");
4029 MCSymbol
*ProcSym
= getContext().getOrCreateSymbol(ProcName
);
4030 getStreamer().EmitCVFPOData(ProcSym
, DirLoc
);
4034 /// parseDirectiveCFISections
4035 /// ::= .cfi_sections section [, section]
4036 bool AsmParser::parseDirectiveCFISections() {
4041 if (parseIdentifier(Name
))
4042 return TokError("Expected an identifier");
4044 if (Name
== ".eh_frame")
4046 else if (Name
== ".debug_frame")
4049 if (getLexer().is(AsmToken::Comma
)) {
4052 if (parseIdentifier(Name
))
4053 return TokError("Expected an identifier");
4055 if (Name
== ".eh_frame")
4057 else if (Name
== ".debug_frame")
4061 getStreamer().EmitCFISections(EH
, Debug
);
4065 /// parseDirectiveCFIStartProc
4066 /// ::= .cfi_startproc [simple]
4067 bool AsmParser::parseDirectiveCFIStartProc() {
4069 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
4070 if (check(parseIdentifier(Simple
) || Simple
!= "simple",
4071 "unexpected token") ||
4072 parseToken(AsmToken::EndOfStatement
))
4073 return addErrorSuffix(" in '.cfi_startproc' directive");
4076 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4077 // being produced if this directive is emitted as part of preprocessor macro
4078 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4079 // Tools like llvm-mc on the other hand are not affected by it, and report
4080 // correct context information.
4081 getStreamer().EmitCFIStartProc(!Simple
.empty(), Lexer
.getLoc());
4085 /// parseDirectiveCFIEndProc
4086 /// ::= .cfi_endproc
4087 bool AsmParser::parseDirectiveCFIEndProc() {
4088 getStreamer().EmitCFIEndProc();
4092 /// parse register name or number.
4093 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register
,
4094 SMLoc DirectiveLoc
) {
4097 if (getLexer().isNot(AsmToken::Integer
)) {
4098 if (getTargetParser().ParseRegister(RegNo
, DirectiveLoc
, DirectiveLoc
))
4100 Register
= getContext().getRegisterInfo()->getDwarfRegNum(RegNo
, true);
4102 return parseAbsoluteExpression(Register
);
4107 /// parseDirectiveCFIDefCfa
4108 /// ::= .cfi_def_cfa register, offset
4109 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc
) {
4110 int64_t Register
= 0, Offset
= 0;
4111 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) ||
4112 parseToken(AsmToken::Comma
, "unexpected token in directive") ||
4113 parseAbsoluteExpression(Offset
))
4116 getStreamer().EmitCFIDefCfa(Register
, Offset
);
4120 /// parseDirectiveCFIDefCfaOffset
4121 /// ::= .cfi_def_cfa_offset offset
4122 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
4124 if (parseAbsoluteExpression(Offset
))
4127 getStreamer().EmitCFIDefCfaOffset(Offset
);
4131 /// parseDirectiveCFIRegister
4132 /// ::= .cfi_register register, register
4133 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc
) {
4134 int64_t Register1
= 0, Register2
= 0;
4135 if (parseRegisterOrRegisterNumber(Register1
, DirectiveLoc
) ||
4136 parseToken(AsmToken::Comma
, "unexpected token in directive") ||
4137 parseRegisterOrRegisterNumber(Register2
, DirectiveLoc
))
4140 getStreamer().EmitCFIRegister(Register1
, Register2
);
4144 /// parseDirectiveCFIWindowSave
4145 /// ::= .cfi_window_save
4146 bool AsmParser::parseDirectiveCFIWindowSave() {
4147 getStreamer().EmitCFIWindowSave();
4151 /// parseDirectiveCFIAdjustCfaOffset
4152 /// ::= .cfi_adjust_cfa_offset adjustment
4153 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
4154 int64_t Adjustment
= 0;
4155 if (parseAbsoluteExpression(Adjustment
))
4158 getStreamer().EmitCFIAdjustCfaOffset(Adjustment
);
4162 /// parseDirectiveCFIDefCfaRegister
4163 /// ::= .cfi_def_cfa_register register
4164 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc
) {
4165 int64_t Register
= 0;
4166 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
))
4169 getStreamer().EmitCFIDefCfaRegister(Register
);
4173 /// parseDirectiveCFIOffset
4174 /// ::= .cfi_offset register, offset
4175 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc
) {
4176 int64_t Register
= 0;
4179 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) ||
4180 parseToken(AsmToken::Comma
, "unexpected token in directive") ||
4181 parseAbsoluteExpression(Offset
))
4184 getStreamer().EmitCFIOffset(Register
, Offset
);
4188 /// parseDirectiveCFIRelOffset
4189 /// ::= .cfi_rel_offset register, offset
4190 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc
) {
4191 int64_t Register
= 0, Offset
= 0;
4193 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) ||
4194 parseToken(AsmToken::Comma
, "unexpected token in directive") ||
4195 parseAbsoluteExpression(Offset
))
4198 getStreamer().EmitCFIRelOffset(Register
, Offset
);
4202 static bool isValidEncoding(int64_t Encoding
) {
4203 if (Encoding
& ~0xff)
4206 if (Encoding
== dwarf::DW_EH_PE_omit
)
4209 const unsigned Format
= Encoding
& 0xf;
4210 if (Format
!= dwarf::DW_EH_PE_absptr
&& Format
!= dwarf::DW_EH_PE_udata2
&&
4211 Format
!= dwarf::DW_EH_PE_udata4
&& Format
!= dwarf::DW_EH_PE_udata8
&&
4212 Format
!= dwarf::DW_EH_PE_sdata2
&& Format
!= dwarf::DW_EH_PE_sdata4
&&
4213 Format
!= dwarf::DW_EH_PE_sdata8
&& Format
!= dwarf::DW_EH_PE_signed
)
4216 const unsigned Application
= Encoding
& 0x70;
4217 if (Application
!= dwarf::DW_EH_PE_absptr
&&
4218 Application
!= dwarf::DW_EH_PE_pcrel
)
4224 /// parseDirectiveCFIPersonalityOrLsda
4225 /// IsPersonality true for cfi_personality, false for cfi_lsda
4226 /// ::= .cfi_personality encoding, [symbol_name]
4227 /// ::= .cfi_lsda encoding, [symbol_name]
4228 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality
) {
4229 int64_t Encoding
= 0;
4230 if (parseAbsoluteExpression(Encoding
))
4232 if (Encoding
== dwarf::DW_EH_PE_omit
)
4236 if (check(!isValidEncoding(Encoding
), "unsupported encoding.") ||
4237 parseToken(AsmToken::Comma
, "unexpected token in directive") ||
4238 check(parseIdentifier(Name
), "expected identifier in directive"))
4241 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
4244 getStreamer().EmitCFIPersonality(Sym
, Encoding
);
4246 getStreamer().EmitCFILsda(Sym
, Encoding
);
4250 /// parseDirectiveCFIRememberState
4251 /// ::= .cfi_remember_state
4252 bool AsmParser::parseDirectiveCFIRememberState() {
4253 getStreamer().EmitCFIRememberState();
4257 /// parseDirectiveCFIRestoreState
4258 /// ::= .cfi_remember_state
4259 bool AsmParser::parseDirectiveCFIRestoreState() {
4260 getStreamer().EmitCFIRestoreState();
4264 /// parseDirectiveCFISameValue
4265 /// ::= .cfi_same_value register
4266 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc
) {
4267 int64_t Register
= 0;
4269 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
))
4272 getStreamer().EmitCFISameValue(Register
);
4276 /// parseDirectiveCFIRestore
4277 /// ::= .cfi_restore register
4278 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc
) {
4279 int64_t Register
= 0;
4280 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
))
4283 getStreamer().EmitCFIRestore(Register
);
4287 /// parseDirectiveCFIEscape
4288 /// ::= .cfi_escape expression[,...]
4289 bool AsmParser::parseDirectiveCFIEscape() {
4292 if (parseAbsoluteExpression(CurrValue
))
4295 Values
.push_back((uint8_t)CurrValue
);
4297 while (getLexer().is(AsmToken::Comma
)) {
4300 if (parseAbsoluteExpression(CurrValue
))
4303 Values
.push_back((uint8_t)CurrValue
);
4306 getStreamer().EmitCFIEscape(Values
);
4310 /// parseDirectiveCFIReturnColumn
4311 /// ::= .cfi_return_column register
4312 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc
) {
4313 int64_t Register
= 0;
4314 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
))
4316 getStreamer().EmitCFIReturnColumn(Register
);
4320 /// parseDirectiveCFISignalFrame
4321 /// ::= .cfi_signal_frame
4322 bool AsmParser::parseDirectiveCFISignalFrame() {
4323 if (parseToken(AsmToken::EndOfStatement
,
4324 "unexpected token in '.cfi_signal_frame'"))
4327 getStreamer().EmitCFISignalFrame();
4331 /// parseDirectiveCFIUndefined
4332 /// ::= .cfi_undefined register
4333 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc
) {
4334 int64_t Register
= 0;
4336 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
))
4339 getStreamer().EmitCFIUndefined(Register
);
4343 /// parseDirectiveAltmacro
4346 bool AsmParser::parseDirectiveAltmacro(StringRef Directive
) {
4347 if (getLexer().isNot(AsmToken::EndOfStatement
))
4348 return TokError("unexpected token in '" + Directive
+ "' directive");
4349 AltMacroMode
= (Directive
== ".altmacro");
4353 /// parseDirectiveMacrosOnOff
4356 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive
) {
4357 if (parseToken(AsmToken::EndOfStatement
,
4358 "unexpected token in '" + Directive
+ "' directive"))
4361 setMacrosEnabled(Directive
== ".macros_on");
4365 /// parseDirectiveMacro
4366 /// ::= .macro name[,] [parameters]
4367 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc
) {
4369 if (parseIdentifier(Name
))
4370 return TokError("expected identifier in '.macro' directive");
4372 if (getLexer().is(AsmToken::Comma
))
4375 MCAsmMacroParameters Parameters
;
4376 while (getLexer().isNot(AsmToken::EndOfStatement
)) {
4378 if (!Parameters
.empty() && Parameters
.back().Vararg
)
4379 return Error(Lexer
.getLoc(),
4380 "Vararg parameter '" + Parameters
.back().Name
+
4381 "' should be last one in the list of parameters.");
4383 MCAsmMacroParameter Parameter
;
4384 if (parseIdentifier(Parameter
.Name
))
4385 return TokError("expected identifier in '.macro' directive");
4387 // Emit an error if two (or more) named parameters share the same name
4388 for (const MCAsmMacroParameter
& CurrParam
: Parameters
)
4389 if (CurrParam
.Name
.equals(Parameter
.Name
))
4390 return TokError("macro '" + Name
+ "' has multiple parameters"
4391 " named '" + Parameter
.Name
+ "'");
4393 if (Lexer
.is(AsmToken::Colon
)) {
4394 Lex(); // consume ':'
4397 StringRef Qualifier
;
4399 QualLoc
= Lexer
.getLoc();
4400 if (parseIdentifier(Qualifier
))
4401 return Error(QualLoc
, "missing parameter qualifier for "
4402 "'" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4404 if (Qualifier
== "req")
4405 Parameter
.Required
= true;
4406 else if (Qualifier
== "vararg")
4407 Parameter
.Vararg
= true;
4409 return Error(QualLoc
, Qualifier
+ " is not a valid parameter qualifier "
4410 "for '" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4413 if (getLexer().is(AsmToken::Equal
)) {
4418 ParamLoc
= Lexer
.getLoc();
4419 if (parseMacroArgument(Parameter
.Value
, /*Vararg=*/false ))
4422 if (Parameter
.Required
)
4423 Warning(ParamLoc
, "pointless default value for required parameter "
4424 "'" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4427 Parameters
.push_back(std::move(Parameter
));
4429 if (getLexer().is(AsmToken::Comma
))
4433 // Eat just the end of statement.
4436 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4437 AsmToken EndToken
, StartToken
= getTok();
4438 unsigned MacroDepth
= 0;
4439 // Lex the macro definition.
4441 // Ignore Lexing errors in macros.
4442 while (Lexer
.is(AsmToken::Error
)) {
4446 // Check whether we have reached the end of the file.
4447 if (getLexer().is(AsmToken::Eof
))
4448 return Error(DirectiveLoc
, "no matching '.endmacro' in definition");
4450 // Otherwise, check whether we have reach the .endmacro.
4451 if (getLexer().is(AsmToken::Identifier
)) {
4452 if (getTok().getIdentifier() == ".endm" ||
4453 getTok().getIdentifier() == ".endmacro") {
4454 if (MacroDepth
== 0) { // Outermost macro.
4455 EndToken
= getTok();
4457 if (getLexer().isNot(AsmToken::EndOfStatement
))
4458 return TokError("unexpected token in '" + EndToken
.getIdentifier() +
4462 // Otherwise we just found the end of an inner macro.
4465 } else if (getTok().getIdentifier() == ".macro") {
4466 // We allow nested macros. Those aren't instantiated until the outermost
4467 // macro is expanded so just ignore them for now.
4472 // Otherwise, scan til the end of the statement.
4473 eatToEndOfStatement();
4476 if (getContext().lookupMacro(Name
)) {
4477 return Error(DirectiveLoc
, "macro '" + Name
+ "' is already defined");
4480 const char *BodyStart
= StartToken
.getLoc().getPointer();
4481 const char *BodyEnd
= EndToken
.getLoc().getPointer();
4482 StringRef Body
= StringRef(BodyStart
, BodyEnd
- BodyStart
);
4483 checkForBadMacro(DirectiveLoc
, Name
, Body
, Parameters
);
4484 MCAsmMacro
Macro(Name
, Body
, std::move(Parameters
));
4485 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4487 getContext().defineMacro(Name
, std::move(Macro
));
4491 /// checkForBadMacro
4493 /// With the support added for named parameters there may be code out there that
4494 /// is transitioning from positional parameters. In versions of gas that did
4495 /// not support named parameters they would be ignored on the macro definition.
4496 /// But to support both styles of parameters this is not possible so if a macro
4497 /// definition has named parameters but does not use them and has what appears
4498 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4499 /// warning that the positional parameter found in body which have no effect.
4500 /// Hoping the developer will either remove the named parameters from the macro
4501 /// definition so the positional parameters get used if that was what was
4502 /// intended or change the macro to use the named parameters. It is possible
4503 /// this warning will trigger when the none of the named parameters are used
4504 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4505 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc
, StringRef Name
,
4507 ArrayRef
<MCAsmMacroParameter
> Parameters
) {
4508 // If this macro is not defined with named parameters the warning we are
4509 // checking for here doesn't apply.
4510 unsigned NParameters
= Parameters
.size();
4511 if (NParameters
== 0)
4514 bool NamedParametersFound
= false;
4515 bool PositionalParametersFound
= false;
4517 // Look at the body of the macro for use of both the named parameters and what
4518 // are likely to be positional parameters. This is what expandMacro() is
4519 // doing when it finds the parameters in the body.
4520 while (!Body
.empty()) {
4521 // Scan for the next possible parameter.
4522 std::size_t End
= Body
.size(), Pos
= 0;
4523 for (; Pos
!= End
; ++Pos
) {
4524 // Check for a substitution or escape.
4525 // This macro is defined with parameters, look for \foo, \bar, etc.
4526 if (Body
[Pos
] == '\\' && Pos
+ 1 != End
)
4529 // This macro should have parameters, but look for $0, $1, ..., $n too.
4530 if (Body
[Pos
] != '$' || Pos
+ 1 == End
)
4532 char Next
= Body
[Pos
+ 1];
4533 if (Next
== '$' || Next
== 'n' ||
4534 isdigit(static_cast<unsigned char>(Next
)))
4538 // Check if we reached the end.
4542 if (Body
[Pos
] == '$') {
4543 switch (Body
[Pos
+ 1]) {
4548 // $n => number of arguments
4550 PositionalParametersFound
= true;
4553 // $[0-9] => argument
4555 PositionalParametersFound
= true;
4561 unsigned I
= Pos
+ 1;
4562 while (isIdentifierChar(Body
[I
]) && I
+ 1 != End
)
4565 const char *Begin
= Body
.data() + Pos
+ 1;
4566 StringRef
Argument(Begin
, I
- (Pos
+ 1));
4568 for (; Index
< NParameters
; ++Index
)
4569 if (Parameters
[Index
].Name
== Argument
)
4572 if (Index
== NParameters
) {
4573 if (Body
[Pos
+ 1] == '(' && Body
[Pos
+ 2] == ')')
4579 NamedParametersFound
= true;
4580 Pos
+= 1 + Argument
.size();
4583 // Update the scan point.
4584 Body
= Body
.substr(Pos
);
4587 if (!NamedParametersFound
&& PositionalParametersFound
)
4588 Warning(DirectiveLoc
, "macro defined with named parameters which are not "
4589 "used in macro body, possible positional parameter "
4590 "found in body which will have no effect");
4593 /// parseDirectiveExitMacro
4595 bool AsmParser::parseDirectiveExitMacro(StringRef Directive
) {
4596 if (parseToken(AsmToken::EndOfStatement
,
4597 "unexpected token in '" + Directive
+ "' directive"))
4600 if (!isInsideMacroInstantiation())
4601 return TokError("unexpected '" + Directive
+ "' in file, "
4602 "no current macro definition");
4604 // Exit all conditionals that are active in the current macro.
4605 while (TheCondStack
.size() != ActiveMacros
.back()->CondStackDepth
) {
4606 TheCondState
= TheCondStack
.back();
4607 TheCondStack
.pop_back();
4614 /// parseDirectiveEndMacro
4617 bool AsmParser::parseDirectiveEndMacro(StringRef Directive
) {
4618 if (getLexer().isNot(AsmToken::EndOfStatement
))
4619 return TokError("unexpected token in '" + Directive
+ "' directive");
4621 // If we are inside a macro instantiation, terminate the current
4623 if (isInsideMacroInstantiation()) {
4628 // Otherwise, this .endmacro is a stray entry in the file; well formed
4629 // .endmacro directives are handled during the macro definition parsing.
4630 return TokError("unexpected '" + Directive
+ "' in file, "
4631 "no current macro definition");
4634 /// parseDirectivePurgeMacro
4636 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc
) {
4639 if (parseTokenLoc(Loc
) ||
4640 check(parseIdentifier(Name
), Loc
,
4641 "expected identifier in '.purgem' directive") ||
4642 parseToken(AsmToken::EndOfStatement
,
4643 "unexpected token in '.purgem' directive"))
4646 if (!getContext().lookupMacro(Name
))
4647 return Error(DirectiveLoc
, "macro '" + Name
+ "' is not defined");
4649 getContext().undefineMacro(Name
);
4650 DEBUG_WITH_TYPE("asm-macros", dbgs()
4651 << "Un-defining macro: " << Name
<< "\n");
4655 /// parseDirectiveBundleAlignMode
4656 /// ::= {.bundle_align_mode} expression
4657 bool AsmParser::parseDirectiveBundleAlignMode() {
4658 // Expect a single argument: an expression that evaluates to a constant
4659 // in the inclusive range 0-30.
4660 SMLoc ExprLoc
= getLexer().getLoc();
4661 int64_t AlignSizePow2
;
4662 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2
) ||
4663 parseToken(AsmToken::EndOfStatement
, "unexpected token after expression "
4664 "in '.bundle_align_mode' "
4666 check(AlignSizePow2
< 0 || AlignSizePow2
> 30, ExprLoc
,
4667 "invalid bundle alignment size (expected between 0 and 30)"))
4670 // Because of AlignSizePow2's verified range we can safely truncate it to
4672 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2
));
4676 /// parseDirectiveBundleLock
4677 /// ::= {.bundle_lock} [align_to_end]
4678 bool AsmParser::parseDirectiveBundleLock() {
4679 if (checkForValidSection())
4681 bool AlignToEnd
= false;
4684 SMLoc Loc
= getTok().getLoc();
4685 const char *kInvalidOptionError
=
4686 "invalid option for '.bundle_lock' directive";
4688 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
4689 if (check(parseIdentifier(Option
), Loc
, kInvalidOptionError
) ||
4690 check(Option
!= "align_to_end", Loc
, kInvalidOptionError
) ||
4691 parseToken(AsmToken::EndOfStatement
,
4692 "unexpected token after '.bundle_lock' directive option"))
4697 getStreamer().EmitBundleLock(AlignToEnd
);
4701 /// parseDirectiveBundleLock
4702 /// ::= {.bundle_lock}
4703 bool AsmParser::parseDirectiveBundleUnlock() {
4704 if (checkForValidSection() ||
4705 parseToken(AsmToken::EndOfStatement
,
4706 "unexpected token in '.bundle_unlock' directive"))
4709 getStreamer().EmitBundleUnlock();
4713 /// parseDirectiveSpace
4714 /// ::= (.skip | .space) expression [ , expression ]
4715 bool AsmParser::parseDirectiveSpace(StringRef IDVal
) {
4716 SMLoc NumBytesLoc
= Lexer
.getLoc();
4717 const MCExpr
*NumBytes
;
4718 if (checkForValidSection() || parseExpression(NumBytes
))
4721 int64_t FillExpr
= 0;
4722 if (parseOptionalToken(AsmToken::Comma
))
4723 if (parseAbsoluteExpression(FillExpr
))
4724 return addErrorSuffix("in '" + Twine(IDVal
) + "' directive");
4725 if (parseToken(AsmToken::EndOfStatement
))
4726 return addErrorSuffix("in '" + Twine(IDVal
) + "' directive");
4728 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4729 getStreamer().emitFill(*NumBytes
, FillExpr
, NumBytesLoc
);
4734 /// parseDirectiveDCB
4735 /// ::= .dcb.{b, l, w} expression, expression
4736 bool AsmParser::parseDirectiveDCB(StringRef IDVal
, unsigned Size
) {
4737 SMLoc NumValuesLoc
= Lexer
.getLoc();
4739 if (checkForValidSection() || parseAbsoluteExpression(NumValues
))
4742 if (NumValues
< 0) {
4743 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
4747 if (parseToken(AsmToken::Comma
,
4748 "unexpected token in '" + Twine(IDVal
) + "' directive"))
4751 const MCExpr
*Value
;
4752 SMLoc ExprLoc
= getLexer().getLoc();
4753 if (parseExpression(Value
))
4756 // Special case constant expressions to match code generator.
4757 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
4758 assert(Size
<= 8 && "Invalid size");
4759 uint64_t IntValue
= MCE
->getValue();
4760 if (!isUIntN(8 * Size
, IntValue
) && !isIntN(8 * Size
, IntValue
))
4761 return Error(ExprLoc
, "literal value out of range for directive");
4762 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4763 getStreamer().EmitIntValue(IntValue
, Size
);
4765 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4766 getStreamer().EmitValue(Value
, Size
, ExprLoc
);
4769 if (parseToken(AsmToken::EndOfStatement
,
4770 "unexpected token in '" + Twine(IDVal
) + "' directive"))
4776 /// parseDirectiveRealDCB
4777 /// ::= .dcb.{d, s} expression, expression
4778 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal
, const fltSemantics
&Semantics
) {
4779 SMLoc NumValuesLoc
= Lexer
.getLoc();
4781 if (checkForValidSection() || parseAbsoluteExpression(NumValues
))
4784 if (NumValues
< 0) {
4785 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
4789 if (parseToken(AsmToken::Comma
,
4790 "unexpected token in '" + Twine(IDVal
) + "' directive"))
4794 if (parseRealValue(Semantics
, AsInt
))
4797 if (parseToken(AsmToken::EndOfStatement
,
4798 "unexpected token in '" + Twine(IDVal
) + "' directive"))
4801 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4802 getStreamer().EmitIntValue(AsInt
.getLimitedValue(),
4803 AsInt
.getBitWidth() / 8);
4808 /// parseDirectiveDS
4809 /// ::= .ds.{b, d, l, p, s, w, x} expression
4810 bool AsmParser::parseDirectiveDS(StringRef IDVal
, unsigned Size
) {
4811 SMLoc NumValuesLoc
= Lexer
.getLoc();
4813 if (checkForValidSection() || parseAbsoluteExpression(NumValues
))
4816 if (NumValues
< 0) {
4817 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
4821 if (parseToken(AsmToken::EndOfStatement
,
4822 "unexpected token in '" + Twine(IDVal
) + "' directive"))
4825 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4826 getStreamer().emitFill(Size
, 0);
4831 /// parseDirectiveLEB128
4832 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4833 bool AsmParser::parseDirectiveLEB128(bool Signed
) {
4834 if (checkForValidSection())
4837 auto parseOp
= [&]() -> bool {
4838 const MCExpr
*Value
;
4839 if (parseExpression(Value
))
4842 getStreamer().EmitSLEB128Value(Value
);
4844 getStreamer().EmitULEB128Value(Value
);
4848 if (parseMany(parseOp
))
4849 return addErrorSuffix(" in directive");
4854 /// parseDirectiveSymbolAttribute
4855 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4856 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr
) {
4857 auto parseOp
= [&]() -> bool {
4859 SMLoc Loc
= getTok().getLoc();
4860 if (parseIdentifier(Name
))
4861 return Error(Loc
, "expected identifier");
4862 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
4864 // Assembler local symbols don't make any sense here. Complain loudly.
4865 if (Sym
->isTemporary())
4866 return Error(Loc
, "non-local symbol required");
4868 if (!getStreamer().EmitSymbolAttribute(Sym
, Attr
))
4869 return Error(Loc
, "unable to emit symbol attribute");
4873 if (parseMany(parseOp
))
4874 return addErrorSuffix(" in directive");
4878 /// parseDirectiveComm
4879 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4880 bool AsmParser::parseDirectiveComm(bool IsLocal
) {
4881 if (checkForValidSection())
4884 SMLoc IDLoc
= getLexer().getLoc();
4886 if (parseIdentifier(Name
))
4887 return TokError("expected identifier in directive");
4889 // Handle the identifier as the key symbol.
4890 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
4892 if (getLexer().isNot(AsmToken::Comma
))
4893 return TokError("unexpected token in directive");
4897 SMLoc SizeLoc
= getLexer().getLoc();
4898 if (parseAbsoluteExpression(Size
))
4901 int64_t Pow2Alignment
= 0;
4902 SMLoc Pow2AlignmentLoc
;
4903 if (getLexer().is(AsmToken::Comma
)) {
4905 Pow2AlignmentLoc
= getLexer().getLoc();
4906 if (parseAbsoluteExpression(Pow2Alignment
))
4909 LCOMM::LCOMMType LCOMM
= Lexer
.getMAI().getLCOMMDirectiveAlignmentType();
4910 if (IsLocal
&& LCOMM
== LCOMM::NoAlignment
)
4911 return Error(Pow2AlignmentLoc
, "alignment not supported on this target");
4913 // If this target takes alignments in bytes (not log) validate and convert.
4914 if ((!IsLocal
&& Lexer
.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4915 (IsLocal
&& LCOMM
== LCOMM::ByteAlignment
)) {
4916 if (!isPowerOf2_64(Pow2Alignment
))
4917 return Error(Pow2AlignmentLoc
, "alignment must be a power of 2");
4918 Pow2Alignment
= Log2_64(Pow2Alignment
);
4922 if (parseToken(AsmToken::EndOfStatement
,
4923 "unexpected token in '.comm' or '.lcomm' directive"))
4926 // NOTE: a size of zero for a .comm should create a undefined symbol
4927 // but a size of .lcomm creates a bss symbol of size zero.
4929 return Error(SizeLoc
, "invalid '.comm' or '.lcomm' directive size, can't "
4930 "be less than zero");
4932 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4933 // may internally end up wanting an alignment in bytes.
4934 // FIXME: Diagnose overflow.
4935 if (Pow2Alignment
< 0)
4936 return Error(Pow2AlignmentLoc
, "invalid '.comm' or '.lcomm' directive "
4937 "alignment, can't be less than zero");
4939 Sym
->redefineIfPossible();
4940 if (!Sym
->isUndefined())
4941 return Error(IDLoc
, "invalid symbol redefinition");
4943 // Create the Symbol as a common or local common with Size and Pow2Alignment
4945 getStreamer().EmitLocalCommonSymbol(Sym
, Size
, 1 << Pow2Alignment
);
4949 getStreamer().EmitCommonSymbol(Sym
, Size
, 1 << Pow2Alignment
);
4953 /// parseDirectiveAbort
4954 /// ::= .abort [... message ...]
4955 bool AsmParser::parseDirectiveAbort() {
4956 // FIXME: Use loc from directive.
4957 SMLoc Loc
= getLexer().getLoc();
4959 StringRef Str
= parseStringToEndOfStatement();
4960 if (parseToken(AsmToken::EndOfStatement
,
4961 "unexpected token in '.abort' directive"))
4965 return Error(Loc
, ".abort detected. Assembly stopping.");
4967 return Error(Loc
, ".abort '" + Str
+ "' detected. Assembly stopping.");
4968 // FIXME: Actually abort assembly here.
4973 /// parseDirectiveInclude
4974 /// ::= .include "filename"
4975 bool AsmParser::parseDirectiveInclude() {
4976 // Allow the strings to have escaped octal character sequence.
4977 std::string Filename
;
4978 SMLoc IncludeLoc
= getTok().getLoc();
4980 if (check(getTok().isNot(AsmToken::String
),
4981 "expected string in '.include' directive") ||
4982 parseEscapedString(Filename
) ||
4983 check(getTok().isNot(AsmToken::EndOfStatement
),
4984 "unexpected token in '.include' directive") ||
4985 // Attempt to switch the lexer to the included file before consuming the
4986 // end of statement to avoid losing it when we switch.
4987 check(enterIncludeFile(Filename
), IncludeLoc
,
4988 "Could not find include file '" + Filename
+ "'"))
4994 /// parseDirectiveIncbin
4995 /// ::= .incbin "filename" [ , skip [ , count ] ]
4996 bool AsmParser::parseDirectiveIncbin() {
4997 // Allow the strings to have escaped octal character sequence.
4998 std::string Filename
;
4999 SMLoc IncbinLoc
= getTok().getLoc();
5000 if (check(getTok().isNot(AsmToken::String
),
5001 "expected string in '.incbin' directive") ||
5002 parseEscapedString(Filename
))
5006 const MCExpr
*Count
= nullptr;
5007 SMLoc SkipLoc
, CountLoc
;
5008 if (parseOptionalToken(AsmToken::Comma
)) {
5009 // The skip expression can be omitted while specifying the count, e.g:
5010 // .incbin "filename",,4
5011 if (getTok().isNot(AsmToken::Comma
)) {
5012 if (parseTokenLoc(SkipLoc
) || parseAbsoluteExpression(Skip
))
5015 if (parseOptionalToken(AsmToken::Comma
)) {
5016 CountLoc
= getTok().getLoc();
5017 if (parseExpression(Count
))
5022 if (parseToken(AsmToken::EndOfStatement
,
5023 "unexpected token in '.incbin' directive"))
5026 if (check(Skip
< 0, SkipLoc
, "skip is negative"))
5029 // Attempt to process the included file.
5030 if (processIncbinFile(Filename
, Skip
, Count
, CountLoc
))
5031 return Error(IncbinLoc
, "Could not find incbin file '" + Filename
+ "'");
5035 /// parseDirectiveIf
5036 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
5037 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc
, DirectiveKind DirKind
) {
5038 TheCondStack
.push_back(TheCondState
);
5039 TheCondState
.TheCond
= AsmCond::IfCond
;
5040 if (TheCondState
.Ignore
) {
5041 eatToEndOfStatement();
5044 if (parseAbsoluteExpression(ExprValue
) ||
5045 parseToken(AsmToken::EndOfStatement
,
5046 "unexpected token in '.if' directive"))
5051 llvm_unreachable("unsupported directive");
5056 ExprValue
= ExprValue
== 0;
5059 ExprValue
= ExprValue
>= 0;
5062 ExprValue
= ExprValue
> 0;
5065 ExprValue
= ExprValue
<= 0;
5068 ExprValue
= ExprValue
< 0;
5072 TheCondState
.CondMet
= ExprValue
;
5073 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5079 /// parseDirectiveIfb
5081 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc
, bool ExpectBlank
) {
5082 TheCondStack
.push_back(TheCondState
);
5083 TheCondState
.TheCond
= AsmCond::IfCond
;
5085 if (TheCondState
.Ignore
) {
5086 eatToEndOfStatement();
5088 StringRef Str
= parseStringToEndOfStatement();
5090 if (parseToken(AsmToken::EndOfStatement
,
5091 "unexpected token in '.ifb' directive"))
5094 TheCondState
.CondMet
= ExpectBlank
== Str
.empty();
5095 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5101 /// parseDirectiveIfc
5102 /// ::= .ifc string1, string2
5103 /// ::= .ifnc string1, string2
5104 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc
, bool ExpectEqual
) {
5105 TheCondStack
.push_back(TheCondState
);
5106 TheCondState
.TheCond
= AsmCond::IfCond
;
5108 if (TheCondState
.Ignore
) {
5109 eatToEndOfStatement();
5111 StringRef Str1
= parseStringToComma();
5113 if (parseToken(AsmToken::Comma
, "unexpected token in '.ifc' directive"))
5116 StringRef Str2
= parseStringToEndOfStatement();
5118 if (parseToken(AsmToken::EndOfStatement
,
5119 "unexpected token in '.ifc' directive"))
5122 TheCondState
.CondMet
= ExpectEqual
== (Str1
.trim() == Str2
.trim());
5123 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5129 /// parseDirectiveIfeqs
5130 /// ::= .ifeqs string1, string2
5131 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc
, bool ExpectEqual
) {
5132 if (Lexer
.isNot(AsmToken::String
)) {
5134 return TokError("expected string parameter for '.ifeqs' directive");
5135 return TokError("expected string parameter for '.ifnes' directive");
5138 StringRef String1
= getTok().getStringContents();
5141 if (Lexer
.isNot(AsmToken::Comma
)) {
5144 "expected comma after first string for '.ifeqs' directive");
5145 return TokError("expected comma after first string for '.ifnes' directive");
5150 if (Lexer
.isNot(AsmToken::String
)) {
5152 return TokError("expected string parameter for '.ifeqs' directive");
5153 return TokError("expected string parameter for '.ifnes' directive");
5156 StringRef String2
= getTok().getStringContents();
5159 TheCondStack
.push_back(TheCondState
);
5160 TheCondState
.TheCond
= AsmCond::IfCond
;
5161 TheCondState
.CondMet
= ExpectEqual
== (String1
== String2
);
5162 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5167 /// parseDirectiveIfdef
5168 /// ::= .ifdef symbol
5169 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc
, bool expect_defined
) {
5171 TheCondStack
.push_back(TheCondState
);
5172 TheCondState
.TheCond
= AsmCond::IfCond
;
5174 if (TheCondState
.Ignore
) {
5175 eatToEndOfStatement();
5177 if (check(parseIdentifier(Name
), "expected identifier after '.ifdef'") ||
5178 parseToken(AsmToken::EndOfStatement
, "unexpected token in '.ifdef'"))
5181 MCSymbol
*Sym
= getContext().lookupSymbol(Name
);
5184 TheCondState
.CondMet
= (Sym
&& !Sym
->isUndefined(false));
5186 TheCondState
.CondMet
= (!Sym
|| Sym
->isUndefined(false));
5187 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5193 /// parseDirectiveElseIf
5194 /// ::= .elseif expression
5195 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc
) {
5196 if (TheCondState
.TheCond
!= AsmCond::IfCond
&&
5197 TheCondState
.TheCond
!= AsmCond::ElseIfCond
)
5198 return Error(DirectiveLoc
, "Encountered a .elseif that doesn't follow an"
5199 " .if or an .elseif");
5200 TheCondState
.TheCond
= AsmCond::ElseIfCond
;
5202 bool LastIgnoreState
= false;
5203 if (!TheCondStack
.empty())
5204 LastIgnoreState
= TheCondStack
.back().Ignore
;
5205 if (LastIgnoreState
|| TheCondState
.CondMet
) {
5206 TheCondState
.Ignore
= true;
5207 eatToEndOfStatement();
5210 if (parseAbsoluteExpression(ExprValue
))
5213 if (parseToken(AsmToken::EndOfStatement
,
5214 "unexpected token in '.elseif' directive"))
5217 TheCondState
.CondMet
= ExprValue
;
5218 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5224 /// parseDirectiveElse
5226 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc
) {
5227 if (parseToken(AsmToken::EndOfStatement
,
5228 "unexpected token in '.else' directive"))
5231 if (TheCondState
.TheCond
!= AsmCond::IfCond
&&
5232 TheCondState
.TheCond
!= AsmCond::ElseIfCond
)
5233 return Error(DirectiveLoc
, "Encountered a .else that doesn't follow "
5234 " an .if or an .elseif");
5235 TheCondState
.TheCond
= AsmCond::ElseCond
;
5236 bool LastIgnoreState
= false;
5237 if (!TheCondStack
.empty())
5238 LastIgnoreState
= TheCondStack
.back().Ignore
;
5239 if (LastIgnoreState
|| TheCondState
.CondMet
)
5240 TheCondState
.Ignore
= true;
5242 TheCondState
.Ignore
= false;
5247 /// parseDirectiveEnd
5249 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc
) {
5250 if (parseToken(AsmToken::EndOfStatement
,
5251 "unexpected token in '.end' directive"))
5254 while (Lexer
.isNot(AsmToken::Eof
))
5260 /// parseDirectiveError
5262 /// ::= .error [string]
5263 bool AsmParser::parseDirectiveError(SMLoc L
, bool WithMessage
) {
5264 if (!TheCondStack
.empty()) {
5265 if (TheCondStack
.back().Ignore
) {
5266 eatToEndOfStatement();
5272 return Error(L
, ".err encountered");
5274 StringRef Message
= ".error directive invoked in source file";
5275 if (Lexer
.isNot(AsmToken::EndOfStatement
)) {
5276 if (Lexer
.isNot(AsmToken::String
))
5277 return TokError(".error argument must be a string");
5279 Message
= getTok().getStringContents();
5283 return Error(L
, Message
);
5286 /// parseDirectiveWarning
5287 /// ::= .warning [string]
5288 bool AsmParser::parseDirectiveWarning(SMLoc L
) {
5289 if (!TheCondStack
.empty()) {
5290 if (TheCondStack
.back().Ignore
) {
5291 eatToEndOfStatement();
5296 StringRef Message
= ".warning directive invoked in source file";
5298 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
5299 if (Lexer
.isNot(AsmToken::String
))
5300 return TokError(".warning argument must be a string");
5302 Message
= getTok().getStringContents();
5304 if (parseToken(AsmToken::EndOfStatement
,
5305 "expected end of statement in '.warning' directive"))
5309 return Warning(L
, Message
);
5312 /// parseDirectiveEndIf
5314 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc
) {
5315 if (parseToken(AsmToken::EndOfStatement
,
5316 "unexpected token in '.endif' directive"))
5319 if ((TheCondState
.TheCond
== AsmCond::NoCond
) || TheCondStack
.empty())
5320 return Error(DirectiveLoc
, "Encountered a .endif that doesn't follow "
5322 if (!TheCondStack
.empty()) {
5323 TheCondState
= TheCondStack
.back();
5324 TheCondStack
.pop_back();
5330 void AsmParser::initializeDirectiveKindMap() {
5331 DirectiveKindMap
[".set"] = DK_SET
;
5332 DirectiveKindMap
[".equ"] = DK_EQU
;
5333 DirectiveKindMap
[".equiv"] = DK_EQUIV
;
5334 DirectiveKindMap
[".ascii"] = DK_ASCII
;
5335 DirectiveKindMap
[".asciz"] = DK_ASCIZ
;
5336 DirectiveKindMap
[".string"] = DK_STRING
;
5337 DirectiveKindMap
[".byte"] = DK_BYTE
;
5338 DirectiveKindMap
[".short"] = DK_SHORT
;
5339 DirectiveKindMap
[".value"] = DK_VALUE
;
5340 DirectiveKindMap
[".2byte"] = DK_2BYTE
;
5341 DirectiveKindMap
[".long"] = DK_LONG
;
5342 DirectiveKindMap
[".int"] = DK_INT
;
5343 DirectiveKindMap
[".4byte"] = DK_4BYTE
;
5344 DirectiveKindMap
[".quad"] = DK_QUAD
;
5345 DirectiveKindMap
[".8byte"] = DK_8BYTE
;
5346 DirectiveKindMap
[".octa"] = DK_OCTA
;
5347 DirectiveKindMap
[".single"] = DK_SINGLE
;
5348 DirectiveKindMap
[".float"] = DK_FLOAT
;
5349 DirectiveKindMap
[".double"] = DK_DOUBLE
;
5350 DirectiveKindMap
[".align"] = DK_ALIGN
;
5351 DirectiveKindMap
[".align32"] = DK_ALIGN32
;
5352 DirectiveKindMap
[".balign"] = DK_BALIGN
;
5353 DirectiveKindMap
[".balignw"] = DK_BALIGNW
;
5354 DirectiveKindMap
[".balignl"] = DK_BALIGNL
;
5355 DirectiveKindMap
[".p2align"] = DK_P2ALIGN
;
5356 DirectiveKindMap
[".p2alignw"] = DK_P2ALIGNW
;
5357 DirectiveKindMap
[".p2alignl"] = DK_P2ALIGNL
;
5358 DirectiveKindMap
[".org"] = DK_ORG
;
5359 DirectiveKindMap
[".fill"] = DK_FILL
;
5360 DirectiveKindMap
[".zero"] = DK_ZERO
;
5361 DirectiveKindMap
[".extern"] = DK_EXTERN
;
5362 DirectiveKindMap
[".globl"] = DK_GLOBL
;
5363 DirectiveKindMap
[".global"] = DK_GLOBAL
;
5364 DirectiveKindMap
[".lazy_reference"] = DK_LAZY_REFERENCE
;
5365 DirectiveKindMap
[".no_dead_strip"] = DK_NO_DEAD_STRIP
;
5366 DirectiveKindMap
[".symbol_resolver"] = DK_SYMBOL_RESOLVER
;
5367 DirectiveKindMap
[".private_extern"] = DK_PRIVATE_EXTERN
;
5368 DirectiveKindMap
[".reference"] = DK_REFERENCE
;
5369 DirectiveKindMap
[".weak_definition"] = DK_WEAK_DEFINITION
;
5370 DirectiveKindMap
[".weak_reference"] = DK_WEAK_REFERENCE
;
5371 DirectiveKindMap
[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN
;
5372 DirectiveKindMap
[".cold"] = DK_COLD
;
5373 DirectiveKindMap
[".comm"] = DK_COMM
;
5374 DirectiveKindMap
[".common"] = DK_COMMON
;
5375 DirectiveKindMap
[".lcomm"] = DK_LCOMM
;
5376 DirectiveKindMap
[".abort"] = DK_ABORT
;
5377 DirectiveKindMap
[".include"] = DK_INCLUDE
;
5378 DirectiveKindMap
[".incbin"] = DK_INCBIN
;
5379 DirectiveKindMap
[".code16"] = DK_CODE16
;
5380 DirectiveKindMap
[".code16gcc"] = DK_CODE16GCC
;
5381 DirectiveKindMap
[".rept"] = DK_REPT
;
5382 DirectiveKindMap
[".rep"] = DK_REPT
;
5383 DirectiveKindMap
[".irp"] = DK_IRP
;
5384 DirectiveKindMap
[".irpc"] = DK_IRPC
;
5385 DirectiveKindMap
[".endr"] = DK_ENDR
;
5386 DirectiveKindMap
[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE
;
5387 DirectiveKindMap
[".bundle_lock"] = DK_BUNDLE_LOCK
;
5388 DirectiveKindMap
[".bundle_unlock"] = DK_BUNDLE_UNLOCK
;
5389 DirectiveKindMap
[".if"] = DK_IF
;
5390 DirectiveKindMap
[".ifeq"] = DK_IFEQ
;
5391 DirectiveKindMap
[".ifge"] = DK_IFGE
;
5392 DirectiveKindMap
[".ifgt"] = DK_IFGT
;
5393 DirectiveKindMap
[".ifle"] = DK_IFLE
;
5394 DirectiveKindMap
[".iflt"] = DK_IFLT
;
5395 DirectiveKindMap
[".ifne"] = DK_IFNE
;
5396 DirectiveKindMap
[".ifb"] = DK_IFB
;
5397 DirectiveKindMap
[".ifnb"] = DK_IFNB
;
5398 DirectiveKindMap
[".ifc"] = DK_IFC
;
5399 DirectiveKindMap
[".ifeqs"] = DK_IFEQS
;
5400 DirectiveKindMap
[".ifnc"] = DK_IFNC
;
5401 DirectiveKindMap
[".ifnes"] = DK_IFNES
;
5402 DirectiveKindMap
[".ifdef"] = DK_IFDEF
;
5403 DirectiveKindMap
[".ifndef"] = DK_IFNDEF
;
5404 DirectiveKindMap
[".ifnotdef"] = DK_IFNOTDEF
;
5405 DirectiveKindMap
[".elseif"] = DK_ELSEIF
;
5406 DirectiveKindMap
[".else"] = DK_ELSE
;
5407 DirectiveKindMap
[".end"] = DK_END
;
5408 DirectiveKindMap
[".endif"] = DK_ENDIF
;
5409 DirectiveKindMap
[".skip"] = DK_SKIP
;
5410 DirectiveKindMap
[".space"] = DK_SPACE
;
5411 DirectiveKindMap
[".file"] = DK_FILE
;
5412 DirectiveKindMap
[".line"] = DK_LINE
;
5413 DirectiveKindMap
[".loc"] = DK_LOC
;
5414 DirectiveKindMap
[".stabs"] = DK_STABS
;
5415 DirectiveKindMap
[".cv_file"] = DK_CV_FILE
;
5416 DirectiveKindMap
[".cv_func_id"] = DK_CV_FUNC_ID
;
5417 DirectiveKindMap
[".cv_loc"] = DK_CV_LOC
;
5418 DirectiveKindMap
[".cv_linetable"] = DK_CV_LINETABLE
;
5419 DirectiveKindMap
[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE
;
5420 DirectiveKindMap
[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID
;
5421 DirectiveKindMap
[".cv_def_range"] = DK_CV_DEF_RANGE
;
5422 DirectiveKindMap
[".cv_string"] = DK_CV_STRING
;
5423 DirectiveKindMap
[".cv_stringtable"] = DK_CV_STRINGTABLE
;
5424 DirectiveKindMap
[".cv_filechecksums"] = DK_CV_FILECHECKSUMS
;
5425 DirectiveKindMap
[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET
;
5426 DirectiveKindMap
[".cv_fpo_data"] = DK_CV_FPO_DATA
;
5427 DirectiveKindMap
[".sleb128"] = DK_SLEB128
;
5428 DirectiveKindMap
[".uleb128"] = DK_ULEB128
;
5429 DirectiveKindMap
[".cfi_sections"] = DK_CFI_SECTIONS
;
5430 DirectiveKindMap
[".cfi_startproc"] = DK_CFI_STARTPROC
;
5431 DirectiveKindMap
[".cfi_endproc"] = DK_CFI_ENDPROC
;
5432 DirectiveKindMap
[".cfi_def_cfa"] = DK_CFI_DEF_CFA
;
5433 DirectiveKindMap
[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET
;
5434 DirectiveKindMap
[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET
;
5435 DirectiveKindMap
[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER
;
5436 DirectiveKindMap
[".cfi_offset"] = DK_CFI_OFFSET
;
5437 DirectiveKindMap
[".cfi_rel_offset"] = DK_CFI_REL_OFFSET
;
5438 DirectiveKindMap
[".cfi_personality"] = DK_CFI_PERSONALITY
;
5439 DirectiveKindMap
[".cfi_lsda"] = DK_CFI_LSDA
;
5440 DirectiveKindMap
[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE
;
5441 DirectiveKindMap
[".cfi_restore_state"] = DK_CFI_RESTORE_STATE
;
5442 DirectiveKindMap
[".cfi_same_value"] = DK_CFI_SAME_VALUE
;
5443 DirectiveKindMap
[".cfi_restore"] = DK_CFI_RESTORE
;
5444 DirectiveKindMap
[".cfi_escape"] = DK_CFI_ESCAPE
;
5445 DirectiveKindMap
[".cfi_return_column"] = DK_CFI_RETURN_COLUMN
;
5446 DirectiveKindMap
[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME
;
5447 DirectiveKindMap
[".cfi_undefined"] = DK_CFI_UNDEFINED
;
5448 DirectiveKindMap
[".cfi_register"] = DK_CFI_REGISTER
;
5449 DirectiveKindMap
[".cfi_window_save"] = DK_CFI_WINDOW_SAVE
;
5450 DirectiveKindMap
[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME
;
5451 DirectiveKindMap
[".macros_on"] = DK_MACROS_ON
;
5452 DirectiveKindMap
[".macros_off"] = DK_MACROS_OFF
;
5453 DirectiveKindMap
[".macro"] = DK_MACRO
;
5454 DirectiveKindMap
[".exitm"] = DK_EXITM
;
5455 DirectiveKindMap
[".endm"] = DK_ENDM
;
5456 DirectiveKindMap
[".endmacro"] = DK_ENDMACRO
;
5457 DirectiveKindMap
[".purgem"] = DK_PURGEM
;
5458 DirectiveKindMap
[".err"] = DK_ERR
;
5459 DirectiveKindMap
[".error"] = DK_ERROR
;
5460 DirectiveKindMap
[".warning"] = DK_WARNING
;
5461 DirectiveKindMap
[".altmacro"] = DK_ALTMACRO
;
5462 DirectiveKindMap
[".noaltmacro"] = DK_NOALTMACRO
;
5463 DirectiveKindMap
[".reloc"] = DK_RELOC
;
5464 DirectiveKindMap
[".dc"] = DK_DC
;
5465 DirectiveKindMap
[".dc.a"] = DK_DC_A
;
5466 DirectiveKindMap
[".dc.b"] = DK_DC_B
;
5467 DirectiveKindMap
[".dc.d"] = DK_DC_D
;
5468 DirectiveKindMap
[".dc.l"] = DK_DC_L
;
5469 DirectiveKindMap
[".dc.s"] = DK_DC_S
;
5470 DirectiveKindMap
[".dc.w"] = DK_DC_W
;
5471 DirectiveKindMap
[".dc.x"] = DK_DC_X
;
5472 DirectiveKindMap
[".dcb"] = DK_DCB
;
5473 DirectiveKindMap
[".dcb.b"] = DK_DCB_B
;
5474 DirectiveKindMap
[".dcb.d"] = DK_DCB_D
;
5475 DirectiveKindMap
[".dcb.l"] = DK_DCB_L
;
5476 DirectiveKindMap
[".dcb.s"] = DK_DCB_S
;
5477 DirectiveKindMap
[".dcb.w"] = DK_DCB_W
;
5478 DirectiveKindMap
[".dcb.x"] = DK_DCB_X
;
5479 DirectiveKindMap
[".ds"] = DK_DS
;
5480 DirectiveKindMap
[".ds.b"] = DK_DS_B
;
5481 DirectiveKindMap
[".ds.d"] = DK_DS_D
;
5482 DirectiveKindMap
[".ds.l"] = DK_DS_L
;
5483 DirectiveKindMap
[".ds.p"] = DK_DS_P
;
5484 DirectiveKindMap
[".ds.s"] = DK_DS_S
;
5485 DirectiveKindMap
[".ds.w"] = DK_DS_W
;
5486 DirectiveKindMap
[".ds.x"] = DK_DS_X
;
5487 DirectiveKindMap
[".print"] = DK_PRINT
;
5488 DirectiveKindMap
[".addrsig"] = DK_ADDRSIG
;
5489 DirectiveKindMap
[".addrsig_sym"] = DK_ADDRSIG_SYM
;
5492 MCAsmMacro
*AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc
) {
5493 AsmToken EndToken
, StartToken
= getTok();
5495 unsigned NestLevel
= 0;
5497 // Check whether we have reached the end of the file.
5498 if (getLexer().is(AsmToken::Eof
)) {
5499 printError(DirectiveLoc
, "no matching '.endr' in definition");
5503 if (Lexer
.is(AsmToken::Identifier
) &&
5504 (getTok().getIdentifier() == ".rep" ||
5505 getTok().getIdentifier() == ".rept" ||
5506 getTok().getIdentifier() == ".irp" ||
5507 getTok().getIdentifier() == ".irpc")) {
5511 // Otherwise, check whether we have reached the .endr.
5512 if (Lexer
.is(AsmToken::Identifier
) && getTok().getIdentifier() == ".endr") {
5513 if (NestLevel
== 0) {
5514 EndToken
= getTok();
5516 if (Lexer
.isNot(AsmToken::EndOfStatement
)) {
5517 printError(getTok().getLoc(),
5518 "unexpected token in '.endr' directive");
5526 // Otherwise, scan till the end of the statement.
5527 eatToEndOfStatement();
5530 const char *BodyStart
= StartToken
.getLoc().getPointer();
5531 const char *BodyEnd
= EndToken
.getLoc().getPointer();
5532 StringRef Body
= StringRef(BodyStart
, BodyEnd
- BodyStart
);
5534 // We Are Anonymous.
5535 MacroLikeBodies
.emplace_back(StringRef(), Body
, MCAsmMacroParameters());
5536 return &MacroLikeBodies
.back();
5539 void AsmParser::instantiateMacroLikeBody(MCAsmMacro
*M
, SMLoc DirectiveLoc
,
5540 raw_svector_ostream
&OS
) {
5543 std::unique_ptr
<MemoryBuffer
> Instantiation
=
5544 MemoryBuffer::getMemBufferCopy(OS
.str(), "<instantiation>");
5546 // Create the macro instantiation object and add to the current macro
5547 // instantiation stack.
5548 MacroInstantiation
*MI
= new MacroInstantiation(
5549 DirectiveLoc
, CurBuffer
, getTok().getLoc(), TheCondStack
.size());
5550 ActiveMacros
.push_back(MI
);
5552 // Jump to the macro instantiation and prime the lexer.
5553 CurBuffer
= SrcMgr
.AddNewSourceBuffer(std::move(Instantiation
), SMLoc());
5554 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
5558 /// parseDirectiveRept
5559 /// ::= .rep | .rept count
5560 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc
, StringRef Dir
) {
5561 const MCExpr
*CountExpr
;
5562 SMLoc CountLoc
= getTok().getLoc();
5563 if (parseExpression(CountExpr
))
5567 if (!CountExpr
->evaluateAsAbsolute(Count
, getStreamer().getAssemblerPtr())) {
5568 return Error(CountLoc
, "unexpected token in '" + Dir
+ "' directive");
5571 if (check(Count
< 0, CountLoc
, "Count is negative") ||
5572 parseToken(AsmToken::EndOfStatement
,
5573 "unexpected token in '" + Dir
+ "' directive"))
5576 // Lex the rept definition.
5577 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5581 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5582 // to hold the macro body with substitutions.
5583 SmallString
<256> Buf
;
5584 raw_svector_ostream
OS(Buf
);
5586 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5587 if (expandMacro(OS
, M
->Body
, None
, None
, false, getTok().getLoc()))
5590 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5595 /// parseDirectiveIrp
5596 /// ::= .irp symbol,values
5597 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc
) {
5598 MCAsmMacroParameter Parameter
;
5599 MCAsmMacroArguments A
;
5600 if (check(parseIdentifier(Parameter
.Name
),
5601 "expected identifier in '.irp' directive") ||
5602 parseToken(AsmToken::Comma
, "expected comma in '.irp' directive") ||
5603 parseMacroArguments(nullptr, A
) ||
5604 parseToken(AsmToken::EndOfStatement
, "expected End of Statement"))
5607 // Lex the irp definition.
5608 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5612 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5613 // to hold the macro body with substitutions.
5614 SmallString
<256> Buf
;
5615 raw_svector_ostream
OS(Buf
);
5617 for (const MCAsmMacroArgument
&Arg
: A
) {
5618 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5619 // This is undocumented, but GAS seems to support it.
5620 if (expandMacro(OS
, M
->Body
, Parameter
, Arg
, true, getTok().getLoc()))
5624 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5629 /// parseDirectiveIrpc
5630 /// ::= .irpc symbol,values
5631 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc
) {
5632 MCAsmMacroParameter Parameter
;
5633 MCAsmMacroArguments A
;
5635 if (check(parseIdentifier(Parameter
.Name
),
5636 "expected identifier in '.irpc' directive") ||
5637 parseToken(AsmToken::Comma
, "expected comma in '.irpc' directive") ||
5638 parseMacroArguments(nullptr, A
))
5641 if (A
.size() != 1 || A
.front().size() != 1)
5642 return TokError("unexpected token in '.irpc' directive");
5644 // Eat the end of statement.
5645 if (parseToken(AsmToken::EndOfStatement
, "expected end of statement"))
5648 // Lex the irpc definition.
5649 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5653 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5654 // to hold the macro body with substitutions.
5655 SmallString
<256> Buf
;
5656 raw_svector_ostream
OS(Buf
);
5658 StringRef Values
= A
.front().front().getString();
5659 for (std::size_t I
= 0, End
= Values
.size(); I
!= End
; ++I
) {
5660 MCAsmMacroArgument Arg
;
5661 Arg
.emplace_back(AsmToken::Identifier
, Values
.slice(I
, I
+ 1));
5663 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5664 // This is undocumented, but GAS seems to support it.
5665 if (expandMacro(OS
, M
->Body
, Parameter
, Arg
, true, getTok().getLoc()))
5669 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5674 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc
) {
5675 if (ActiveMacros
.empty())
5676 return TokError("unmatched '.endr' directive");
5678 // The only .repl that should get here are the ones created by
5679 // instantiateMacroLikeBody.
5680 assert(getLexer().is(AsmToken::EndOfStatement
));
5686 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc
, ParseStatementInfo
&Info
,
5688 const MCExpr
*Value
;
5689 SMLoc ExprLoc
= getLexer().getLoc();
5690 if (parseExpression(Value
))
5692 const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
);
5694 return Error(ExprLoc
, "unexpected expression in _emit");
5695 uint64_t IntValue
= MCE
->getValue();
5696 if (!isUInt
<8>(IntValue
) && !isInt
<8>(IntValue
))
5697 return Error(ExprLoc
, "literal value out of range for directive");
5699 Info
.AsmRewrites
->emplace_back(AOK_Emit
, IDLoc
, Len
);
5703 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc
, ParseStatementInfo
&Info
) {
5704 const MCExpr
*Value
;
5705 SMLoc ExprLoc
= getLexer().getLoc();
5706 if (parseExpression(Value
))
5708 const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
);
5710 return Error(ExprLoc
, "unexpected expression in align");
5711 uint64_t IntValue
= MCE
->getValue();
5712 if (!isPowerOf2_64(IntValue
))
5713 return Error(ExprLoc
, "literal value not a power of two greater then zero");
5715 Info
.AsmRewrites
->emplace_back(AOK_Align
, IDLoc
, 5, Log2_64(IntValue
));
5719 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc
) {
5720 const AsmToken StrTok
= getTok();
5722 if (StrTok
.isNot(AsmToken::String
) || StrTok
.getString().front() != '"')
5723 return Error(DirectiveLoc
, "expected double quoted string after .print");
5724 if (parseToken(AsmToken::EndOfStatement
, "expected end of statement"))
5726 llvm::outs() << StrTok
.getStringContents() << '\n';
5730 bool AsmParser::parseDirectiveAddrsig() {
5731 getStreamer().EmitAddrsig();
5735 bool AsmParser::parseDirectiveAddrsigSym() {
5737 if (check(parseIdentifier(Name
),
5738 "expected identifier in '.addrsig_sym' directive"))
5740 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
5741 getStreamer().EmitAddrsigSym(Sym
);
5745 // We are comparing pointers, but the pointers are relative to a single string.
5746 // Thus, this should always be deterministic.
5747 static int rewritesSort(const AsmRewrite
*AsmRewriteA
,
5748 const AsmRewrite
*AsmRewriteB
) {
5749 if (AsmRewriteA
->Loc
.getPointer() < AsmRewriteB
->Loc
.getPointer())
5751 if (AsmRewriteB
->Loc
.getPointer() < AsmRewriteA
->Loc
.getPointer())
5754 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5755 // rewrite to the same location. Make sure the SizeDirective rewrite is
5756 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5757 // ensures the sort algorithm is stable.
5758 if (AsmRewritePrecedence
[AsmRewriteA
->Kind
] >
5759 AsmRewritePrecedence
[AsmRewriteB
->Kind
])
5762 if (AsmRewritePrecedence
[AsmRewriteA
->Kind
] <
5763 AsmRewritePrecedence
[AsmRewriteB
->Kind
])
5765 llvm_unreachable("Unstable rewrite sort.");
5768 bool AsmParser::parseMSInlineAsm(
5769 void *AsmLoc
, std::string
&AsmString
, unsigned &NumOutputs
,
5770 unsigned &NumInputs
, SmallVectorImpl
<std::pair
<void *, bool>> &OpDecls
,
5771 SmallVectorImpl
<std::string
> &Constraints
,
5772 SmallVectorImpl
<std::string
> &Clobbers
, const MCInstrInfo
*MII
,
5773 const MCInstPrinter
*IP
, MCAsmParserSemaCallback
&SI
) {
5774 SmallVector
<void *, 4> InputDecls
;
5775 SmallVector
<void *, 4> OutputDecls
;
5776 SmallVector
<bool, 4> InputDeclsAddressOf
;
5777 SmallVector
<bool, 4> OutputDeclsAddressOf
;
5778 SmallVector
<std::string
, 4> InputConstraints
;
5779 SmallVector
<std::string
, 4> OutputConstraints
;
5780 SmallVector
<unsigned, 4> ClobberRegs
;
5782 SmallVector
<AsmRewrite
, 4> AsmStrRewrites
;
5787 // While we have input, parse each statement.
5788 unsigned InputIdx
= 0;
5789 unsigned OutputIdx
= 0;
5790 while (getLexer().isNot(AsmToken::Eof
)) {
5791 // Parse curly braces marking block start/end
5792 if (parseCurlyBlockScope(AsmStrRewrites
))
5795 ParseStatementInfo
Info(&AsmStrRewrites
);
5796 bool StatementErr
= parseStatement(Info
, &SI
);
5798 if (StatementErr
|| Info
.ParseError
) {
5799 // Emit pending errors if any exist.
5800 printPendingErrors();
5804 // No pending error should exist here.
5805 assert(!hasPendingError() && "unexpected error from parseStatement");
5807 if (Info
.Opcode
== ~0U)
5810 const MCInstrDesc
&Desc
= MII
->get(Info
.Opcode
);
5812 // Build the list of clobbers, outputs and inputs.
5813 for (unsigned i
= 1, e
= Info
.ParsedOperands
.size(); i
!= e
; ++i
) {
5814 MCParsedAsmOperand
&Operand
= *Info
.ParsedOperands
[i
];
5817 if (Operand
.isImm())
5820 // Register operand.
5821 if (Operand
.isReg() && !Operand
.needAddressOf() &&
5822 !getTargetParser().OmitRegisterFromClobberLists(Operand
.getReg())) {
5823 unsigned NumDefs
= Desc
.getNumDefs();
5825 if (NumDefs
&& Operand
.getMCOperandNum() < NumDefs
)
5826 ClobberRegs
.push_back(Operand
.getReg());
5830 // Expr/Input or Output.
5831 StringRef SymName
= Operand
.getSymName();
5832 if (SymName
.empty())
5835 void *OpDecl
= Operand
.getOpDecl();
5839 bool isOutput
= (i
== 1) && Desc
.mayStore();
5840 SMLoc Start
= SMLoc::getFromPointer(SymName
.data());
5843 OutputDecls
.push_back(OpDecl
);
5844 OutputDeclsAddressOf
.push_back(Operand
.needAddressOf());
5845 OutputConstraints
.push_back(("=" + Operand
.getConstraint()).str());
5846 AsmStrRewrites
.emplace_back(AOK_Output
, Start
, SymName
.size());
5848 InputDecls
.push_back(OpDecl
);
5849 InputDeclsAddressOf
.push_back(Operand
.needAddressOf());
5850 InputConstraints
.push_back(Operand
.getConstraint().str());
5851 AsmStrRewrites
.emplace_back(AOK_Input
, Start
, SymName
.size());
5855 // Consider implicit defs to be clobbers. Think of cpuid and push.
5856 ArrayRef
<MCPhysReg
> ImpDefs(Desc
.getImplicitDefs(),
5857 Desc
.getNumImplicitDefs());
5858 ClobberRegs
.insert(ClobberRegs
.end(), ImpDefs
.begin(), ImpDefs
.end());
5861 // Set the number of Outputs and Inputs.
5862 NumOutputs
= OutputDecls
.size();
5863 NumInputs
= InputDecls
.size();
5865 // Set the unique clobbers.
5866 array_pod_sort(ClobberRegs
.begin(), ClobberRegs
.end());
5867 ClobberRegs
.erase(std::unique(ClobberRegs
.begin(), ClobberRegs
.end()),
5869 Clobbers
.assign(ClobberRegs
.size(), std::string());
5870 for (unsigned I
= 0, E
= ClobberRegs
.size(); I
!= E
; ++I
) {
5871 raw_string_ostream
OS(Clobbers
[I
]);
5872 IP
->printRegName(OS
, ClobberRegs
[I
]);
5875 // Merge the various outputs and inputs. Output are expected first.
5876 if (NumOutputs
|| NumInputs
) {
5877 unsigned NumExprs
= NumOutputs
+ NumInputs
;
5878 OpDecls
.resize(NumExprs
);
5879 Constraints
.resize(NumExprs
);
5880 for (unsigned i
= 0; i
< NumOutputs
; ++i
) {
5881 OpDecls
[i
] = std::make_pair(OutputDecls
[i
], OutputDeclsAddressOf
[i
]);
5882 Constraints
[i
] = OutputConstraints
[i
];
5884 for (unsigned i
= 0, j
= NumOutputs
; i
< NumInputs
; ++i
, ++j
) {
5885 OpDecls
[j
] = std::make_pair(InputDecls
[i
], InputDeclsAddressOf
[i
]);
5886 Constraints
[j
] = InputConstraints
[i
];
5890 // Build the IR assembly string.
5891 std::string AsmStringIR
;
5892 raw_string_ostream
OS(AsmStringIR
);
5893 StringRef ASMString
=
5894 SrcMgr
.getMemoryBuffer(SrcMgr
.getMainFileID())->getBuffer();
5895 const char *AsmStart
= ASMString
.begin();
5896 const char *AsmEnd
= ASMString
.end();
5897 array_pod_sort(AsmStrRewrites
.begin(), AsmStrRewrites
.end(), rewritesSort
);
5898 for (const AsmRewrite
&AR
: AsmStrRewrites
) {
5899 AsmRewriteKind Kind
= AR
.Kind
;
5901 const char *Loc
= AR
.Loc
.getPointer();
5902 assert(Loc
>= AsmStart
&& "Expected Loc to be at or after Start!");
5904 // Emit everything up to the immediate/expression.
5905 if (unsigned Len
= Loc
- AsmStart
)
5906 OS
<< StringRef(AsmStart
, Len
);
5908 // Skip the original expression.
5909 if (Kind
== AOK_Skip
) {
5910 AsmStart
= Loc
+ AR
.Len
;
5914 unsigned AdditionalSkip
= 0;
5915 // Rewrite expressions in $N notation.
5920 assert(AR
.IntelExp
.isValid() && "cannot write invalid intel expression");
5921 if (AR
.IntelExp
.NeedBracs
)
5923 if (AR
.IntelExp
.hasBaseReg())
5924 OS
<< AR
.IntelExp
.BaseReg
;
5925 if (AR
.IntelExp
.hasIndexReg())
5926 OS
<< (AR
.IntelExp
.hasBaseReg() ? " + " : "")
5927 << AR
.IntelExp
.IndexReg
;
5928 if (AR
.IntelExp
.Scale
> 1)
5929 OS
<< " * $$" << AR
.IntelExp
.Scale
;
5930 if (AR
.IntelExp
.Imm
|| !AR
.IntelExp
.hasRegs())
5931 OS
<< (AR
.IntelExp
.hasRegs() ? " + $$" : "$$") << AR
.IntelExp
.Imm
;
5932 if (AR
.IntelExp
.NeedBracs
)
5936 OS
<< Ctx
.getAsmInfo()->getPrivateLabelPrefix() << AR
.Label
;
5939 OS
<< '$' << InputIdx
++;
5942 OS
<< '$' << OutputIdx
++;
5944 case AOK_SizeDirective
:
5947 case 8: OS
<< "byte ptr "; break;
5948 case 16: OS
<< "word ptr "; break;
5949 case 32: OS
<< "dword ptr "; break;
5950 case 64: OS
<< "qword ptr "; break;
5951 case 80: OS
<< "xword ptr "; break;
5952 case 128: OS
<< "xmmword ptr "; break;
5953 case 256: OS
<< "ymmword ptr "; break;
5960 // MS alignment directives are measured in bytes. If the native assembler
5961 // measures alignment in bytes, we can pass it straight through.
5963 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5966 // Alignment is in log2 form, so print that instead and skip the original
5968 unsigned Val
= AR
.Val
;
5970 assert(Val
< 10 && "Expected alignment less then 2^10.");
5971 AdditionalSkip
= (Val
< 4) ? 2 : Val
< 7 ? 3 : 4;
5977 case AOK_EndOfStatement
:
5982 // Skip the original expression.
5983 AsmStart
= Loc
+ AR
.Len
+ AdditionalSkip
;
5986 // Emit the remainder of the asm string.
5987 if (AsmStart
!= AsmEnd
)
5988 OS
<< StringRef(AsmStart
, AsmEnd
- AsmStart
);
5990 AsmString
= OS
.str();
5995 namespace MCParserUtils
{
5997 /// Returns whether the given symbol is used anywhere in the given expression,
5998 /// or subexpressions.
5999 static bool isSymbolUsedInExpression(const MCSymbol
*Sym
, const MCExpr
*Value
) {
6000 switch (Value
->getKind()) {
6001 case MCExpr::Binary
: {
6002 const MCBinaryExpr
*BE
= static_cast<const MCBinaryExpr
*>(Value
);
6003 return isSymbolUsedInExpression(Sym
, BE
->getLHS()) ||
6004 isSymbolUsedInExpression(Sym
, BE
->getRHS());
6006 case MCExpr::Target
:
6007 case MCExpr::Constant
:
6009 case MCExpr::SymbolRef
: {
6011 static_cast<const MCSymbolRefExpr
*>(Value
)->getSymbol();
6013 return isSymbolUsedInExpression(Sym
, S
.getVariableValue());
6017 return isSymbolUsedInExpression(
6018 Sym
, static_cast<const MCUnaryExpr
*>(Value
)->getSubExpr());
6021 llvm_unreachable("Unknown expr kind!");
6024 bool parseAssignmentExpression(StringRef Name
, bool allow_redef
,
6025 MCAsmParser
&Parser
, MCSymbol
*&Sym
,
6026 const MCExpr
*&Value
) {
6028 // FIXME: Use better location, we should use proper tokens.
6029 SMLoc EqualLoc
= Parser
.getTok().getLoc();
6030 if (Parser
.parseExpression(Value
))
6031 return Parser
.TokError("missing expression");
6033 // Note: we don't count b as used in "a = b". This is to allow
6037 if (Parser
.parseToken(AsmToken::EndOfStatement
))
6040 // Validate that the LHS is allowed to be a variable (either it has not been
6041 // used as a symbol, or it is an absolute symbol).
6042 Sym
= Parser
.getContext().lookupSymbol(Name
);
6044 // Diagnose assignment to a label.
6046 // FIXME: Diagnostics. Note the location of the definition as a label.
6047 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6048 if (isSymbolUsedInExpression(Sym
, Value
))
6049 return Parser
.Error(EqualLoc
, "Recursive use of '" + Name
+ "'");
6050 else if (Sym
->isUndefined(/*SetUsed*/ false) && !Sym
->isUsed() &&
6052 ; // Allow redefinitions of undefined symbols only used in directives.
6053 else if (Sym
->isVariable() && !Sym
->isUsed() && allow_redef
)
6054 ; // Allow redefinitions of variables that haven't yet been used.
6055 else if (!Sym
->isUndefined() && (!Sym
->isVariable() || !allow_redef
))
6056 return Parser
.Error(EqualLoc
, "redefinition of '" + Name
+ "'");
6057 else if (!Sym
->isVariable())
6058 return Parser
.Error(EqualLoc
, "invalid assignment to '" + Name
+ "'");
6059 else if (!isa
<MCConstantExpr
>(Sym
->getVariableValue()))
6060 return Parser
.Error(EqualLoc
,
6061 "invalid reassignment of non-absolute variable '" +
6063 } else if (Name
== ".") {
6064 Parser
.getStreamer().emitValueToOffset(Value
, 0, EqualLoc
);
6067 Sym
= Parser
.getContext().getOrCreateSymbol(Name
);
6069 Sym
->setRedefinable(allow_redef
);
6074 } // end namespace MCParserUtils
6075 } // end namespace llvm
6077 /// Create an MCAsmParser instance.
6078 MCAsmParser
*llvm::createMCAsmParser(SourceMgr
&SM
, MCContext
&C
,
6079 MCStreamer
&Out
, const MCAsmInfo
&MAI
,
6081 return new AsmParser(SM
, C
, Out
, MAI
, CB
);