1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
156 /// The values from the last parsed cpp hash file line comment if any.
157 StringRef CppHashFilename;
158 int64_t CppHashLineNumber;
161 /// When generating dwarf for assembly source files we need to calculate the
162 /// logical line number based on the last parsed cpp hash file line comment
163 /// and current line. Since this is slow and messes up the SourceMgr's
164 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
165 SMLoc LastQueryIDLoc;
166 unsigned LastQueryBuffer;
167 unsigned LastQueryLine;
169 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
170 unsigned AssemblerDialect;
172 /// \brief is Darwin compatibility enabled?
175 /// \brief Are we parsing ms-style inline assembly?
176 bool ParsingInlineAsm;
179 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
180 const MCAsmInfo &MAI);
181 ~AsmParser() override;
183 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
185 void addDirectiveHandler(StringRef Directive,
186 ExtensionDirectiveHandler Handler) override {
187 ExtensionDirectiveMap[Directive] = Handler;
190 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
191 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
195 /// @name MCAsmParser Interface
198 SourceMgr &getSourceManager() override { return SrcMgr; }
199 MCAsmLexer &getLexer() override { return Lexer; }
200 MCContext &getContext() override { return Ctx; }
201 MCStreamer &getStreamer() override { return Out; }
202 unsigned getAssemblerDialect() override {
203 if (AssemblerDialect == ~0U)
204 return MAI.getAssemblerDialect();
206 return AssemblerDialect;
208 void setAssemblerDialect(unsigned i) override {
209 AssemblerDialect = i;
212 void Note(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None) override;
214 bool Warning(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Error(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
219 const AsmToken &Lex() override;
221 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
222 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
224 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
225 unsigned &NumOutputs, unsigned &NumInputs,
226 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
227 SmallVectorImpl<std::string> &Constraints,
228 SmallVectorImpl<std::string> &Clobbers,
229 const MCInstrInfo *MII, const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI) override;
232 bool parseExpression(const MCExpr *&Res);
233 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
234 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseAbsoluteExpression(int64_t &Res) override;
238 /// \brief Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 bool parseIdentifier(StringRef &Res) override;
241 void eatToEndOfStatement() override;
243 void checkForValidSection() override;
248 bool parseStatement(ParseStatementInfo &Info,
249 MCAsmParserSemaCallback *SI);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters,
257 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, MCAsmMacro Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument.
290 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
292 /// \brief Parse all macro arguments for a given macro.
293 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
295 void printMacroInstantiations();
296 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
297 ArrayRef<SMRange> Ranges = None) const {
298 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
300 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
302 /// \brief Enter the specified file. This returns true on failure.
303 bool enterIncludeFile(const std::string &Filename);
305 /// \brief Process the specified file for the .incbin directive.
306 /// This returns true on failure.
307 bool processIncbinFile(const std::string &Filename);
309 /// \brief Reset the current lexer position to that given by \p Loc. The
310 /// current token is not set; clients should ensure Lex() is called
313 /// \param InBuffer If not 0, should be the known buffer id that contains the
315 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
317 /// \brief Parse up to the end of statement and a return the contents from the
318 /// current token until the end of the statement; the current token on exit
319 /// will be either the EndOfStatement or EOF.
320 StringRef parseStringToEndOfStatement() override;
322 /// \brief Parse until the end of a statement or a comma is encountered,
323 /// return the contents from the current token up to the end or comma.
324 StringRef parseStringToComma();
326 bool parseAssignment(StringRef Name, bool allow_redef,
327 bool NoDeadStrip = false);
329 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
330 MCBinaryExpr::Opcode &Kind);
332 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 // Generic (target and platform independent) directive parsing.
340 DK_NO_DIRECTIVE, // Placeholder
341 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
342 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
343 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
344 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
345 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
346 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
347 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
348 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
349 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
350 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
351 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
352 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
353 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
354 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
355 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
356 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
357 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
358 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
359 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
360 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
361 DK_MACROS_ON, DK_MACROS_OFF,
362 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
364 DK_ERR, DK_ERROR, DK_WARNING,
368 /// \brief Maps directive name --> DirectiveKind enum, for
369 /// directives parsed by this class.
370 StringMap<DirectiveKind> DirectiveKindMap;
372 // ".ascii", ".asciz", ".string"
373 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
374 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
375 bool parseDirectiveOctaValue(); // ".octa"
376 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
377 bool parseDirectiveFill(); // ".fill"
378 bool parseDirectiveZero(); // ".zero"
379 // ".set", ".equ", ".equiv"
380 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
381 bool parseDirectiveOrg(); // ".org"
382 // ".align{,32}", ".p2align{,w,l}"
383 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
385 // ".file", ".line", ".loc", ".stabs"
386 bool parseDirectiveFile(SMLoc DirectiveLoc);
387 bool parseDirectiveLine();
388 bool parseDirectiveLoc();
389 bool parseDirectiveStabs();
392 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIWindowSave();
394 bool parseDirectiveCFISections();
395 bool parseDirectiveCFIStartProc();
396 bool parseDirectiveCFIEndProc();
397 bool parseDirectiveCFIDefCfaOffset();
398 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIAdjustCfaOffset();
400 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
404 bool parseDirectiveCFIRememberState();
405 bool parseDirectiveCFIRestoreState();
406 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIEscape();
409 bool parseDirectiveCFISignalFrame();
410 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
413 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveExitMacro(StringRef Directive);
415 bool parseDirectiveEndMacro(StringRef Directive);
416 bool parseDirectiveMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveMacrosOnOff(StringRef Directive);
419 // ".bundle_align_mode"
420 bool parseDirectiveBundleAlignMode();
422 bool parseDirectiveBundleLock();
424 bool parseDirectiveBundleUnlock();
427 bool parseDirectiveSpace(StringRef IDVal);
429 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
430 bool parseDirectiveLEB128(bool Signed);
432 /// \brief Parse a directive like ".globl" which
433 /// accepts a single symbol (which should be a label or an external).
434 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
436 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
438 bool parseDirectiveAbort(); // ".abort"
439 bool parseDirectiveInclude(); // ".include"
440 bool parseDirectiveIncbin(); // ".incbin"
442 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
443 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
444 // ".ifb" or ".ifnb", depending on ExpectBlank.
445 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
446 // ".ifc" or ".ifnc", depending on ExpectEqual.
447 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
448 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
449 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
450 // ".ifdef" or ".ifndef", depending on expect_defined
451 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
452 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
453 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
454 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
455 bool parseEscapedString(std::string &Data) override;
457 const MCExpr *applyModifierToExpr(const MCExpr *E,
458 MCSymbolRefExpr::VariantKind Variant);
460 // Macro-like directives
461 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
462 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
463 raw_svector_ostream &OS);
464 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
465 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
466 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
467 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
469 // "_emit" or "__emit"
470 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
474 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
477 bool parseDirectiveEnd(SMLoc DirectiveLoc);
479 // ".err" or ".error"
480 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
483 bool parseDirectiveWarning(SMLoc DirectiveLoc);
485 void initializeDirectiveKindMap();
491 extern MCAsmParserExtension *createDarwinAsmParser();
492 extern MCAsmParserExtension *createELFAsmParser();
493 extern MCAsmParserExtension *createCOFFAsmParser();
497 enum { DEFAULT_ADDRSPACE = 0 };
499 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
500 const MCAsmInfo &MAI)
501 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
502 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
503 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
504 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
505 // Save the old handler.
506 SavedDiagHandler = SrcMgr.getDiagHandler();
507 SavedDiagContext = SrcMgr.getDiagContext();
508 // Set our own handler which calls the saved handler.
509 SrcMgr.setDiagHandler(DiagHandler, this);
510 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
512 // Initialize the platform / file format parser.
513 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
514 case MCObjectFileInfo::IsCOFF:
515 PlatformParser.reset(createCOFFAsmParser());
517 case MCObjectFileInfo::IsMachO:
518 PlatformParser.reset(createDarwinAsmParser());
521 case MCObjectFileInfo::IsELF:
522 PlatformParser.reset(createELFAsmParser());
526 PlatformParser->Initialize(*this);
527 initializeDirectiveKindMap();
529 NumOfMacroInstantiations = 0;
532 AsmParser::~AsmParser() {
533 assert((HadError || ActiveMacros.empty()) &&
534 "Unexpected active macro instantiation!");
537 void AsmParser::printMacroInstantiations() {
538 // Print the active macro instantiation stack.
539 for (std::vector<MacroInstantiation *>::const_reverse_iterator
540 it = ActiveMacros.rbegin(),
541 ie = ActiveMacros.rend();
543 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
544 "while in macro instantiation");
547 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
548 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
549 printMacroInstantiations();
552 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 if (getTargetParser().getTargetOptions().MCFatalWarnings)
554 return Error(L, Msg, Ranges);
555 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
562 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::enterIncludeFile(const std::string &Filename) {
568 std::string IncludedFile;
570 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
579 /// Process the specified .incbin file by searching for it in the include paths
580 /// then just emitting the byte contents of the file to the streamer. This
581 /// returns true on failure.
582 bool AsmParser::processIncbinFile(const std::string &Filename) {
583 std::string IncludedFile;
585 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 // Pick up the bytes from the file and emit them.
590 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
594 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
595 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
596 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
600 const AsmToken &AsmParser::Lex() {
601 const AsmToken *tok = &Lexer.Lex();
603 if (tok->is(AsmToken::Eof)) {
604 // If this is the end of an included file, pop the parent file off the
606 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
607 if (ParentIncludeLoc != SMLoc()) {
608 jumpToLoc(ParentIncludeLoc);
613 if (tok->is(AsmToken::Error))
614 Error(Lexer.getErrLoc(), Lexer.getErr());
619 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
620 // Create the initial section, if requested.
621 if (!NoInitialTextSection)
622 Out.InitSections(false);
628 AsmCond StartingCondState = TheCondState;
630 // If we are generating dwarf for assembly source files save the initial text
631 // section and generate a .file directive.
632 if (getContext().getGenDwarfForAssembly()) {
633 MCSymbol *SectionStartSym = getContext().createTempSymbol();
634 getStreamer().EmitLabel(SectionStartSym);
635 auto InsertResult = getContext().addGenDwarfSection(
636 getStreamer().getCurrentSection().first);
637 assert(InsertResult.second && ".text section should not have debug info yet");
638 InsertResult.first->second.first = SectionStartSym;
639 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
640 0, StringRef(), getContext().getMainFileName()));
643 // While we have input, parse each statement.
644 while (Lexer.isNot(AsmToken::Eof)) {
645 ParseStatementInfo Info;
646 if (!parseStatement(Info, nullptr))
649 // We had an error, validate that one was emitted and recover by skipping to
651 assert(HadError && "Parse statement returned an error, but none emitted!");
652 eatToEndOfStatement();
655 if (TheCondState.TheCond != StartingCondState.TheCond ||
656 TheCondState.Ignore != StartingCondState.Ignore)
657 return TokError("unmatched .ifs or .elses");
659 // Check to see there are no empty DwarfFile slots.
660 const auto &LineTables = getContext().getMCDwarfLineTables();
661 if (!LineTables.empty()) {
663 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
664 if (File.Name.empty() && Index != 0)
665 TokError("unassigned file number: " + Twine(Index) +
666 " for .file directives");
671 // Check to see that all assembler local symbols were actually defined.
672 // Targets that don't do subsections via symbols may not want this, though,
673 // so conservatively exclude them. Only do this if we're finalizing, though,
674 // as otherwise we won't necessarilly have seen everything yet.
675 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
676 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
677 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
680 MCSymbol *Sym = i->getValue();
681 // Variable symbols may not be marked as defined, so check those
682 // explicitly. If we know it's a variable, we have a definition for
683 // the purposes of this check.
684 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
685 // FIXME: We would really like to refer back to where the symbol was
686 // first referenced for a source location. We need to add something
687 // to track that. Currently, we just point to the end of the file.
689 getLexer().getLoc(), SourceMgr::DK_Error,
690 "assembler local symbol '" + Sym->getName() + "' not defined");
694 // Finalize the output stream if there are no errors and if the client wants
696 if (!HadError && !NoFinalize)
702 void AsmParser::checkForValidSection() {
703 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
704 TokError("expected section directive before assembly directive");
705 Out.InitSections(false);
709 /// \brief Throw away the rest of the line for testing purposes.
710 void AsmParser::eatToEndOfStatement() {
711 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
715 if (Lexer.is(AsmToken::EndOfStatement))
719 StringRef AsmParser::parseStringToEndOfStatement() {
720 const char *Start = getTok().getLoc().getPointer();
722 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
725 const char *End = getTok().getLoc().getPointer();
726 return StringRef(Start, End - Start);
729 StringRef AsmParser::parseStringToComma() {
730 const char *Start = getTok().getLoc().getPointer();
732 while (Lexer.isNot(AsmToken::EndOfStatement) &&
733 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
736 const char *End = getTok().getLoc().getPointer();
737 return StringRef(Start, End - Start);
740 /// \brief Parse a paren expression and return it.
741 /// NOTE: This assumes the leading '(' has already been consumed.
743 /// parenexpr ::= expr)
745 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (parseExpression(Res))
748 if (Lexer.isNot(AsmToken::RParen))
749 return TokError("expected ')' in parentheses expression");
750 EndLoc = Lexer.getTok().getEndLoc();
755 /// \brief Parse a bracket expression and return it.
756 /// NOTE: This assumes the leading '[' has already been consumed.
758 /// bracketexpr ::= expr]
760 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
761 if (parseExpression(Res))
763 if (Lexer.isNot(AsmToken::RBrac))
764 return TokError("expected ']' in brackets expression");
765 EndLoc = Lexer.getTok().getEndLoc();
770 /// \brief Parse a primary expression and return it.
771 /// primaryexpr ::= (parenexpr
772 /// primaryexpr ::= symbol
773 /// primaryexpr ::= number
774 /// primaryexpr ::= '.'
775 /// primaryexpr ::= ~,+,- primaryexpr
776 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
777 SMLoc FirstTokenLoc = getLexer().getLoc();
778 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
779 switch (FirstTokenKind) {
781 return TokError("unknown token in expression");
782 // If we have an error assume that we've already handled it.
783 case AsmToken::Error:
785 case AsmToken::Exclaim:
786 Lex(); // Eat the operator.
787 if (parsePrimaryExpr(Res, EndLoc))
789 Res = MCUnaryExpr::CreateLNot(Res, getContext());
791 case AsmToken::Dollar:
793 case AsmToken::String:
794 case AsmToken::Identifier: {
795 StringRef Identifier;
796 if (parseIdentifier(Identifier)) {
797 if (FirstTokenKind == AsmToken::Dollar) {
798 if (Lexer.getMAI().getDollarIsPC()) {
799 // This is a '$' reference, which references the current PC. Emit a
800 // temporary label to the streamer and refer to it.
801 MCSymbol *Sym = Ctx.createTempSymbol();
803 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
805 EndLoc = FirstTokenLoc;
808 return Error(FirstTokenLoc, "invalid token in expression");
811 // Parse symbol variant
812 std::pair<StringRef, StringRef> Split;
813 if (!MAI.useParensForSymbolVariant()) {
814 if (FirstTokenKind == AsmToken::String) {
815 if (Lexer.is(AsmToken::At)) {
816 Lexer.Lex(); // eat @
817 SMLoc AtLoc = getLexer().getLoc();
819 if (parseIdentifier(VName))
820 return Error(AtLoc, "expected symbol variant after '@'");
822 Split = std::make_pair(Identifier, VName);
825 Split = Identifier.split('@');
827 } else if (Lexer.is(AsmToken::LParen)) {
828 Lexer.Lex(); // eat (
830 parseIdentifier(VName);
831 if (Lexer.isNot(AsmToken::RParen)) {
832 return Error(Lexer.getTok().getLoc(),
833 "unexpected token in variant, expected ')'");
835 Lexer.Lex(); // eat )
836 Split = std::make_pair(Identifier, VName);
839 EndLoc = SMLoc::getFromPointer(Identifier.end());
841 // This is a symbol reference.
842 StringRef SymbolName = Identifier;
843 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
845 // Lookup the symbol variant if used.
846 if (Split.second.size()) {
847 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
848 if (Variant != MCSymbolRefExpr::VK_Invalid) {
849 SymbolName = Split.first;
850 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
851 Variant = MCSymbolRefExpr::VK_None;
853 return Error(SMLoc::getFromPointer(Split.second.begin()),
854 "invalid variant '" + Split.second + "'");
858 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
860 // If this is an absolute variable reference, substitute it now to preserve
861 // semantics in the face of reassignment.
862 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
864 return Error(EndLoc, "unexpected modifier on variable reference");
866 Res = Sym->getVariableValue();
870 // Otherwise create a symbol ref.
871 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
874 case AsmToken::BigNum:
875 return TokError("literal value out of range for directive");
876 case AsmToken::Integer: {
877 SMLoc Loc = getTok().getLoc();
878 int64_t IntVal = getTok().getIntVal();
879 Res = MCConstantExpr::Create(IntVal, getContext());
880 EndLoc = Lexer.getTok().getEndLoc();
882 // Look for 'b' or 'f' following an Integer as a directional label
883 if (Lexer.getKind() == AsmToken::Identifier) {
884 StringRef IDVal = getTok().getString();
885 // Lookup the symbol variant if used.
886 std::pair<StringRef, StringRef> Split = IDVal.split('@');
887 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
888 if (Split.first.size() != IDVal.size()) {
889 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
890 if (Variant == MCSymbolRefExpr::VK_Invalid)
891 return TokError("invalid variant '" + Split.second + "'");
894 if (IDVal == "f" || IDVal == "b") {
896 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
897 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
898 if (IDVal == "b" && Sym->isUndefined())
899 return Error(Loc, "invalid reference to undefined symbol");
900 EndLoc = Lexer.getTok().getEndLoc();
901 Lex(); // Eat identifier.
906 case AsmToken::Real: {
907 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
908 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
909 Res = MCConstantExpr::Create(IntVal, getContext());
910 EndLoc = Lexer.getTok().getEndLoc();
914 case AsmToken::Dot: {
915 // This is a '.' reference, which references the current PC. Emit a
916 // temporary label to the streamer and refer to it.
917 MCSymbol *Sym = Ctx.createTempSymbol();
919 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
920 EndLoc = Lexer.getTok().getEndLoc();
921 Lex(); // Eat identifier.
924 case AsmToken::LParen:
925 Lex(); // Eat the '('.
926 return parseParenExpr(Res, EndLoc);
927 case AsmToken::LBrac:
928 if (!PlatformParser->HasBracketExpressions())
929 return TokError("brackets expression not supported on this target");
930 Lex(); // Eat the '['.
931 return parseBracketExpr(Res, EndLoc);
932 case AsmToken::Minus:
933 Lex(); // Eat the operator.
934 if (parsePrimaryExpr(Res, EndLoc))
936 Res = MCUnaryExpr::CreateMinus(Res, getContext());
939 Lex(); // Eat the operator.
940 if (parsePrimaryExpr(Res, EndLoc))
942 Res = MCUnaryExpr::CreatePlus(Res, getContext());
944 case AsmToken::Tilde:
945 Lex(); // Eat the operator.
946 if (parsePrimaryExpr(Res, EndLoc))
948 Res = MCUnaryExpr::CreateNot(Res, getContext());
953 bool AsmParser::parseExpression(const MCExpr *&Res) {
955 return parseExpression(Res, EndLoc);
959 AsmParser::applyModifierToExpr(const MCExpr *E,
960 MCSymbolRefExpr::VariantKind Variant) {
961 // Ask the target implementation about this expression first.
962 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
965 // Recurse over the given expression, rebuilding it to apply the given variant
966 // if there is exactly one symbol.
967 switch (E->getKind()) {
969 case MCExpr::Constant:
972 case MCExpr::SymbolRef: {
973 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
975 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
976 TokError("invalid variant on expression '" + getTok().getIdentifier() +
977 "' (already modified)");
981 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
984 case MCExpr::Unary: {
985 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
986 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
989 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
992 case MCExpr::Binary: {
993 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
994 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
995 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1005 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1009 llvm_unreachable("Invalid expression kind!");
1012 /// \brief Parse an expression and return it.
1014 /// expr ::= expr &&,|| expr -> lowest.
1015 /// expr ::= expr |,^,&,! expr
1016 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1017 /// expr ::= expr <<,>> expr
1018 /// expr ::= expr +,- expr
1019 /// expr ::= expr *,/,% expr -> highest.
1020 /// expr ::= primaryexpr
1022 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1023 // Parse the expression.
1025 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1028 // As a special case, we support 'a op b @ modifier' by rewriting the
1029 // expression to include the modifier. This is inefficient, but in general we
1030 // expect users to use 'a@modifier op b'.
1031 if (Lexer.getKind() == AsmToken::At) {
1034 if (Lexer.isNot(AsmToken::Identifier))
1035 return TokError("unexpected symbol modifier following '@'");
1037 MCSymbolRefExpr::VariantKind Variant =
1038 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1039 if (Variant == MCSymbolRefExpr::VK_Invalid)
1040 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1042 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1044 return TokError("invalid modifier '" + getTok().getIdentifier() +
1045 "' (no symbols present)");
1052 // Try to constant fold it up front, if possible.
1054 if (Res->EvaluateAsAbsolute(Value))
1055 Res = MCConstantExpr::Create(Value, getContext());
1060 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1062 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1065 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1068 SMLoc StartLoc = Lexer.getLoc();
1069 if (parseExpression(Expr))
1072 if (!Expr->EvaluateAsAbsolute(Res))
1073 return Error(StartLoc, "expected absolute expression");
1078 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1079 MCBinaryExpr::Opcode &Kind) {
1082 return 0; // not a binop.
1084 // Lowest Precedence: &&, ||
1085 case AsmToken::AmpAmp:
1086 Kind = MCBinaryExpr::LAnd;
1088 case AsmToken::PipePipe:
1089 Kind = MCBinaryExpr::LOr;
1092 // Low Precedence: |, &, ^
1094 // FIXME: gas seems to support '!' as an infix operator?
1095 case AsmToken::Pipe:
1096 Kind = MCBinaryExpr::Or;
1098 case AsmToken::Caret:
1099 Kind = MCBinaryExpr::Xor;
1102 Kind = MCBinaryExpr::And;
1105 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1106 case AsmToken::EqualEqual:
1107 Kind = MCBinaryExpr::EQ;
1109 case AsmToken::ExclaimEqual:
1110 case AsmToken::LessGreater:
1111 Kind = MCBinaryExpr::NE;
1113 case AsmToken::Less:
1114 Kind = MCBinaryExpr::LT;
1116 case AsmToken::LessEqual:
1117 Kind = MCBinaryExpr::LTE;
1119 case AsmToken::Greater:
1120 Kind = MCBinaryExpr::GT;
1122 case AsmToken::GreaterEqual:
1123 Kind = MCBinaryExpr::GTE;
1126 // Intermediate Precedence: <<, >>
1127 case AsmToken::LessLess:
1128 Kind = MCBinaryExpr::Shl;
1130 case AsmToken::GreaterGreater:
1131 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1134 // High Intermediate Precedence: +, -
1135 case AsmToken::Plus:
1136 Kind = MCBinaryExpr::Add;
1138 case AsmToken::Minus:
1139 Kind = MCBinaryExpr::Sub;
1142 // Highest Precedence: *, /, %
1143 case AsmToken::Star:
1144 Kind = MCBinaryExpr::Mul;
1146 case AsmToken::Slash:
1147 Kind = MCBinaryExpr::Div;
1149 case AsmToken::Percent:
1150 Kind = MCBinaryExpr::Mod;
1155 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1156 /// Res contains the LHS of the expression on input.
1157 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1160 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1161 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1163 // If the next token is lower precedence than we are allowed to eat, return
1164 // successfully with what we ate already.
1165 if (TokPrec < Precedence)
1170 // Eat the next primary expression.
1172 if (parsePrimaryExpr(RHS, EndLoc))
1175 // If BinOp binds less tightly with RHS than the operator after RHS, let
1176 // the pending operator take RHS as its LHS.
1177 MCBinaryExpr::Opcode Dummy;
1178 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1179 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1182 // Merge LHS and RHS according to operator.
1183 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1188 /// ::= EndOfStatement
1189 /// ::= Label* Directive ...Operands... EndOfStatement
1190 /// ::= Label* Identifier OperandList* EndOfStatement
1191 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1192 MCAsmParserSemaCallback *SI) {
1193 if (Lexer.is(AsmToken::EndOfStatement)) {
1199 // Statements always start with an identifier or are a full line comment.
1200 AsmToken ID = getTok();
1201 SMLoc IDLoc = ID.getLoc();
1203 int64_t LocalLabelVal = -1;
1204 // A full line comment is a '#' as the first token.
1205 if (Lexer.is(AsmToken::Hash))
1206 return parseCppHashLineFilenameComment(IDLoc);
1208 // Allow an integer followed by a ':' as a directional local label.
1209 if (Lexer.is(AsmToken::Integer)) {
1210 LocalLabelVal = getTok().getIntVal();
1211 if (LocalLabelVal < 0) {
1212 if (!TheCondState.Ignore)
1213 return TokError("unexpected token at start of statement");
1216 IDVal = getTok().getString();
1217 Lex(); // Consume the integer token to be used as an identifier token.
1218 if (Lexer.getKind() != AsmToken::Colon) {
1219 if (!TheCondState.Ignore)
1220 return TokError("unexpected token at start of statement");
1223 } else if (Lexer.is(AsmToken::Dot)) {
1224 // Treat '.' as a valid identifier in this context.
1227 } else if (parseIdentifier(IDVal)) {
1228 if (!TheCondState.Ignore)
1229 return TokError("unexpected token at start of statement");
1233 // Handle conditional assembly here before checking for skipping. We
1234 // have to do this so that .endif isn't skipped in a ".if 0" block for
1236 StringMap<DirectiveKind>::const_iterator DirKindIt =
1237 DirectiveKindMap.find(IDVal);
1238 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1240 : DirKindIt->getValue();
1251 return parseDirectiveIf(IDLoc, DirKind);
1253 return parseDirectiveIfb(IDLoc, true);
1255 return parseDirectiveIfb(IDLoc, false);
1257 return parseDirectiveIfc(IDLoc, true);
1259 return parseDirectiveIfeqs(IDLoc, true);
1261 return parseDirectiveIfc(IDLoc, false);
1263 return parseDirectiveIfeqs(IDLoc, false);
1265 return parseDirectiveIfdef(IDLoc, true);
1268 return parseDirectiveIfdef(IDLoc, false);
1270 return parseDirectiveElseIf(IDLoc);
1272 return parseDirectiveElse(IDLoc);
1274 return parseDirectiveEndIf(IDLoc);
1277 // Ignore the statement if in the middle of inactive conditional
1279 if (TheCondState.Ignore) {
1280 eatToEndOfStatement();
1284 // FIXME: Recurse on local labels?
1286 // See what kind of statement we have.
1287 switch (Lexer.getKind()) {
1288 case AsmToken::Colon: {
1289 checkForValidSection();
1291 // identifier ':' -> Label.
1294 // Diagnose attempt to use '.' as a label.
1296 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1298 // Diagnose attempt to use a variable as a label.
1300 // FIXME: Diagnostics. Note the location of the definition as a label.
1301 // FIXME: This doesn't diagnose assignment to a symbol which has been
1302 // implicitly marked as external.
1304 if (LocalLabelVal == -1) {
1305 if (ParsingInlineAsm && SI) {
1306 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1307 assert(RewrittenLabel.size() && "We should have an internal name here.");
1308 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1309 IDVal.size(), RewrittenLabel));
1310 IDVal = RewrittenLabel;
1312 Sym = getContext().getOrCreateSymbol(IDVal);
1314 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1316 Sym->redefineIfPossible();
1318 if (!Sym->isUndefined() || Sym->isVariable())
1319 return Error(IDLoc, "invalid symbol redefinition");
1322 if (!ParsingInlineAsm)
1325 // If we are generating dwarf for assembly source files then gather the
1326 // info to make a dwarf label entry for this label if needed.
1327 if (getContext().getGenDwarfForAssembly())
1328 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1331 getTargetParser().onLabelParsed(Sym);
1333 // Consume any end of statement token, if present, to avoid spurious
1334 // AddBlankLine calls().
1335 if (Lexer.is(AsmToken::EndOfStatement)) {
1337 if (Lexer.is(AsmToken::Eof))
1344 case AsmToken::Equal:
1345 // identifier '=' ... -> assignment statement
1348 return parseAssignment(IDVal, true);
1350 default: // Normal instruction or directive.
1354 // If macros are enabled, check to see if this is a macro instantiation.
1355 if (areMacrosEnabled())
1356 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1357 return handleMacroEntry(M, IDLoc);
1360 // Otherwise, we have a normal instruction or directive.
1362 // Directives start with "."
1363 if (IDVal[0] == '.' && IDVal != ".") {
1364 // There are several entities interested in parsing directives:
1366 // 1. The target-specific assembly parser. Some directives are target
1367 // specific or may potentially behave differently on certain targets.
1368 // 2. Asm parser extensions. For example, platform-specific parsers
1369 // (like the ELF parser) register themselves as extensions.
1370 // 3. The generic directive parser implemented by this class. These are
1371 // all the directives that behave in a target and platform independent
1372 // manner, or at least have a default behavior that's shared between
1373 // all targets and platforms.
1375 // First query the target-specific parser. It will return 'true' if it
1376 // isn't interested in this directive.
1377 if (!getTargetParser().ParseDirective(ID))
1380 // Next, check the extension directive map to see if any extension has
1381 // registered itself to parse this directive.
1382 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1383 ExtensionDirectiveMap.lookup(IDVal);
1385 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1387 // Finally, if no one else is interested in this directive, it must be
1388 // generic and familiar to this class.
1394 return parseDirectiveSet(IDVal, true);
1396 return parseDirectiveSet(IDVal, false);
1398 return parseDirectiveAscii(IDVal, false);
1401 return parseDirectiveAscii(IDVal, true);
1403 return parseDirectiveValue(1);
1407 return parseDirectiveValue(2);
1411 return parseDirectiveValue(4);
1414 return parseDirectiveValue(8);
1416 return parseDirectiveOctaValue();
1419 return parseDirectiveRealValue(APFloat::IEEEsingle);
1421 return parseDirectiveRealValue(APFloat::IEEEdouble);
1423 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1424 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1427 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1428 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1431 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1433 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1435 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1437 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1439 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1441 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1443 return parseDirectiveOrg();
1445 return parseDirectiveFill();
1447 return parseDirectiveZero();
1449 eatToEndOfStatement(); // .extern is the default, ignore it.
1453 return parseDirectiveSymbolAttribute(MCSA_Global);
1454 case DK_LAZY_REFERENCE:
1455 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1456 case DK_NO_DEAD_STRIP:
1457 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1458 case DK_SYMBOL_RESOLVER:
1459 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1460 case DK_PRIVATE_EXTERN:
1461 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1463 return parseDirectiveSymbolAttribute(MCSA_Reference);
1464 case DK_WEAK_DEFINITION:
1465 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1466 case DK_WEAK_REFERENCE:
1467 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1468 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1469 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1472 return parseDirectiveComm(/*IsLocal=*/false);
1474 return parseDirectiveComm(/*IsLocal=*/true);
1476 return parseDirectiveAbort();
1478 return parseDirectiveInclude();
1480 return parseDirectiveIncbin();
1483 return TokError(Twine(IDVal) + " not supported yet");
1485 return parseDirectiveRept(IDLoc, IDVal);
1487 return parseDirectiveIrp(IDLoc);
1489 return parseDirectiveIrpc(IDLoc);
1491 return parseDirectiveEndr(IDLoc);
1492 case DK_BUNDLE_ALIGN_MODE:
1493 return parseDirectiveBundleAlignMode();
1494 case DK_BUNDLE_LOCK:
1495 return parseDirectiveBundleLock();
1496 case DK_BUNDLE_UNLOCK:
1497 return parseDirectiveBundleUnlock();
1499 return parseDirectiveLEB128(true);
1501 return parseDirectiveLEB128(false);
1504 return parseDirectiveSpace(IDVal);
1506 return parseDirectiveFile(IDLoc);
1508 return parseDirectiveLine();
1510 return parseDirectiveLoc();
1512 return parseDirectiveStabs();
1513 case DK_CFI_SECTIONS:
1514 return parseDirectiveCFISections();
1515 case DK_CFI_STARTPROC:
1516 return parseDirectiveCFIStartProc();
1517 case DK_CFI_ENDPROC:
1518 return parseDirectiveCFIEndProc();
1519 case DK_CFI_DEF_CFA:
1520 return parseDirectiveCFIDefCfa(IDLoc);
1521 case DK_CFI_DEF_CFA_OFFSET:
1522 return parseDirectiveCFIDefCfaOffset();
1523 case DK_CFI_ADJUST_CFA_OFFSET:
1524 return parseDirectiveCFIAdjustCfaOffset();
1525 case DK_CFI_DEF_CFA_REGISTER:
1526 return parseDirectiveCFIDefCfaRegister(IDLoc);
1528 return parseDirectiveCFIOffset(IDLoc);
1529 case DK_CFI_REL_OFFSET:
1530 return parseDirectiveCFIRelOffset(IDLoc);
1531 case DK_CFI_PERSONALITY:
1532 return parseDirectiveCFIPersonalityOrLsda(true);
1534 return parseDirectiveCFIPersonalityOrLsda(false);
1535 case DK_CFI_REMEMBER_STATE:
1536 return parseDirectiveCFIRememberState();
1537 case DK_CFI_RESTORE_STATE:
1538 return parseDirectiveCFIRestoreState();
1539 case DK_CFI_SAME_VALUE:
1540 return parseDirectiveCFISameValue(IDLoc);
1541 case DK_CFI_RESTORE:
1542 return parseDirectiveCFIRestore(IDLoc);
1544 return parseDirectiveCFIEscape();
1545 case DK_CFI_SIGNAL_FRAME:
1546 return parseDirectiveCFISignalFrame();
1547 case DK_CFI_UNDEFINED:
1548 return parseDirectiveCFIUndefined(IDLoc);
1549 case DK_CFI_REGISTER:
1550 return parseDirectiveCFIRegister(IDLoc);
1551 case DK_CFI_WINDOW_SAVE:
1552 return parseDirectiveCFIWindowSave();
1555 return parseDirectiveMacrosOnOff(IDVal);
1557 return parseDirectiveMacro(IDLoc);
1559 return parseDirectiveExitMacro(IDVal);
1562 return parseDirectiveEndMacro(IDVal);
1564 return parseDirectivePurgeMacro(IDLoc);
1566 return parseDirectiveEnd(IDLoc);
1568 return parseDirectiveError(IDLoc, false);
1570 return parseDirectiveError(IDLoc, true);
1572 return parseDirectiveWarning(IDLoc);
1575 return Error(IDLoc, "unknown directive");
1578 // __asm _emit or __asm __emit
1579 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1580 IDVal == "_EMIT" || IDVal == "__EMIT"))
1581 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1584 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1585 return parseDirectiveMSAlign(IDLoc, Info);
1587 checkForValidSection();
1589 // Canonicalize the opcode to lower case.
1590 std::string OpcodeStr = IDVal.lower();
1591 ParseInstructionInfo IInfo(Info.AsmRewrites);
1592 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1593 Info.ParsedOperands);
1594 Info.ParseError = HadError;
1596 // Dump the parsed representation, if requested.
1597 if (getShowParsedOperands()) {
1598 SmallString<256> Str;
1599 raw_svector_ostream OS(Str);
1600 OS << "parsed instruction: [";
1601 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1604 Info.ParsedOperands[i]->print(OS);
1608 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1611 // If we are generating dwarf for the current section then generate a .loc
1612 // directive for the instruction.
1613 if (!HadError && getContext().getGenDwarfForAssembly() &&
1614 getContext().getGenDwarfSectionSyms().count(
1615 getStreamer().getCurrentSection().first)) {
1617 if (ActiveMacros.empty())
1618 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1620 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1621 ActiveMacros.back()->ExitBuffer);
1623 // If we previously parsed a cpp hash file line comment then make sure the
1624 // current Dwarf File is for the CppHashFilename if not then emit the
1625 // Dwarf File table for it and adjust the line number for the .loc.
1626 if (CppHashFilename.size()) {
1627 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1628 0, StringRef(), CppHashFilename);
1629 getContext().setGenDwarfFileNumber(FileNumber);
1631 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1632 // cache with the different Loc from the call above we save the last
1633 // info we queried here with SrcMgr.FindLineNumber().
1634 unsigned CppHashLocLineNo;
1635 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1636 CppHashLocLineNo = LastQueryLine;
1638 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1639 LastQueryLine = CppHashLocLineNo;
1640 LastQueryIDLoc = CppHashLoc;
1641 LastQueryBuffer = CppHashBuf;
1643 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1646 getStreamer().EmitDwarfLocDirective(
1647 getContext().getGenDwarfFileNumber(), Line, 0,
1648 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1652 // If parsing succeeded, match the instruction.
1655 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1656 Info.ParsedOperands, Out,
1657 ErrorInfo, ParsingInlineAsm);
1660 // Don't skip the rest of the line, the instruction parser is responsible for
1665 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1666 /// since they may not be able to be tokenized to get to the end of line token.
1667 void AsmParser::eatToEndOfLine() {
1668 if (!Lexer.is(AsmToken::EndOfStatement))
1669 Lexer.LexUntilEndOfLine();
1674 /// parseCppHashLineFilenameComment as this:
1675 /// ::= # number "filename"
1676 /// or just as a full line comment if it doesn't have a number and a string.
1677 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1678 Lex(); // Eat the hash token.
1680 if (getLexer().isNot(AsmToken::Integer)) {
1681 // Consume the line since in cases it is not a well-formed line directive,
1682 // as if were simply a full line comment.
1687 int64_t LineNumber = getTok().getIntVal();
1690 if (getLexer().isNot(AsmToken::String)) {
1695 StringRef Filename = getTok().getString();
1696 // Get rid of the enclosing quotes.
1697 Filename = Filename.substr(1, Filename.size() - 2);
1699 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1701 CppHashFilename = Filename;
1702 CppHashLineNumber = LineNumber;
1703 CppHashBuf = CurBuffer;
1705 // Ignore any trailing characters, they're just comment.
1710 /// \brief will use the last parsed cpp hash line filename comment
1711 /// for the Filename and LineNo if any in the diagnostic.
1712 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1713 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1714 raw_ostream &OS = errs();
1716 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1717 const SMLoc &DiagLoc = Diag.getLoc();
1718 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1719 unsigned CppHashBuf =
1720 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1722 // Like SourceMgr::printMessage() we need to print the include stack if any
1723 // before printing the message.
1724 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1725 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1726 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1727 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1728 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1731 // If we have not parsed a cpp hash line filename comment or the source
1732 // manager changed or buffer changed (like in a nested include) then just
1733 // print the normal diagnostic using its Filename and LineNo.
1734 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1735 DiagBuf != CppHashBuf) {
1736 if (Parser->SavedDiagHandler)
1737 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1739 Diag.print(nullptr, OS);
1743 // Use the CppHashFilename and calculate a line number based on the
1744 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1746 const std::string &Filename = Parser->CppHashFilename;
1748 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1749 int CppHashLocLineNo =
1750 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1752 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1754 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1755 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1756 Diag.getLineContents(), Diag.getRanges());
1758 if (Parser->SavedDiagHandler)
1759 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1761 NewDiag.print(nullptr, OS);
1764 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1765 // difference being that that function accepts '@' as part of identifiers and
1766 // we can't do that. AsmLexer.cpp should probably be changed to handle
1767 // '@' as a special case when needed.
1768 static bool isIdentifierChar(char c) {
1769 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1773 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1774 ArrayRef<MCAsmMacroParameter> Parameters,
1775 ArrayRef<MCAsmMacroArgument> A,
1776 bool EnableAtPseudoVariable, const SMLoc &L) {
1777 unsigned NParameters = Parameters.size();
1778 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1779 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1780 return Error(L, "Wrong number of arguments");
1782 // A macro without parameters is handled differently on Darwin:
1783 // gas accepts no arguments and does no substitutions
1784 while (!Body.empty()) {
1785 // Scan for the next substitution.
1786 std::size_t End = Body.size(), Pos = 0;
1787 for (; Pos != End; ++Pos) {
1788 // Check for a substitution or escape.
1789 if (IsDarwin && !NParameters) {
1790 // This macro has no parameters, look for $0, $1, etc.
1791 if (Body[Pos] != '$' || Pos + 1 == End)
1794 char Next = Body[Pos + 1];
1795 if (Next == '$' || Next == 'n' ||
1796 isdigit(static_cast<unsigned char>(Next)))
1799 // This macro has parameters, look for \foo, \bar, etc.
1800 if (Body[Pos] == '\\' && Pos + 1 != End)
1806 OS << Body.slice(0, Pos);
1808 // Check if we reached the end.
1812 if (IsDarwin && !NParameters) {
1813 switch (Body[Pos + 1]) {
1819 // $n => number of arguments
1824 // $[0-9] => argument
1826 // Missing arguments are ignored.
1827 unsigned Index = Body[Pos + 1] - '0';
1828 if (Index >= A.size())
1831 // Otherwise substitute with the token values, with spaces eliminated.
1832 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1833 ie = A[Index].end();
1835 OS << it->getString();
1841 unsigned I = Pos + 1;
1843 // Check for the \@ pseudo-variable.
1844 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1847 while (isIdentifierChar(Body[I]) && I + 1 != End)
1850 const char *Begin = Body.data() + Pos + 1;
1851 StringRef Argument(Begin, I - (Pos + 1));
1854 if (Argument == "@") {
1855 OS << NumOfMacroInstantiations;
1858 for (; Index < NParameters; ++Index)
1859 if (Parameters[Index].Name == Argument)
1862 if (Index == NParameters) {
1863 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1866 OS << '\\' << Argument;
1870 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1871 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1872 ie = A[Index].end();
1874 // We expect no quotes around the string's contents when
1875 // parsing for varargs.
1876 if (it->getKind() != AsmToken::String || VarargParameter)
1877 OS << it->getString();
1879 OS << it->getStringContents();
1881 Pos += 1 + Argument.size();
1885 // Update the scan point.
1886 Body = Body.substr(Pos);
1892 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1893 size_t CondStackDepth)
1894 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1895 CondStackDepth(CondStackDepth) {}
1897 static bool isOperator(AsmToken::TokenKind kind) {
1901 case AsmToken::Plus:
1902 case AsmToken::Minus:
1903 case AsmToken::Tilde:
1904 case AsmToken::Slash:
1905 case AsmToken::Star:
1907 case AsmToken::Equal:
1908 case AsmToken::EqualEqual:
1909 case AsmToken::Pipe:
1910 case AsmToken::PipePipe:
1911 case AsmToken::Caret:
1913 case AsmToken::AmpAmp:
1914 case AsmToken::Exclaim:
1915 case AsmToken::ExclaimEqual:
1916 case AsmToken::Percent:
1917 case AsmToken::Less:
1918 case AsmToken::LessEqual:
1919 case AsmToken::LessLess:
1920 case AsmToken::LessGreater:
1921 case AsmToken::Greater:
1922 case AsmToken::GreaterEqual:
1923 case AsmToken::GreaterGreater:
1929 class AsmLexerSkipSpaceRAII {
1931 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1932 Lexer.setSkipSpace(SkipSpace);
1935 ~AsmLexerSkipSpaceRAII() {
1936 Lexer.setSkipSpace(true);
1944 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1947 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1948 StringRef Str = parseStringToEndOfStatement();
1949 MA.push_back(AsmToken(AsmToken::String, Str));
1954 unsigned ParenLevel = 0;
1955 unsigned AddTokens = 0;
1957 // Darwin doesn't use spaces to delmit arguments.
1958 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1961 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1962 return TokError("unexpected token in macro instantiation");
1964 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1967 if (Lexer.is(AsmToken::Space)) {
1968 Lex(); // Eat spaces
1970 // Spaces can delimit parameters, but could also be part an expression.
1971 // If the token after a space is an operator, add the token and the next
1972 // one into this argument
1974 if (isOperator(Lexer.getKind())) {
1975 // Check to see whether the token is used as an operator,
1976 // or part of an identifier
1977 const char *NextChar = getTok().getEndLoc().getPointer();
1978 if (*NextChar == ' ')
1982 if (!AddTokens && ParenLevel == 0) {
1988 // handleMacroEntry relies on not advancing the lexer here
1989 // to be able to fill in the remaining default parameter values
1990 if (Lexer.is(AsmToken::EndOfStatement))
1993 // Adjust the current parentheses level.
1994 if (Lexer.is(AsmToken::LParen))
1996 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1999 // Append the token to the current argument list.
2000 MA.push_back(getTok());
2006 if (ParenLevel != 0)
2007 return TokError("unbalanced parentheses in macro argument");
2011 // Parse the macro instantiation arguments.
2012 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2013 MCAsmMacroArguments &A) {
2014 const unsigned NParameters = M ? M->Parameters.size() : 0;
2015 bool NamedParametersFound = false;
2016 SmallVector<SMLoc, 4> FALocs;
2018 A.resize(NParameters);
2019 FALocs.resize(NParameters);
2021 // Parse two kinds of macro invocations:
2022 // - macros defined without any parameters accept an arbitrary number of them
2023 // - macros defined with parameters accept at most that many of them
2024 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2025 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2027 SMLoc IDLoc = Lexer.getLoc();
2028 MCAsmMacroParameter FA;
2030 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2031 if (parseIdentifier(FA.Name)) {
2032 Error(IDLoc, "invalid argument identifier for formal argument");
2033 eatToEndOfStatement();
2037 if (!Lexer.is(AsmToken::Equal)) {
2038 TokError("expected '=' after formal parameter identifier");
2039 eatToEndOfStatement();
2044 NamedParametersFound = true;
2047 if (NamedParametersFound && FA.Name.empty()) {
2048 Error(IDLoc, "cannot mix positional and keyword arguments");
2049 eatToEndOfStatement();
2053 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2054 if (parseMacroArgument(FA.Value, Vararg))
2057 unsigned PI = Parameter;
2058 if (!FA.Name.empty()) {
2060 for (FAI = 0; FAI < NParameters; ++FAI)
2061 if (M->Parameters[FAI].Name == FA.Name)
2064 if (FAI >= NParameters) {
2065 assert(M && "expected macro to be defined");
2067 "parameter named '" + FA.Name + "' does not exist for macro '" +
2074 if (!FA.Value.empty()) {
2079 if (FALocs.size() <= PI)
2080 FALocs.resize(PI + 1);
2082 FALocs[PI] = Lexer.getLoc();
2085 // At the end of the statement, fill in remaining arguments that have
2086 // default values. If there aren't any, then the next argument is
2087 // required but missing
2088 if (Lexer.is(AsmToken::EndOfStatement)) {
2089 bool Failure = false;
2090 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2091 if (A[FAI].empty()) {
2092 if (M->Parameters[FAI].Required) {
2093 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2094 "missing value for required parameter "
2095 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2099 if (!M->Parameters[FAI].Value.empty())
2100 A[FAI] = M->Parameters[FAI].Value;
2106 if (Lexer.is(AsmToken::Comma))
2110 return TokError("too many positional arguments");
2113 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2114 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2115 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2118 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2119 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2122 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2124 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2125 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2126 // this, although we should protect against infinite loops.
2127 if (ActiveMacros.size() == 20)
2128 return TokError("macros cannot be nested more than 20 levels deep");
2130 MCAsmMacroArguments A;
2131 if (parseMacroArguments(M, A))
2134 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2135 // to hold the macro body with substitutions.
2136 SmallString<256> Buf;
2137 StringRef Body = M->Body;
2138 raw_svector_ostream OS(Buf);
2140 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2143 // We include the .endmacro in the buffer as our cue to exit the macro
2145 OS << ".endmacro\n";
2147 std::unique_ptr<MemoryBuffer> Instantiation =
2148 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2150 // Create the macro instantiation object and add to the current macro
2151 // instantiation stack.
2152 MacroInstantiation *MI = new MacroInstantiation(
2153 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2154 ActiveMacros.push_back(MI);
2156 ++NumOfMacroInstantiations;
2158 // Jump to the macro instantiation and prime the lexer.
2159 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2160 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2166 void AsmParser::handleMacroExit() {
2167 // Jump to the EndOfStatement we should return to, and consume it.
2168 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2171 // Pop the instantiation entry.
2172 delete ActiveMacros.back();
2173 ActiveMacros.pop_back();
2176 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2177 switch (Value->getKind()) {
2178 case MCExpr::Binary: {
2179 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2180 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2182 case MCExpr::Target:
2183 case MCExpr::Constant:
2185 case MCExpr::SymbolRef: {
2187 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2189 return isUsedIn(Sym, S.getVariableValue());
2193 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2196 llvm_unreachable("Unknown expr kind!");
2199 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2201 // FIXME: Use better location, we should use proper tokens.
2202 SMLoc EqualLoc = Lexer.getLoc();
2204 const MCExpr *Value;
2205 if (parseExpression(Value))
2208 // Note: we don't count b as used in "a = b". This is to allow
2212 if (Lexer.isNot(AsmToken::EndOfStatement))
2213 return TokError("unexpected token in assignment");
2215 // Eat the end of statement marker.
2218 // Validate that the LHS is allowed to be a variable (either it has not been
2219 // used as a symbol, or it is an absolute symbol).
2220 MCSymbol *Sym = getContext().lookupSymbol(Name);
2222 // Diagnose assignment to a label.
2224 // FIXME: Diagnostics. Note the location of the definition as a label.
2225 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2226 if (isUsedIn(Sym, Value))
2227 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2228 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2229 ; // Allow redefinitions of undefined symbols only used in directives.
2230 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2231 ; // Allow redefinitions of variables that haven't yet been used.
2232 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2233 return Error(EqualLoc, "redefinition of '" + Name + "'");
2234 else if (!Sym->isVariable())
2235 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2236 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2237 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2240 // Don't count these checks as uses.
2241 Sym->setUsed(false);
2242 } else if (Name == ".") {
2243 if (Out.EmitValueToOffset(Value, 0)) {
2244 Error(EqualLoc, "expected absolute expression");
2245 eatToEndOfStatement();
2249 Sym = getContext().getOrCreateSymbol(Name);
2251 Sym->setRedefinable(allow_redef);
2253 // Do the assignment.
2254 Out.EmitAssignment(Sym, Value);
2256 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2261 /// parseIdentifier:
2264 bool AsmParser::parseIdentifier(StringRef &Res) {
2265 // The assembler has relaxed rules for accepting identifiers, in particular we
2266 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2267 // separate tokens. At this level, we have already lexed so we cannot (currently)
2268 // handle this as a context dependent token, instead we detect adjacent tokens
2269 // and return the combined identifier.
2270 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2271 SMLoc PrefixLoc = getLexer().getLoc();
2273 // Consume the prefix character, and check for a following identifier.
2275 if (Lexer.isNot(AsmToken::Identifier))
2278 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2279 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2282 // Construct the joined identifier and consume the token.
2284 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2289 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2292 Res = getTok().getIdentifier();
2294 Lex(); // Consume the identifier token.
2299 /// parseDirectiveSet:
2300 /// ::= .equ identifier ',' expression
2301 /// ::= .equiv identifier ',' expression
2302 /// ::= .set identifier ',' expression
2303 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2306 if (parseIdentifier(Name))
2307 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2309 if (getLexer().isNot(AsmToken::Comma))
2310 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2313 return parseAssignment(Name, allow_redef, true);
2316 bool AsmParser::parseEscapedString(std::string &Data) {
2317 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2320 StringRef Str = getTok().getStringContents();
2321 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2322 if (Str[i] != '\\') {
2327 // Recognize escaped characters. Note that this escape semantics currently
2328 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2331 return TokError("unexpected backslash at end of string");
2333 // Recognize octal sequences.
2334 if ((unsigned)(Str[i] - '0') <= 7) {
2335 // Consume up to three octal characters.
2336 unsigned Value = Str[i] - '0';
2338 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2340 Value = Value * 8 + (Str[i] - '0');
2342 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2344 Value = Value * 8 + (Str[i] - '0');
2349 return TokError("invalid octal escape sequence (out of range)");
2351 Data += (unsigned char)Value;
2355 // Otherwise recognize individual escapes.
2358 // Just reject invalid escape sequences for now.
2359 return TokError("invalid escape sequence (unrecognized character)");
2361 case 'b': Data += '\b'; break;
2362 case 'f': Data += '\f'; break;
2363 case 'n': Data += '\n'; break;
2364 case 'r': Data += '\r'; break;
2365 case 't': Data += '\t'; break;
2366 case '"': Data += '"'; break;
2367 case '\\': Data += '\\'; break;
2374 /// parseDirectiveAscii:
2375 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2376 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2377 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2378 checkForValidSection();
2381 if (getLexer().isNot(AsmToken::String))
2382 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2385 if (parseEscapedString(Data))
2388 getStreamer().EmitBytes(Data);
2390 getStreamer().EmitBytes(StringRef("\0", 1));
2394 if (getLexer().is(AsmToken::EndOfStatement))
2397 if (getLexer().isNot(AsmToken::Comma))
2398 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2407 /// parseDirectiveValue
2408 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2409 bool AsmParser::parseDirectiveValue(unsigned Size) {
2410 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2411 checkForValidSection();
2414 const MCExpr *Value;
2415 SMLoc ExprLoc = getLexer().getLoc();
2416 if (parseExpression(Value))
2419 // Special case constant expressions to match code generator.
2420 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2421 assert(Size <= 8 && "Invalid size");
2422 uint64_t IntValue = MCE->getValue();
2423 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2424 return Error(ExprLoc, "literal value out of range for directive");
2425 getStreamer().EmitIntValue(IntValue, Size);
2427 getStreamer().EmitValue(Value, Size, ExprLoc);
2429 if (getLexer().is(AsmToken::EndOfStatement))
2432 // FIXME: Improve diagnostic.
2433 if (getLexer().isNot(AsmToken::Comma))
2434 return TokError("unexpected token in directive");
2443 /// ParseDirectiveOctaValue
2444 /// ::= .octa [ hexconstant (, hexconstant)* ]
2445 bool AsmParser::parseDirectiveOctaValue() {
2446 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2447 checkForValidSection();
2450 if (Lexer.getKind() == AsmToken::Error)
2452 if (Lexer.getKind() != AsmToken::Integer &&
2453 Lexer.getKind() != AsmToken::BigNum)
2454 return TokError("unknown token in expression");
2456 SMLoc ExprLoc = getLexer().getLoc();
2457 APInt IntValue = getTok().getAPIntVal();
2461 if (IntValue.isIntN(64)) {
2463 lo = IntValue.getZExtValue();
2464 } else if (IntValue.isIntN(128)) {
2465 // It might actually have more than 128 bits, but the top ones are zero.
2466 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2467 lo = IntValue.getLoBits(64).getZExtValue();
2469 return Error(ExprLoc, "literal value out of range for directive");
2471 if (MAI.isLittleEndian()) {
2472 getStreamer().EmitIntValue(lo, 8);
2473 getStreamer().EmitIntValue(hi, 8);
2475 getStreamer().EmitIntValue(hi, 8);
2476 getStreamer().EmitIntValue(lo, 8);
2479 if (getLexer().is(AsmToken::EndOfStatement))
2482 // FIXME: Improve diagnostic.
2483 if (getLexer().isNot(AsmToken::Comma))
2484 return TokError("unexpected token in directive");
2493 /// parseDirectiveRealValue
2494 /// ::= (.single | .double) [ expression (, expression)* ]
2495 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2496 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2497 checkForValidSection();
2500 // We don't truly support arithmetic on floating point expressions, so we
2501 // have to manually parse unary prefixes.
2503 if (getLexer().is(AsmToken::Minus)) {
2506 } else if (getLexer().is(AsmToken::Plus))
2509 if (getLexer().isNot(AsmToken::Integer) &&
2510 getLexer().isNot(AsmToken::Real) &&
2511 getLexer().isNot(AsmToken::Identifier))
2512 return TokError("unexpected token in directive");
2514 // Convert to an APFloat.
2515 APFloat Value(Semantics);
2516 StringRef IDVal = getTok().getString();
2517 if (getLexer().is(AsmToken::Identifier)) {
2518 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2519 Value = APFloat::getInf(Semantics);
2520 else if (!IDVal.compare_lower("nan"))
2521 Value = APFloat::getNaN(Semantics, false, ~0);
2523 return TokError("invalid floating point literal");
2524 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2525 APFloat::opInvalidOp)
2526 return TokError("invalid floating point literal");
2530 // Consume the numeric token.
2533 // Emit the value as an integer.
2534 APInt AsInt = Value.bitcastToAPInt();
2535 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2536 AsInt.getBitWidth() / 8);
2538 if (getLexer().is(AsmToken::EndOfStatement))
2541 if (getLexer().isNot(AsmToken::Comma))
2542 return TokError("unexpected token in directive");
2551 /// parseDirectiveZero
2552 /// ::= .zero expression
2553 bool AsmParser::parseDirectiveZero() {
2554 checkForValidSection();
2557 if (parseAbsoluteExpression(NumBytes))
2561 if (getLexer().is(AsmToken::Comma)) {
2563 if (parseAbsoluteExpression(Val))
2567 if (getLexer().isNot(AsmToken::EndOfStatement))
2568 return TokError("unexpected token in '.zero' directive");
2572 getStreamer().EmitFill(NumBytes, Val);
2577 /// parseDirectiveFill
2578 /// ::= .fill expression [ , expression [ , expression ] ]
2579 bool AsmParser::parseDirectiveFill() {
2580 checkForValidSection();
2582 SMLoc RepeatLoc = getLexer().getLoc();
2584 if (parseAbsoluteExpression(NumValues))
2587 if (NumValues < 0) {
2589 "'.fill' directive with negative repeat count has no effect");
2593 int64_t FillSize = 1;
2594 int64_t FillExpr = 0;
2596 SMLoc SizeLoc, ExprLoc;
2597 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2598 if (getLexer().isNot(AsmToken::Comma))
2599 return TokError("unexpected token in '.fill' directive");
2602 SizeLoc = getLexer().getLoc();
2603 if (parseAbsoluteExpression(FillSize))
2606 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2607 if (getLexer().isNot(AsmToken::Comma))
2608 return TokError("unexpected token in '.fill' directive");
2611 ExprLoc = getLexer().getLoc();
2612 if (parseAbsoluteExpression(FillExpr))
2615 if (getLexer().isNot(AsmToken::EndOfStatement))
2616 return TokError("unexpected token in '.fill' directive");
2623 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2627 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2631 if (!isUInt<32>(FillExpr) && FillSize > 4)
2632 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2634 if (NumValues > 0) {
2635 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2636 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2637 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2638 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2639 if (NonZeroFillSize < FillSize)
2640 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2647 /// parseDirectiveOrg
2648 /// ::= .org expression [ , expression ]
2649 bool AsmParser::parseDirectiveOrg() {
2650 checkForValidSection();
2652 const MCExpr *Offset;
2653 SMLoc Loc = getTok().getLoc();
2654 if (parseExpression(Offset))
2657 // Parse optional fill expression.
2658 int64_t FillExpr = 0;
2659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2660 if (getLexer().isNot(AsmToken::Comma))
2661 return TokError("unexpected token in '.org' directive");
2664 if (parseAbsoluteExpression(FillExpr))
2667 if (getLexer().isNot(AsmToken::EndOfStatement))
2668 return TokError("unexpected token in '.org' directive");
2673 // Only limited forms of relocatable expressions are accepted here, it
2674 // has to be relative to the current section. The streamer will return
2675 // 'true' if the expression wasn't evaluatable.
2676 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2677 return Error(Loc, "expected assembly-time absolute expression");
2682 /// parseDirectiveAlign
2683 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2684 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2685 checkForValidSection();
2687 SMLoc AlignmentLoc = getLexer().getLoc();
2689 if (parseAbsoluteExpression(Alignment))
2693 bool HasFillExpr = false;
2694 int64_t FillExpr = 0;
2695 int64_t MaxBytesToFill = 0;
2696 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2697 if (getLexer().isNot(AsmToken::Comma))
2698 return TokError("unexpected token in directive");
2701 // The fill expression can be omitted while specifying a maximum number of
2702 // alignment bytes, e.g:
2704 if (getLexer().isNot(AsmToken::Comma)) {
2706 if (parseAbsoluteExpression(FillExpr))
2710 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2711 if (getLexer().isNot(AsmToken::Comma))
2712 return TokError("unexpected token in directive");
2715 MaxBytesLoc = getLexer().getLoc();
2716 if (parseAbsoluteExpression(MaxBytesToFill))
2719 if (getLexer().isNot(AsmToken::EndOfStatement))
2720 return TokError("unexpected token in directive");
2729 // Compute alignment in bytes.
2731 // FIXME: Diagnose overflow.
2732 if (Alignment >= 32) {
2733 Error(AlignmentLoc, "invalid alignment value");
2737 Alignment = 1ULL << Alignment;
2739 // Reject alignments that aren't a power of two, for gas compatibility.
2740 if (!isPowerOf2_64(Alignment))
2741 Error(AlignmentLoc, "alignment must be a power of 2");
2744 // Diagnose non-sensical max bytes to align.
2745 if (MaxBytesLoc.isValid()) {
2746 if (MaxBytesToFill < 1) {
2747 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2748 "many bytes, ignoring maximum bytes expression");
2752 if (MaxBytesToFill >= Alignment) {
2753 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2759 // Check whether we should use optimal code alignment for this .align
2761 const MCSection *Section = getStreamer().getCurrentSection().first;
2762 assert(Section && "must have section to emit alignment");
2763 bool UseCodeAlign = Section->UseCodeAlign();
2764 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2765 ValueSize == 1 && UseCodeAlign) {
2766 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2768 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2769 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2776 /// parseDirectiveFile
2777 /// ::= .file [number] filename
2778 /// ::= .file number directory filename
2779 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2780 // FIXME: I'm not sure what this is.
2781 int64_t FileNumber = -1;
2782 SMLoc FileNumberLoc = getLexer().getLoc();
2783 if (getLexer().is(AsmToken::Integer)) {
2784 FileNumber = getTok().getIntVal();
2788 return TokError("file number less than one");
2791 if (getLexer().isNot(AsmToken::String))
2792 return TokError("unexpected token in '.file' directive");
2794 // Usually the directory and filename together, otherwise just the directory.
2795 // Allow the strings to have escaped octal character sequence.
2796 std::string Path = getTok().getString();
2797 if (parseEscapedString(Path))
2801 StringRef Directory;
2803 std::string FilenameData;
2804 if (getLexer().is(AsmToken::String)) {
2805 if (FileNumber == -1)
2806 return TokError("explicit path specified, but no file number");
2807 if (parseEscapedString(FilenameData))
2809 Filename = FilenameData;
2816 if (getLexer().isNot(AsmToken::EndOfStatement))
2817 return TokError("unexpected token in '.file' directive");
2819 if (FileNumber == -1)
2820 getStreamer().EmitFileDirective(Filename);
2822 if (getContext().getGenDwarfForAssembly())
2824 "input can't have .file dwarf directives when -g is "
2825 "used to generate dwarf debug info for assembly code");
2827 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2829 Error(FileNumberLoc, "file number already allocated");
2835 /// parseDirectiveLine
2836 /// ::= .line [number]
2837 bool AsmParser::parseDirectiveLine() {
2838 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2839 if (getLexer().isNot(AsmToken::Integer))
2840 return TokError("unexpected token in '.line' directive");
2842 int64_t LineNumber = getTok().getIntVal();
2846 // FIXME: Do something with the .line.
2849 if (getLexer().isNot(AsmToken::EndOfStatement))
2850 return TokError("unexpected token in '.line' directive");
2855 /// parseDirectiveLoc
2856 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2857 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2858 /// The first number is a file number, must have been previously assigned with
2859 /// a .file directive, the second number is the line number and optionally the
2860 /// third number is a column position (zero if not specified). The remaining
2861 /// optional items are .loc sub-directives.
2862 bool AsmParser::parseDirectiveLoc() {
2863 if (getLexer().isNot(AsmToken::Integer))
2864 return TokError("unexpected token in '.loc' directive");
2865 int64_t FileNumber = getTok().getIntVal();
2867 return TokError("file number less than one in '.loc' directive");
2868 if (!getContext().isValidDwarfFileNumber(FileNumber))
2869 return TokError("unassigned file number in '.loc' directive");
2872 int64_t LineNumber = 0;
2873 if (getLexer().is(AsmToken::Integer)) {
2874 LineNumber = getTok().getIntVal();
2876 return TokError("line number less than zero in '.loc' directive");
2880 int64_t ColumnPos = 0;
2881 if (getLexer().is(AsmToken::Integer)) {
2882 ColumnPos = getTok().getIntVal();
2884 return TokError("column position less than zero in '.loc' directive");
2888 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2890 int64_t Discriminator = 0;
2891 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2893 if (getLexer().is(AsmToken::EndOfStatement))
2897 SMLoc Loc = getTok().getLoc();
2898 if (parseIdentifier(Name))
2899 return TokError("unexpected token in '.loc' directive");
2901 if (Name == "basic_block")
2902 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2903 else if (Name == "prologue_end")
2904 Flags |= DWARF2_FLAG_PROLOGUE_END;
2905 else if (Name == "epilogue_begin")
2906 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2907 else if (Name == "is_stmt") {
2908 Loc = getTok().getLoc();
2909 const MCExpr *Value;
2910 if (parseExpression(Value))
2912 // The expression must be the constant 0 or 1.
2913 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2914 int Value = MCE->getValue();
2916 Flags &= ~DWARF2_FLAG_IS_STMT;
2917 else if (Value == 1)
2918 Flags |= DWARF2_FLAG_IS_STMT;
2920 return Error(Loc, "is_stmt value not 0 or 1");
2922 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2924 } else if (Name == "isa") {
2925 Loc = getTok().getLoc();
2926 const MCExpr *Value;
2927 if (parseExpression(Value))
2929 // The expression must be a constant greater or equal to 0.
2930 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2931 int Value = MCE->getValue();
2933 return Error(Loc, "isa number less than zero");
2936 return Error(Loc, "isa number not a constant value");
2938 } else if (Name == "discriminator") {
2939 if (parseAbsoluteExpression(Discriminator))
2942 return Error(Loc, "unknown sub-directive in '.loc' directive");
2945 if (getLexer().is(AsmToken::EndOfStatement))
2950 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2951 Isa, Discriminator, StringRef());
2956 /// parseDirectiveStabs
2957 /// ::= .stabs string, number, number, number
2958 bool AsmParser::parseDirectiveStabs() {
2959 return TokError("unsupported directive '.stabs'");
2962 /// parseDirectiveCFISections
2963 /// ::= .cfi_sections section [, section]
2964 bool AsmParser::parseDirectiveCFISections() {
2969 if (parseIdentifier(Name))
2970 return TokError("Expected an identifier");
2972 if (Name == ".eh_frame")
2974 else if (Name == ".debug_frame")
2977 if (getLexer().is(AsmToken::Comma)) {
2980 if (parseIdentifier(Name))
2981 return TokError("Expected an identifier");
2983 if (Name == ".eh_frame")
2985 else if (Name == ".debug_frame")
2989 getStreamer().EmitCFISections(EH, Debug);
2993 /// parseDirectiveCFIStartProc
2994 /// ::= .cfi_startproc [simple]
2995 bool AsmParser::parseDirectiveCFIStartProc() {
2997 if (getLexer().isNot(AsmToken::EndOfStatement))
2998 if (parseIdentifier(Simple) || Simple != "simple")
2999 return TokError("unexpected token in .cfi_startproc directive");
3001 getStreamer().EmitCFIStartProc(!Simple.empty());
3005 /// parseDirectiveCFIEndProc
3006 /// ::= .cfi_endproc
3007 bool AsmParser::parseDirectiveCFIEndProc() {
3008 getStreamer().EmitCFIEndProc();
3012 /// \brief parse register name or number.
3013 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3014 SMLoc DirectiveLoc) {
3017 if (getLexer().isNot(AsmToken::Integer)) {
3018 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3020 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3022 return parseAbsoluteExpression(Register);
3027 /// parseDirectiveCFIDefCfa
3028 /// ::= .cfi_def_cfa register, offset
3029 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3030 int64_t Register = 0;
3031 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3034 if (getLexer().isNot(AsmToken::Comma))
3035 return TokError("unexpected token in directive");
3039 if (parseAbsoluteExpression(Offset))
3042 getStreamer().EmitCFIDefCfa(Register, Offset);
3046 /// parseDirectiveCFIDefCfaOffset
3047 /// ::= .cfi_def_cfa_offset offset
3048 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3050 if (parseAbsoluteExpression(Offset))
3053 getStreamer().EmitCFIDefCfaOffset(Offset);
3057 /// parseDirectiveCFIRegister
3058 /// ::= .cfi_register register, register
3059 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3060 int64_t Register1 = 0;
3061 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3064 if (getLexer().isNot(AsmToken::Comma))
3065 return TokError("unexpected token in directive");
3068 int64_t Register2 = 0;
3069 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3072 getStreamer().EmitCFIRegister(Register1, Register2);
3076 /// parseDirectiveCFIWindowSave
3077 /// ::= .cfi_window_save
3078 bool AsmParser::parseDirectiveCFIWindowSave() {
3079 getStreamer().EmitCFIWindowSave();
3083 /// parseDirectiveCFIAdjustCfaOffset
3084 /// ::= .cfi_adjust_cfa_offset adjustment
3085 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3086 int64_t Adjustment = 0;
3087 if (parseAbsoluteExpression(Adjustment))
3090 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3094 /// parseDirectiveCFIDefCfaRegister
3095 /// ::= .cfi_def_cfa_register register
3096 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3097 int64_t Register = 0;
3098 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3101 getStreamer().EmitCFIDefCfaRegister(Register);
3105 /// parseDirectiveCFIOffset
3106 /// ::= .cfi_offset register, offset
3107 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3108 int64_t Register = 0;
3111 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3114 if (getLexer().isNot(AsmToken::Comma))
3115 return TokError("unexpected token in directive");
3118 if (parseAbsoluteExpression(Offset))
3121 getStreamer().EmitCFIOffset(Register, Offset);
3125 /// parseDirectiveCFIRelOffset
3126 /// ::= .cfi_rel_offset register, offset
3127 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3128 int64_t Register = 0;
3130 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3133 if (getLexer().isNot(AsmToken::Comma))
3134 return TokError("unexpected token in directive");
3138 if (parseAbsoluteExpression(Offset))
3141 getStreamer().EmitCFIRelOffset(Register, Offset);
3145 static bool isValidEncoding(int64_t Encoding) {
3146 if (Encoding & ~0xff)
3149 if (Encoding == dwarf::DW_EH_PE_omit)
3152 const unsigned Format = Encoding & 0xf;
3153 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3154 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3155 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3156 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3159 const unsigned Application = Encoding & 0x70;
3160 if (Application != dwarf::DW_EH_PE_absptr &&
3161 Application != dwarf::DW_EH_PE_pcrel)
3167 /// parseDirectiveCFIPersonalityOrLsda
3168 /// IsPersonality true for cfi_personality, false for cfi_lsda
3169 /// ::= .cfi_personality encoding, [symbol_name]
3170 /// ::= .cfi_lsda encoding, [symbol_name]
3171 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3172 int64_t Encoding = 0;
3173 if (parseAbsoluteExpression(Encoding))
3175 if (Encoding == dwarf::DW_EH_PE_omit)
3178 if (!isValidEncoding(Encoding))
3179 return TokError("unsupported encoding.");
3181 if (getLexer().isNot(AsmToken::Comma))
3182 return TokError("unexpected token in directive");
3186 if (parseIdentifier(Name))
3187 return TokError("expected identifier in directive");
3189 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3192 getStreamer().EmitCFIPersonality(Sym, Encoding);
3194 getStreamer().EmitCFILsda(Sym, Encoding);
3198 /// parseDirectiveCFIRememberState
3199 /// ::= .cfi_remember_state
3200 bool AsmParser::parseDirectiveCFIRememberState() {
3201 getStreamer().EmitCFIRememberState();
3205 /// parseDirectiveCFIRestoreState
3206 /// ::= .cfi_remember_state
3207 bool AsmParser::parseDirectiveCFIRestoreState() {
3208 getStreamer().EmitCFIRestoreState();
3212 /// parseDirectiveCFISameValue
3213 /// ::= .cfi_same_value register
3214 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3215 int64_t Register = 0;
3217 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3220 getStreamer().EmitCFISameValue(Register);
3224 /// parseDirectiveCFIRestore
3225 /// ::= .cfi_restore register
3226 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3227 int64_t Register = 0;
3228 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3231 getStreamer().EmitCFIRestore(Register);
3235 /// parseDirectiveCFIEscape
3236 /// ::= .cfi_escape expression[,...]
3237 bool AsmParser::parseDirectiveCFIEscape() {
3240 if (parseAbsoluteExpression(CurrValue))
3243 Values.push_back((uint8_t)CurrValue);
3245 while (getLexer().is(AsmToken::Comma)) {
3248 if (parseAbsoluteExpression(CurrValue))
3251 Values.push_back((uint8_t)CurrValue);
3254 getStreamer().EmitCFIEscape(Values);
3258 /// parseDirectiveCFISignalFrame
3259 /// ::= .cfi_signal_frame
3260 bool AsmParser::parseDirectiveCFISignalFrame() {
3261 if (getLexer().isNot(AsmToken::EndOfStatement))
3262 return Error(getLexer().getLoc(),
3263 "unexpected token in '.cfi_signal_frame'");
3265 getStreamer().EmitCFISignalFrame();
3269 /// parseDirectiveCFIUndefined
3270 /// ::= .cfi_undefined register
3271 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3272 int64_t Register = 0;
3274 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3277 getStreamer().EmitCFIUndefined(Register);
3281 /// parseDirectiveMacrosOnOff
3284 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3285 if (getLexer().isNot(AsmToken::EndOfStatement))
3286 return Error(getLexer().getLoc(),
3287 "unexpected token in '" + Directive + "' directive");
3289 setMacrosEnabled(Directive == ".macros_on");
3293 /// parseDirectiveMacro
3294 /// ::= .macro name[,] [parameters]
3295 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3297 if (parseIdentifier(Name))
3298 return TokError("expected identifier in '.macro' directive");
3300 if (getLexer().is(AsmToken::Comma))
3303 MCAsmMacroParameters Parameters;
3304 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3306 if (!Parameters.empty() && Parameters.back().Vararg)
3307 return Error(Lexer.getLoc(),
3308 "Vararg parameter '" + Parameters.back().Name +
3309 "' should be last one in the list of parameters.");
3311 MCAsmMacroParameter Parameter;
3312 if (parseIdentifier(Parameter.Name))
3313 return TokError("expected identifier in '.macro' directive");
3315 if (Lexer.is(AsmToken::Colon)) {
3316 Lex(); // consume ':'
3319 StringRef Qualifier;
3321 QualLoc = Lexer.getLoc();
3322 if (parseIdentifier(Qualifier))
3323 return Error(QualLoc, "missing parameter qualifier for "
3324 "'" + Parameter.Name + "' in macro '" + Name + "'");
3326 if (Qualifier == "req")
3327 Parameter.Required = true;
3328 else if (Qualifier == "vararg")
3329 Parameter.Vararg = true;
3331 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3332 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3335 if (getLexer().is(AsmToken::Equal)) {
3340 ParamLoc = Lexer.getLoc();
3341 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3344 if (Parameter.Required)
3345 Warning(ParamLoc, "pointless default value for required parameter "
3346 "'" + Parameter.Name + "' in macro '" + Name + "'");
3349 Parameters.push_back(std::move(Parameter));
3351 if (getLexer().is(AsmToken::Comma))
3355 // Eat the end of statement.
3358 AsmToken EndToken, StartToken = getTok();
3359 unsigned MacroDepth = 0;
3361 // Lex the macro definition.
3363 // Check whether we have reached the end of the file.
3364 if (getLexer().is(AsmToken::Eof))
3365 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3367 // Otherwise, check whether we have reach the .endmacro.
3368 if (getLexer().is(AsmToken::Identifier)) {
3369 if (getTok().getIdentifier() == ".endm" ||
3370 getTok().getIdentifier() == ".endmacro") {
3371 if (MacroDepth == 0) { // Outermost macro.
3372 EndToken = getTok();
3374 if (getLexer().isNot(AsmToken::EndOfStatement))
3375 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3379 // Otherwise we just found the end of an inner macro.
3382 } else if (getTok().getIdentifier() == ".macro") {
3383 // We allow nested macros. Those aren't instantiated until the outermost
3384 // macro is expanded so just ignore them for now.
3389 // Otherwise, scan til the end of the statement.
3390 eatToEndOfStatement();
3393 if (lookupMacro(Name)) {
3394 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3397 const char *BodyStart = StartToken.getLoc().getPointer();
3398 const char *BodyEnd = EndToken.getLoc().getPointer();
3399 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3400 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3401 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3405 /// checkForBadMacro
3407 /// With the support added for named parameters there may be code out there that
3408 /// is transitioning from positional parameters. In versions of gas that did
3409 /// not support named parameters they would be ignored on the macro definition.
3410 /// But to support both styles of parameters this is not possible so if a macro
3411 /// definition has named parameters but does not use them and has what appears
3412 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3413 /// warning that the positional parameter found in body which have no effect.
3414 /// Hoping the developer will either remove the named parameters from the macro
3415 /// definition so the positional parameters get used if that was what was
3416 /// intended or change the macro to use the named parameters. It is possible
3417 /// this warning will trigger when the none of the named parameters are used
3418 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3419 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3421 ArrayRef<MCAsmMacroParameter> Parameters) {
3422 // If this macro is not defined with named parameters the warning we are
3423 // checking for here doesn't apply.
3424 unsigned NParameters = Parameters.size();
3425 if (NParameters == 0)
3428 bool NamedParametersFound = false;
3429 bool PositionalParametersFound = false;
3431 // Look at the body of the macro for use of both the named parameters and what
3432 // are likely to be positional parameters. This is what expandMacro() is
3433 // doing when it finds the parameters in the body.
3434 while (!Body.empty()) {
3435 // Scan for the next possible parameter.
3436 std::size_t End = Body.size(), Pos = 0;
3437 for (; Pos != End; ++Pos) {
3438 // Check for a substitution or escape.
3439 // This macro is defined with parameters, look for \foo, \bar, etc.
3440 if (Body[Pos] == '\\' && Pos + 1 != End)
3443 // This macro should have parameters, but look for $0, $1, ..., $n too.
3444 if (Body[Pos] != '$' || Pos + 1 == End)
3446 char Next = Body[Pos + 1];
3447 if (Next == '$' || Next == 'n' ||
3448 isdigit(static_cast<unsigned char>(Next)))
3452 // Check if we reached the end.
3456 if (Body[Pos] == '$') {
3457 switch (Body[Pos + 1]) {
3462 // $n => number of arguments
3464 PositionalParametersFound = true;
3467 // $[0-9] => argument
3469 PositionalParametersFound = true;
3475 unsigned I = Pos + 1;
3476 while (isIdentifierChar(Body[I]) && I + 1 != End)
3479 const char *Begin = Body.data() + Pos + 1;
3480 StringRef Argument(Begin, I - (Pos + 1));
3482 for (; Index < NParameters; ++Index)
3483 if (Parameters[Index].Name == Argument)
3486 if (Index == NParameters) {
3487 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3493 NamedParametersFound = true;
3494 Pos += 1 + Argument.size();
3497 // Update the scan point.
3498 Body = Body.substr(Pos);
3501 if (!NamedParametersFound && PositionalParametersFound)
3502 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3503 "used in macro body, possible positional parameter "
3504 "found in body which will have no effect");
3507 /// parseDirectiveExitMacro
3509 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3510 if (getLexer().isNot(AsmToken::EndOfStatement))
3511 return TokError("unexpected token in '" + Directive + "' directive");
3513 if (!isInsideMacroInstantiation())
3514 return TokError("unexpected '" + Directive + "' in file, "
3515 "no current macro definition");
3517 // Exit all conditionals that are active in the current macro.
3518 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3519 TheCondState = TheCondStack.back();
3520 TheCondStack.pop_back();
3527 /// parseDirectiveEndMacro
3530 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3531 if (getLexer().isNot(AsmToken::EndOfStatement))
3532 return TokError("unexpected token in '" + Directive + "' directive");
3534 // If we are inside a macro instantiation, terminate the current
3536 if (isInsideMacroInstantiation()) {
3541 // Otherwise, this .endmacro is a stray entry in the file; well formed
3542 // .endmacro directives are handled during the macro definition parsing.
3543 return TokError("unexpected '" + Directive + "' in file, "
3544 "no current macro definition");
3547 /// parseDirectivePurgeMacro
3549 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3551 if (parseIdentifier(Name))
3552 return TokError("expected identifier in '.purgem' directive");
3554 if (getLexer().isNot(AsmToken::EndOfStatement))
3555 return TokError("unexpected token in '.purgem' directive");
3557 if (!lookupMacro(Name))
3558 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3560 undefineMacro(Name);
3564 /// parseDirectiveBundleAlignMode
3565 /// ::= {.bundle_align_mode} expression
3566 bool AsmParser::parseDirectiveBundleAlignMode() {
3567 checkForValidSection();
3569 // Expect a single argument: an expression that evaluates to a constant
3570 // in the inclusive range 0-30.
3571 SMLoc ExprLoc = getLexer().getLoc();
3572 int64_t AlignSizePow2;
3573 if (parseAbsoluteExpression(AlignSizePow2))
3575 else if (getLexer().isNot(AsmToken::EndOfStatement))
3576 return TokError("unexpected token after expression in"
3577 " '.bundle_align_mode' directive");
3578 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3579 return Error(ExprLoc,
3580 "invalid bundle alignment size (expected between 0 and 30)");
3584 // Because of AlignSizePow2's verified range we can safely truncate it to
3586 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3590 /// parseDirectiveBundleLock
3591 /// ::= {.bundle_lock} [align_to_end]
3592 bool AsmParser::parseDirectiveBundleLock() {
3593 checkForValidSection();
3594 bool AlignToEnd = false;
3596 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3598 SMLoc Loc = getTok().getLoc();
3599 const char *kInvalidOptionError =
3600 "invalid option for '.bundle_lock' directive";
3602 if (parseIdentifier(Option))
3603 return Error(Loc, kInvalidOptionError);
3605 if (Option != "align_to_end")
3606 return Error(Loc, kInvalidOptionError);
3607 else if (getLexer().isNot(AsmToken::EndOfStatement))
3609 "unexpected token after '.bundle_lock' directive option");
3615 getStreamer().EmitBundleLock(AlignToEnd);
3619 /// parseDirectiveBundleLock
3620 /// ::= {.bundle_lock}
3621 bool AsmParser::parseDirectiveBundleUnlock() {
3622 checkForValidSection();
3624 if (getLexer().isNot(AsmToken::EndOfStatement))
3625 return TokError("unexpected token in '.bundle_unlock' directive");
3628 getStreamer().EmitBundleUnlock();
3632 /// parseDirectiveSpace
3633 /// ::= (.skip | .space) expression [ , expression ]
3634 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3635 checkForValidSection();
3638 if (parseAbsoluteExpression(NumBytes))
3641 int64_t FillExpr = 0;
3642 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3643 if (getLexer().isNot(AsmToken::Comma))
3644 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3647 if (parseAbsoluteExpression(FillExpr))
3650 if (getLexer().isNot(AsmToken::EndOfStatement))
3651 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3657 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3660 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3661 getStreamer().EmitFill(NumBytes, FillExpr);
3666 /// parseDirectiveLEB128
3667 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3668 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3669 checkForValidSection();
3670 const MCExpr *Value;
3673 if (parseExpression(Value))
3677 getStreamer().EmitSLEB128Value(Value);
3679 getStreamer().EmitULEB128Value(Value);
3681 if (getLexer().is(AsmToken::EndOfStatement))
3684 if (getLexer().isNot(AsmToken::Comma))
3685 return TokError("unexpected token in directive");
3692 /// parseDirectiveSymbolAttribute
3693 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3694 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3695 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3698 SMLoc Loc = getTok().getLoc();
3700 if (parseIdentifier(Name))
3701 return Error(Loc, "expected identifier in directive");
3703 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3705 // Assembler local symbols don't make any sense here. Complain loudly.
3706 if (Sym->isTemporary())
3707 return Error(Loc, "non-local symbol required in directive");
3709 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3710 return Error(Loc, "unable to emit symbol attribute");
3712 if (getLexer().is(AsmToken::EndOfStatement))
3715 if (getLexer().isNot(AsmToken::Comma))
3716 return TokError("unexpected token in directive");
3725 /// parseDirectiveComm
3726 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3727 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3728 checkForValidSection();
3730 SMLoc IDLoc = getLexer().getLoc();
3732 if (parseIdentifier(Name))
3733 return TokError("expected identifier in directive");
3735 // Handle the identifier as the key symbol.
3736 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3738 if (getLexer().isNot(AsmToken::Comma))
3739 return TokError("unexpected token in directive");
3743 SMLoc SizeLoc = getLexer().getLoc();
3744 if (parseAbsoluteExpression(Size))
3747 int64_t Pow2Alignment = 0;
3748 SMLoc Pow2AlignmentLoc;
3749 if (getLexer().is(AsmToken::Comma)) {
3751 Pow2AlignmentLoc = getLexer().getLoc();
3752 if (parseAbsoluteExpression(Pow2Alignment))
3755 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3756 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3757 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3759 // If this target takes alignments in bytes (not log) validate and convert.
3760 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3761 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3762 if (!isPowerOf2_64(Pow2Alignment))
3763 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3764 Pow2Alignment = Log2_64(Pow2Alignment);
3768 if (getLexer().isNot(AsmToken::EndOfStatement))
3769 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3773 // NOTE: a size of zero for a .comm should create a undefined symbol
3774 // but a size of .lcomm creates a bss symbol of size zero.
3776 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3777 "be less than zero");
3779 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3780 // may internally end up wanting an alignment in bytes.
3781 // FIXME: Diagnose overflow.
3782 if (Pow2Alignment < 0)
3783 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3784 "alignment, can't be less than zero");
3786 if (!Sym->isUndefined())
3787 return Error(IDLoc, "invalid symbol redefinition");
3789 // Create the Symbol as a common or local common with Size and Pow2Alignment
3791 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3795 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3799 /// parseDirectiveAbort
3800 /// ::= .abort [... message ...]
3801 bool AsmParser::parseDirectiveAbort() {
3802 // FIXME: Use loc from directive.
3803 SMLoc Loc = getLexer().getLoc();
3805 StringRef Str = parseStringToEndOfStatement();
3806 if (getLexer().isNot(AsmToken::EndOfStatement))
3807 return TokError("unexpected token in '.abort' directive");
3812 Error(Loc, ".abort detected. Assembly stopping.");
3814 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3815 // FIXME: Actually abort assembly here.
3820 /// parseDirectiveInclude
3821 /// ::= .include "filename"
3822 bool AsmParser::parseDirectiveInclude() {
3823 if (getLexer().isNot(AsmToken::String))
3824 return TokError("expected string in '.include' directive");
3826 // Allow the strings to have escaped octal character sequence.
3827 std::string Filename;
3828 if (parseEscapedString(Filename))
3830 SMLoc IncludeLoc = getLexer().getLoc();
3833 if (getLexer().isNot(AsmToken::EndOfStatement))
3834 return TokError("unexpected token in '.include' directive");
3836 // Attempt to switch the lexer to the included file before consuming the end
3837 // of statement to avoid losing it when we switch.
3838 if (enterIncludeFile(Filename)) {
3839 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3846 /// parseDirectiveIncbin
3847 /// ::= .incbin "filename"
3848 bool AsmParser::parseDirectiveIncbin() {
3849 if (getLexer().isNot(AsmToken::String))
3850 return TokError("expected string in '.incbin' directive");
3852 // Allow the strings to have escaped octal character sequence.
3853 std::string Filename;
3854 if (parseEscapedString(Filename))
3856 SMLoc IncbinLoc = getLexer().getLoc();
3859 if (getLexer().isNot(AsmToken::EndOfStatement))
3860 return TokError("unexpected token in '.incbin' directive");
3862 // Attempt to process the included file.
3863 if (processIncbinFile(Filename)) {
3864 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3871 /// parseDirectiveIf
3872 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3873 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3874 TheCondStack.push_back(TheCondState);
3875 TheCondState.TheCond = AsmCond::IfCond;
3876 if (TheCondState.Ignore) {
3877 eatToEndOfStatement();
3880 if (parseAbsoluteExpression(ExprValue))
3883 if (getLexer().isNot(AsmToken::EndOfStatement))
3884 return TokError("unexpected token in '.if' directive");
3890 llvm_unreachable("unsupported directive");
3895 ExprValue = ExprValue == 0;
3898 ExprValue = ExprValue >= 0;
3901 ExprValue = ExprValue > 0;
3904 ExprValue = ExprValue <= 0;
3907 ExprValue = ExprValue < 0;
3911 TheCondState.CondMet = ExprValue;
3912 TheCondState.Ignore = !TheCondState.CondMet;
3918 /// parseDirectiveIfb
3920 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3921 TheCondStack.push_back(TheCondState);
3922 TheCondState.TheCond = AsmCond::IfCond;
3924 if (TheCondState.Ignore) {
3925 eatToEndOfStatement();
3927 StringRef Str = parseStringToEndOfStatement();
3929 if (getLexer().isNot(AsmToken::EndOfStatement))
3930 return TokError("unexpected token in '.ifb' directive");
3934 TheCondState.CondMet = ExpectBlank == Str.empty();
3935 TheCondState.Ignore = !TheCondState.CondMet;
3941 /// parseDirectiveIfc
3942 /// ::= .ifc string1, string2
3943 /// ::= .ifnc string1, string2
3944 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3945 TheCondStack.push_back(TheCondState);
3946 TheCondState.TheCond = AsmCond::IfCond;
3948 if (TheCondState.Ignore) {
3949 eatToEndOfStatement();
3951 StringRef Str1 = parseStringToComma();
3953 if (getLexer().isNot(AsmToken::Comma))
3954 return TokError("unexpected token in '.ifc' directive");
3958 StringRef Str2 = parseStringToEndOfStatement();
3960 if (getLexer().isNot(AsmToken::EndOfStatement))
3961 return TokError("unexpected token in '.ifc' directive");
3965 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3966 TheCondState.Ignore = !TheCondState.CondMet;
3972 /// parseDirectiveIfeqs
3973 /// ::= .ifeqs string1, string2
3974 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3975 if (Lexer.isNot(AsmToken::String)) {
3977 TokError("expected string parameter for '.ifeqs' directive");
3979 TokError("expected string parameter for '.ifnes' directive");
3980 eatToEndOfStatement();
3984 StringRef String1 = getTok().getStringContents();
3987 if (Lexer.isNot(AsmToken::Comma)) {
3989 TokError("expected comma after first string for '.ifeqs' directive");
3991 TokError("expected comma after first string for '.ifnes' directive");
3992 eatToEndOfStatement();
3998 if (Lexer.isNot(AsmToken::String)) {
4000 TokError("expected string parameter for '.ifeqs' directive");
4002 TokError("expected string parameter for '.ifnes' directive");
4003 eatToEndOfStatement();
4007 StringRef String2 = getTok().getStringContents();
4010 TheCondStack.push_back(TheCondState);
4011 TheCondState.TheCond = AsmCond::IfCond;
4012 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4013 TheCondState.Ignore = !TheCondState.CondMet;
4018 /// parseDirectiveIfdef
4019 /// ::= .ifdef symbol
4020 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4022 TheCondStack.push_back(TheCondState);
4023 TheCondState.TheCond = AsmCond::IfCond;
4025 if (TheCondState.Ignore) {
4026 eatToEndOfStatement();
4028 if (parseIdentifier(Name))
4029 return TokError("expected identifier after '.ifdef'");
4033 MCSymbol *Sym = getContext().lookupSymbol(Name);
4036 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4038 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4039 TheCondState.Ignore = !TheCondState.CondMet;
4045 /// parseDirectiveElseIf
4046 /// ::= .elseif expression
4047 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4048 if (TheCondState.TheCond != AsmCond::IfCond &&
4049 TheCondState.TheCond != AsmCond::ElseIfCond)
4050 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4052 TheCondState.TheCond = AsmCond::ElseIfCond;
4054 bool LastIgnoreState = false;
4055 if (!TheCondStack.empty())
4056 LastIgnoreState = TheCondStack.back().Ignore;
4057 if (LastIgnoreState || TheCondState.CondMet) {
4058 TheCondState.Ignore = true;
4059 eatToEndOfStatement();
4062 if (parseAbsoluteExpression(ExprValue))
4065 if (getLexer().isNot(AsmToken::EndOfStatement))
4066 return TokError("unexpected token in '.elseif' directive");
4069 TheCondState.CondMet = ExprValue;
4070 TheCondState.Ignore = !TheCondState.CondMet;
4076 /// parseDirectiveElse
4078 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4079 if (getLexer().isNot(AsmToken::EndOfStatement))
4080 return TokError("unexpected token in '.else' directive");
4084 if (TheCondState.TheCond != AsmCond::IfCond &&
4085 TheCondState.TheCond != AsmCond::ElseIfCond)
4086 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4088 TheCondState.TheCond = AsmCond::ElseCond;
4089 bool LastIgnoreState = false;
4090 if (!TheCondStack.empty())
4091 LastIgnoreState = TheCondStack.back().Ignore;
4092 if (LastIgnoreState || TheCondState.CondMet)
4093 TheCondState.Ignore = true;
4095 TheCondState.Ignore = false;
4100 /// parseDirectiveEnd
4102 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4103 if (getLexer().isNot(AsmToken::EndOfStatement))
4104 return TokError("unexpected token in '.end' directive");
4108 while (Lexer.isNot(AsmToken::Eof))
4114 /// parseDirectiveError
4116 /// ::= .error [string]
4117 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4118 if (!TheCondStack.empty()) {
4119 if (TheCondStack.back().Ignore) {
4120 eatToEndOfStatement();
4126 return Error(L, ".err encountered");
4128 StringRef Message = ".error directive invoked in source file";
4129 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4130 if (Lexer.isNot(AsmToken::String)) {
4131 TokError(".error argument must be a string");
4132 eatToEndOfStatement();
4136 Message = getTok().getStringContents();
4144 /// parseDirectiveWarning
4145 /// ::= .warning [string]
4146 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4147 if (!TheCondStack.empty()) {
4148 if (TheCondStack.back().Ignore) {
4149 eatToEndOfStatement();
4154 StringRef Message = ".warning directive invoked in source file";
4155 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4156 if (Lexer.isNot(AsmToken::String)) {
4157 TokError(".warning argument must be a string");
4158 eatToEndOfStatement();
4162 Message = getTok().getStringContents();
4166 Warning(L, Message);
4170 /// parseDirectiveEndIf
4172 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4173 if (getLexer().isNot(AsmToken::EndOfStatement))
4174 return TokError("unexpected token in '.endif' directive");
4178 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4179 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4181 if (!TheCondStack.empty()) {
4182 TheCondState = TheCondStack.back();
4183 TheCondStack.pop_back();
4189 void AsmParser::initializeDirectiveKindMap() {
4190 DirectiveKindMap[".set"] = DK_SET;
4191 DirectiveKindMap[".equ"] = DK_EQU;
4192 DirectiveKindMap[".equiv"] = DK_EQUIV;
4193 DirectiveKindMap[".ascii"] = DK_ASCII;
4194 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4195 DirectiveKindMap[".string"] = DK_STRING;
4196 DirectiveKindMap[".byte"] = DK_BYTE;
4197 DirectiveKindMap[".short"] = DK_SHORT;
4198 DirectiveKindMap[".value"] = DK_VALUE;
4199 DirectiveKindMap[".2byte"] = DK_2BYTE;
4200 DirectiveKindMap[".long"] = DK_LONG;
4201 DirectiveKindMap[".int"] = DK_INT;
4202 DirectiveKindMap[".4byte"] = DK_4BYTE;
4203 DirectiveKindMap[".quad"] = DK_QUAD;
4204 DirectiveKindMap[".8byte"] = DK_8BYTE;
4205 DirectiveKindMap[".octa"] = DK_OCTA;
4206 DirectiveKindMap[".single"] = DK_SINGLE;
4207 DirectiveKindMap[".float"] = DK_FLOAT;
4208 DirectiveKindMap[".double"] = DK_DOUBLE;
4209 DirectiveKindMap[".align"] = DK_ALIGN;
4210 DirectiveKindMap[".align32"] = DK_ALIGN32;
4211 DirectiveKindMap[".balign"] = DK_BALIGN;
4212 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4213 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4214 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4215 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4216 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4217 DirectiveKindMap[".org"] = DK_ORG;
4218 DirectiveKindMap[".fill"] = DK_FILL;
4219 DirectiveKindMap[".zero"] = DK_ZERO;
4220 DirectiveKindMap[".extern"] = DK_EXTERN;
4221 DirectiveKindMap[".globl"] = DK_GLOBL;
4222 DirectiveKindMap[".global"] = DK_GLOBAL;
4223 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4224 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4225 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4226 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4227 DirectiveKindMap[".reference"] = DK_REFERENCE;
4228 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4229 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4230 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4231 DirectiveKindMap[".comm"] = DK_COMM;
4232 DirectiveKindMap[".common"] = DK_COMMON;
4233 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4234 DirectiveKindMap[".abort"] = DK_ABORT;
4235 DirectiveKindMap[".include"] = DK_INCLUDE;
4236 DirectiveKindMap[".incbin"] = DK_INCBIN;
4237 DirectiveKindMap[".code16"] = DK_CODE16;
4238 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4239 DirectiveKindMap[".rept"] = DK_REPT;
4240 DirectiveKindMap[".rep"] = DK_REPT;
4241 DirectiveKindMap[".irp"] = DK_IRP;
4242 DirectiveKindMap[".irpc"] = DK_IRPC;
4243 DirectiveKindMap[".endr"] = DK_ENDR;
4244 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4245 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4246 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4247 DirectiveKindMap[".if"] = DK_IF;
4248 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4249 DirectiveKindMap[".ifge"] = DK_IFGE;
4250 DirectiveKindMap[".ifgt"] = DK_IFGT;
4251 DirectiveKindMap[".ifle"] = DK_IFLE;
4252 DirectiveKindMap[".iflt"] = DK_IFLT;
4253 DirectiveKindMap[".ifne"] = DK_IFNE;
4254 DirectiveKindMap[".ifb"] = DK_IFB;
4255 DirectiveKindMap[".ifnb"] = DK_IFNB;
4256 DirectiveKindMap[".ifc"] = DK_IFC;
4257 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4258 DirectiveKindMap[".ifnc"] = DK_IFNC;
4259 DirectiveKindMap[".ifnes"] = DK_IFNES;
4260 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4261 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4262 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4263 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4264 DirectiveKindMap[".else"] = DK_ELSE;
4265 DirectiveKindMap[".end"] = DK_END;
4266 DirectiveKindMap[".endif"] = DK_ENDIF;
4267 DirectiveKindMap[".skip"] = DK_SKIP;
4268 DirectiveKindMap[".space"] = DK_SPACE;
4269 DirectiveKindMap[".file"] = DK_FILE;
4270 DirectiveKindMap[".line"] = DK_LINE;
4271 DirectiveKindMap[".loc"] = DK_LOC;
4272 DirectiveKindMap[".stabs"] = DK_STABS;
4273 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4274 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4275 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4276 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4277 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4278 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4279 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4280 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4281 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4282 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4283 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4284 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4285 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4286 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4287 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4288 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4289 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4290 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4291 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4292 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4293 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4294 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4295 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4296 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4297 DirectiveKindMap[".macro"] = DK_MACRO;
4298 DirectiveKindMap[".exitm"] = DK_EXITM;
4299 DirectiveKindMap[".endm"] = DK_ENDM;
4300 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4301 DirectiveKindMap[".purgem"] = DK_PURGEM;
4302 DirectiveKindMap[".err"] = DK_ERR;
4303 DirectiveKindMap[".error"] = DK_ERROR;
4304 DirectiveKindMap[".warning"] = DK_WARNING;
4307 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4308 AsmToken EndToken, StartToken = getTok();
4310 unsigned NestLevel = 0;
4312 // Check whether we have reached the end of the file.
4313 if (getLexer().is(AsmToken::Eof)) {
4314 Error(DirectiveLoc, "no matching '.endr' in definition");
4318 if (Lexer.is(AsmToken::Identifier) &&
4319 (getTok().getIdentifier() == ".rept")) {
4323 // Otherwise, check whether we have reached the .endr.
4324 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4325 if (NestLevel == 0) {
4326 EndToken = getTok();
4328 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4329 TokError("unexpected token in '.endr' directive");
4337 // Otherwise, scan till the end of the statement.
4338 eatToEndOfStatement();
4341 const char *BodyStart = StartToken.getLoc().getPointer();
4342 const char *BodyEnd = EndToken.getLoc().getPointer();
4343 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4345 // We Are Anonymous.
4346 MacroLikeBodies.push_back(
4347 MCAsmMacro(StringRef(), Body, MCAsmMacroParameters()));
4348 return &MacroLikeBodies.back();
4351 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4352 raw_svector_ostream &OS) {
4355 std::unique_ptr<MemoryBuffer> Instantiation =
4356 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4358 // Create the macro instantiation object and add to the current macro
4359 // instantiation stack.
4360 MacroInstantiation *MI = new MacroInstantiation(
4361 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4362 ActiveMacros.push_back(MI);
4364 // Jump to the macro instantiation and prime the lexer.
4365 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4366 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4370 /// parseDirectiveRept
4371 /// ::= .rep | .rept count
4372 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4373 const MCExpr *CountExpr;
4374 SMLoc CountLoc = getTok().getLoc();
4375 if (parseExpression(CountExpr))
4379 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4380 eatToEndOfStatement();
4381 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4385 return Error(CountLoc, "Count is negative");
4387 if (Lexer.isNot(AsmToken::EndOfStatement))
4388 return TokError("unexpected token in '" + Dir + "' directive");
4390 // Eat the end of statement.
4393 // Lex the rept definition.
4394 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4398 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4399 // to hold the macro body with substitutions.
4400 SmallString<256> Buf;
4401 raw_svector_ostream OS(Buf);
4403 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4404 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4407 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4412 /// parseDirectiveIrp
4413 /// ::= .irp symbol,values
4414 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4415 MCAsmMacroParameter Parameter;
4417 if (parseIdentifier(Parameter.Name))
4418 return TokError("expected identifier in '.irp' directive");
4420 if (Lexer.isNot(AsmToken::Comma))
4421 return TokError("expected comma in '.irp' directive");
4425 MCAsmMacroArguments A;
4426 if (parseMacroArguments(nullptr, A))
4429 // Eat the end of statement.
4432 // Lex the irp definition.
4433 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4437 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4438 // to hold the macro body with substitutions.
4439 SmallString<256> Buf;
4440 raw_svector_ostream OS(Buf);
4442 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4443 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4444 // This is undocumented, but GAS seems to support it.
4445 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4449 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4454 /// parseDirectiveIrpc
4455 /// ::= .irpc symbol,values
4456 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4457 MCAsmMacroParameter Parameter;
4459 if (parseIdentifier(Parameter.Name))
4460 return TokError("expected identifier in '.irpc' directive");
4462 if (Lexer.isNot(AsmToken::Comma))
4463 return TokError("expected comma in '.irpc' directive");
4467 MCAsmMacroArguments A;
4468 if (parseMacroArguments(nullptr, A))
4471 if (A.size() != 1 || A.front().size() != 1)
4472 return TokError("unexpected token in '.irpc' directive");
4474 // Eat the end of statement.
4477 // Lex the irpc definition.
4478 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4482 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4483 // to hold the macro body with substitutions.
4484 SmallString<256> Buf;
4485 raw_svector_ostream OS(Buf);
4487 StringRef Values = A.front().front().getString();
4488 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4489 MCAsmMacroArgument Arg;
4490 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4492 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4493 // This is undocumented, but GAS seems to support it.
4494 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4498 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4503 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4504 if (ActiveMacros.empty())
4505 return TokError("unmatched '.endr' directive");
4507 // The only .repl that should get here are the ones created by
4508 // instantiateMacroLikeBody.
4509 assert(getLexer().is(AsmToken::EndOfStatement));
4515 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4517 const MCExpr *Value;
4518 SMLoc ExprLoc = getLexer().getLoc();
4519 if (parseExpression(Value))
4521 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4523 return Error(ExprLoc, "unexpected expression in _emit");
4524 uint64_t IntValue = MCE->getValue();
4525 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4526 return Error(ExprLoc, "literal value out of range for directive");
4528 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4532 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4533 const MCExpr *Value;
4534 SMLoc ExprLoc = getLexer().getLoc();
4535 if (parseExpression(Value))
4537 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4539 return Error(ExprLoc, "unexpected expression in align");
4540 uint64_t IntValue = MCE->getValue();
4541 if (!isPowerOf2_64(IntValue))
4542 return Error(ExprLoc, "literal value not a power of two greater then zero");
4544 Info.AsmRewrites->push_back(
4545 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4549 // We are comparing pointers, but the pointers are relative to a single string.
4550 // Thus, this should always be deterministic.
4551 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4552 const AsmRewrite *AsmRewriteB) {
4553 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4555 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4558 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4559 // rewrite to the same location. Make sure the SizeDirective rewrite is
4560 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4561 // ensures the sort algorithm is stable.
4562 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4563 AsmRewritePrecedence[AsmRewriteB->Kind])
4566 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4567 AsmRewritePrecedence[AsmRewriteB->Kind])
4569 llvm_unreachable("Unstable rewrite sort.");
4572 bool AsmParser::parseMSInlineAsm(
4573 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4574 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4575 SmallVectorImpl<std::string> &Constraints,
4576 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4577 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4578 SmallVector<void *, 4> InputDecls;
4579 SmallVector<void *, 4> OutputDecls;
4580 SmallVector<bool, 4> InputDeclsAddressOf;
4581 SmallVector<bool, 4> OutputDeclsAddressOf;
4582 SmallVector<std::string, 4> InputConstraints;
4583 SmallVector<std::string, 4> OutputConstraints;
4584 SmallVector<unsigned, 4> ClobberRegs;
4586 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4591 // While we have input, parse each statement.
4592 unsigned InputIdx = 0;
4593 unsigned OutputIdx = 0;
4594 while (getLexer().isNot(AsmToken::Eof)) {
4595 ParseStatementInfo Info(&AsmStrRewrites);
4596 if (parseStatement(Info, &SI))
4599 if (Info.ParseError)
4602 if (Info.Opcode == ~0U)
4605 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4607 // Build the list of clobbers, outputs and inputs.
4608 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4609 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4612 if (Operand.isImm())
4615 // Register operand.
4616 if (Operand.isReg() && !Operand.needAddressOf() &&
4617 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4618 unsigned NumDefs = Desc.getNumDefs();
4620 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4621 ClobberRegs.push_back(Operand.getReg());
4625 // Expr/Input or Output.
4626 StringRef SymName = Operand.getSymName();
4627 if (SymName.empty())
4630 void *OpDecl = Operand.getOpDecl();
4634 bool isOutput = (i == 1) && Desc.mayStore();
4635 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4638 OutputDecls.push_back(OpDecl);
4639 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4640 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4641 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4643 InputDecls.push_back(OpDecl);
4644 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4645 InputConstraints.push_back(Operand.getConstraint().str());
4646 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4650 // Consider implicit defs to be clobbers. Think of cpuid and push.
4651 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4652 Desc.getNumImplicitDefs());
4653 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4656 // Set the number of Outputs and Inputs.
4657 NumOutputs = OutputDecls.size();
4658 NumInputs = InputDecls.size();
4660 // Set the unique clobbers.
4661 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4662 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4664 Clobbers.assign(ClobberRegs.size(), std::string());
4665 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4666 raw_string_ostream OS(Clobbers[I]);
4667 IP->printRegName(OS, ClobberRegs[I]);
4670 // Merge the various outputs and inputs. Output are expected first.
4671 if (NumOutputs || NumInputs) {
4672 unsigned NumExprs = NumOutputs + NumInputs;
4673 OpDecls.resize(NumExprs);
4674 Constraints.resize(NumExprs);
4675 for (unsigned i = 0; i < NumOutputs; ++i) {
4676 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4677 Constraints[i] = OutputConstraints[i];
4679 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4680 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4681 Constraints[j] = InputConstraints[i];
4685 // Build the IR assembly string.
4686 std::string AsmStringIR;
4687 raw_string_ostream OS(AsmStringIR);
4688 StringRef ASMString =
4689 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4690 const char *AsmStart = ASMString.begin();
4691 const char *AsmEnd = ASMString.end();
4692 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4693 for (const AsmRewrite &AR : AsmStrRewrites) {
4694 AsmRewriteKind Kind = AR.Kind;
4695 if (Kind == AOK_Delete)
4698 const char *Loc = AR.Loc.getPointer();
4699 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4701 // Emit everything up to the immediate/expression.
4702 if (unsigned Len = Loc - AsmStart)
4703 OS << StringRef(AsmStart, Len);
4705 // Skip the original expression.
4706 if (Kind == AOK_Skip) {
4707 AsmStart = Loc + AR.Len;
4711 unsigned AdditionalSkip = 0;
4712 // Rewrite expressions in $N notation.
4717 OS << "$$" << AR.Val;
4723 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4726 OS << '$' << InputIdx++;
4729 OS << '$' << OutputIdx++;
4731 case AOK_SizeDirective:
4734 case 8: OS << "byte ptr "; break;
4735 case 16: OS << "word ptr "; break;
4736 case 32: OS << "dword ptr "; break;
4737 case 64: OS << "qword ptr "; break;
4738 case 80: OS << "xword ptr "; break;
4739 case 128: OS << "xmmword ptr "; break;
4740 case 256: OS << "ymmword ptr "; break;
4747 unsigned Val = AR.Val;
4748 OS << ".align " << Val;
4750 // Skip the original immediate.
4751 assert(Val < 10 && "Expected alignment less then 2^10.");
4752 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4755 case AOK_DotOperator:
4756 // Insert the dot if the user omitted it.
4758 if (AsmStringIR.back() != '.')
4764 // Skip the original expression.
4765 AsmStart = Loc + AR.Len + AdditionalSkip;
4768 // Emit the remainder of the asm string.
4769 if (AsmStart != AsmEnd)
4770 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4772 AsmString = OS.str();
4776 /// \brief Create an MCAsmParser instance.
4777 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4778 MCStreamer &Out, const MCAsmInfo &MAI) {
4779 return new AsmParser(SM, C, Out, MAI);