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 MCSection *Sec = getStreamer().getCurrentSection().first;
634 if (!Sec->getBeginSymbol()) {
635 MCSymbol *SectionStartSym = getContext().createTempSymbol();
636 getStreamer().EmitLabel(SectionStartSym);
637 Sec->setBeginSymbol(SectionStartSym);
639 bool InsertResult = getContext().addGenDwarfSection(Sec);
640 assert(InsertResult && ".text section should not have debug info yet");
642 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
643 0, StringRef(), getContext().getMainFileName()));
646 // While we have input, parse each statement.
647 while (Lexer.isNot(AsmToken::Eof)) {
648 ParseStatementInfo Info;
649 if (!parseStatement(Info, nullptr))
652 // We had an error, validate that one was emitted and recover by skipping to
654 assert(HadError && "Parse statement returned an error, but none emitted!");
655 eatToEndOfStatement();
658 if (TheCondState.TheCond != StartingCondState.TheCond ||
659 TheCondState.Ignore != StartingCondState.Ignore)
660 return TokError("unmatched .ifs or .elses");
662 // Check to see there are no empty DwarfFile slots.
663 const auto &LineTables = getContext().getMCDwarfLineTables();
664 if (!LineTables.empty()) {
666 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
667 if (File.Name.empty() && Index != 0)
668 TokError("unassigned file number: " + Twine(Index) +
669 " for .file directives");
674 // Check to see that all assembler local symbols were actually defined.
675 // Targets that don't do subsections via symbols may not want this, though,
676 // so conservatively exclude them. Only do this if we're finalizing, though,
677 // as otherwise we won't necessarilly have seen everything yet.
678 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
679 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
680 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
683 MCSymbol *Sym = i->getValue();
684 // Variable symbols may not be marked as defined, so check those
685 // explicitly. If we know it's a variable, we have a definition for
686 // the purposes of this check.
687 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
688 // FIXME: We would really like to refer back to where the symbol was
689 // first referenced for a source location. We need to add something
690 // to track that. Currently, we just point to the end of the file.
692 getLexer().getLoc(), SourceMgr::DK_Error,
693 "assembler local symbol '" + Sym->getName() + "' not defined");
697 // Finalize the output stream if there are no errors and if the client wants
699 if (!HadError && !NoFinalize)
705 void AsmParser::checkForValidSection() {
706 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
707 TokError("expected section directive before assembly directive");
708 Out.InitSections(false);
712 /// \brief Throw away the rest of the line for testing purposes.
713 void AsmParser::eatToEndOfStatement() {
714 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
718 if (Lexer.is(AsmToken::EndOfStatement))
722 StringRef AsmParser::parseStringToEndOfStatement() {
723 const char *Start = getTok().getLoc().getPointer();
725 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
728 const char *End = getTok().getLoc().getPointer();
729 return StringRef(Start, End - Start);
732 StringRef AsmParser::parseStringToComma() {
733 const char *Start = getTok().getLoc().getPointer();
735 while (Lexer.isNot(AsmToken::EndOfStatement) &&
736 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
739 const char *End = getTok().getLoc().getPointer();
740 return StringRef(Start, End - Start);
743 /// \brief Parse a paren expression and return it.
744 /// NOTE: This assumes the leading '(' has already been consumed.
746 /// parenexpr ::= expr)
748 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
749 if (parseExpression(Res))
751 if (Lexer.isNot(AsmToken::RParen))
752 return TokError("expected ')' in parentheses expression");
753 EndLoc = Lexer.getTok().getEndLoc();
758 /// \brief Parse a bracket expression and return it.
759 /// NOTE: This assumes the leading '[' has already been consumed.
761 /// bracketexpr ::= expr]
763 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
764 if (parseExpression(Res))
766 if (Lexer.isNot(AsmToken::RBrac))
767 return TokError("expected ']' in brackets expression");
768 EndLoc = Lexer.getTok().getEndLoc();
773 /// \brief Parse a primary expression and return it.
774 /// primaryexpr ::= (parenexpr
775 /// primaryexpr ::= symbol
776 /// primaryexpr ::= number
777 /// primaryexpr ::= '.'
778 /// primaryexpr ::= ~,+,- primaryexpr
779 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
780 SMLoc FirstTokenLoc = getLexer().getLoc();
781 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
782 switch (FirstTokenKind) {
784 return TokError("unknown token in expression");
785 // If we have an error assume that we've already handled it.
786 case AsmToken::Error:
788 case AsmToken::Exclaim:
789 Lex(); // Eat the operator.
790 if (parsePrimaryExpr(Res, EndLoc))
792 Res = MCUnaryExpr::createLNot(Res, getContext());
794 case AsmToken::Dollar:
796 case AsmToken::String:
797 case AsmToken::Identifier: {
798 StringRef Identifier;
799 if (parseIdentifier(Identifier)) {
800 if (FirstTokenKind == AsmToken::Dollar) {
801 if (Lexer.getMAI().getDollarIsPC()) {
802 // This is a '$' reference, which references the current PC. Emit a
803 // temporary label to the streamer and refer to it.
804 MCSymbol *Sym = Ctx.createTempSymbol();
806 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
808 EndLoc = FirstTokenLoc;
811 return Error(FirstTokenLoc, "invalid token in expression");
814 // Parse symbol variant
815 std::pair<StringRef, StringRef> Split;
816 if (!MAI.useParensForSymbolVariant()) {
817 if (FirstTokenKind == AsmToken::String) {
818 if (Lexer.is(AsmToken::At)) {
819 Lexer.Lex(); // eat @
820 SMLoc AtLoc = getLexer().getLoc();
822 if (parseIdentifier(VName))
823 return Error(AtLoc, "expected symbol variant after '@'");
825 Split = std::make_pair(Identifier, VName);
828 Split = Identifier.split('@');
830 } else if (Lexer.is(AsmToken::LParen)) {
831 Lexer.Lex(); // eat (
833 parseIdentifier(VName);
834 if (Lexer.isNot(AsmToken::RParen)) {
835 return Error(Lexer.getTok().getLoc(),
836 "unexpected token in variant, expected ')'");
838 Lexer.Lex(); // eat )
839 Split = std::make_pair(Identifier, VName);
842 EndLoc = SMLoc::getFromPointer(Identifier.end());
844 // This is a symbol reference.
845 StringRef SymbolName = Identifier;
846 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
848 // Lookup the symbol variant if used.
849 if (Split.second.size()) {
850 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
851 if (Variant != MCSymbolRefExpr::VK_Invalid) {
852 SymbolName = Split.first;
853 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
854 Variant = MCSymbolRefExpr::VK_None;
856 return Error(SMLoc::getFromPointer(Split.second.begin()),
857 "invalid variant '" + Split.second + "'");
861 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
863 // If this is an absolute variable reference, substitute it now to preserve
864 // semantics in the face of reassignment.
865 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
867 return Error(EndLoc, "unexpected modifier on variable reference");
869 Res = Sym->getVariableValue();
873 // Otherwise create a symbol ref.
874 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
877 case AsmToken::BigNum:
878 return TokError("literal value out of range for directive");
879 case AsmToken::Integer: {
880 SMLoc Loc = getTok().getLoc();
881 int64_t IntVal = getTok().getIntVal();
882 Res = MCConstantExpr::create(IntVal, getContext());
883 EndLoc = Lexer.getTok().getEndLoc();
885 // Look for 'b' or 'f' following an Integer as a directional label
886 if (Lexer.getKind() == AsmToken::Identifier) {
887 StringRef IDVal = getTok().getString();
888 // Lookup the symbol variant if used.
889 std::pair<StringRef, StringRef> Split = IDVal.split('@');
890 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
891 if (Split.first.size() != IDVal.size()) {
892 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
893 if (Variant == MCSymbolRefExpr::VK_Invalid)
894 return TokError("invalid variant '" + Split.second + "'");
897 if (IDVal == "f" || IDVal == "b") {
899 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
900 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
901 if (IDVal == "b" && Sym->isUndefined())
902 return Error(Loc, "invalid reference to undefined symbol");
903 EndLoc = Lexer.getTok().getEndLoc();
904 Lex(); // Eat identifier.
909 case AsmToken::Real: {
910 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
911 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
912 Res = MCConstantExpr::create(IntVal, getContext());
913 EndLoc = Lexer.getTok().getEndLoc();
917 case AsmToken::Dot: {
918 // This is a '.' reference, which references the current PC. Emit a
919 // temporary label to the streamer and refer to it.
920 MCSymbol *Sym = Ctx.createTempSymbol();
922 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
923 EndLoc = Lexer.getTok().getEndLoc();
924 Lex(); // Eat identifier.
927 case AsmToken::LParen:
928 Lex(); // Eat the '('.
929 return parseParenExpr(Res, EndLoc);
930 case AsmToken::LBrac:
931 if (!PlatformParser->HasBracketExpressions())
932 return TokError("brackets expression not supported on this target");
933 Lex(); // Eat the '['.
934 return parseBracketExpr(Res, EndLoc);
935 case AsmToken::Minus:
936 Lex(); // Eat the operator.
937 if (parsePrimaryExpr(Res, EndLoc))
939 Res = MCUnaryExpr::createMinus(Res, getContext());
942 Lex(); // Eat the operator.
943 if (parsePrimaryExpr(Res, EndLoc))
945 Res = MCUnaryExpr::createPlus(Res, getContext());
947 case AsmToken::Tilde:
948 Lex(); // Eat the operator.
949 if (parsePrimaryExpr(Res, EndLoc))
951 Res = MCUnaryExpr::createNot(Res, getContext());
956 bool AsmParser::parseExpression(const MCExpr *&Res) {
958 return parseExpression(Res, EndLoc);
962 AsmParser::applyModifierToExpr(const MCExpr *E,
963 MCSymbolRefExpr::VariantKind Variant) {
964 // Ask the target implementation about this expression first.
965 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
968 // Recurse over the given expression, rebuilding it to apply the given variant
969 // if there is exactly one symbol.
970 switch (E->getKind()) {
972 case MCExpr::Constant:
975 case MCExpr::SymbolRef: {
976 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
978 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
979 TokError("invalid variant on expression '" + getTok().getIdentifier() +
980 "' (already modified)");
984 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
987 case MCExpr::Unary: {
988 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
989 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
992 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
995 case MCExpr::Binary: {
996 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
997 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
998 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1008 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1012 llvm_unreachable("Invalid expression kind!");
1015 /// \brief Parse an expression and return it.
1017 /// expr ::= expr &&,|| expr -> lowest.
1018 /// expr ::= expr |,^,&,! expr
1019 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1020 /// expr ::= expr <<,>> expr
1021 /// expr ::= expr +,- expr
1022 /// expr ::= expr *,/,% expr -> highest.
1023 /// expr ::= primaryexpr
1025 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1026 // Parse the expression.
1028 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1031 // As a special case, we support 'a op b @ modifier' by rewriting the
1032 // expression to include the modifier. This is inefficient, but in general we
1033 // expect users to use 'a@modifier op b'.
1034 if (Lexer.getKind() == AsmToken::At) {
1037 if (Lexer.isNot(AsmToken::Identifier))
1038 return TokError("unexpected symbol modifier following '@'");
1040 MCSymbolRefExpr::VariantKind Variant =
1041 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1042 if (Variant == MCSymbolRefExpr::VK_Invalid)
1043 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1045 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1047 return TokError("invalid modifier '" + getTok().getIdentifier() +
1048 "' (no symbols present)");
1055 // Try to constant fold it up front, if possible.
1057 if (Res->evaluateAsAbsolute(Value))
1058 Res = MCConstantExpr::create(Value, getContext());
1063 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1065 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1068 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1071 SMLoc StartLoc = Lexer.getLoc();
1072 if (parseExpression(Expr))
1075 if (!Expr->evaluateAsAbsolute(Res))
1076 return Error(StartLoc, "expected absolute expression");
1081 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1082 MCBinaryExpr::Opcode &Kind) {
1085 return 0; // not a binop.
1087 // Lowest Precedence: &&, ||
1088 case AsmToken::AmpAmp:
1089 Kind = MCBinaryExpr::LAnd;
1091 case AsmToken::PipePipe:
1092 Kind = MCBinaryExpr::LOr;
1095 // Low Precedence: |, &, ^
1097 // FIXME: gas seems to support '!' as an infix operator?
1098 case AsmToken::Pipe:
1099 Kind = MCBinaryExpr::Or;
1101 case AsmToken::Caret:
1102 Kind = MCBinaryExpr::Xor;
1105 Kind = MCBinaryExpr::And;
1108 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1109 case AsmToken::EqualEqual:
1110 Kind = MCBinaryExpr::EQ;
1112 case AsmToken::ExclaimEqual:
1113 case AsmToken::LessGreater:
1114 Kind = MCBinaryExpr::NE;
1116 case AsmToken::Less:
1117 Kind = MCBinaryExpr::LT;
1119 case AsmToken::LessEqual:
1120 Kind = MCBinaryExpr::LTE;
1122 case AsmToken::Greater:
1123 Kind = MCBinaryExpr::GT;
1125 case AsmToken::GreaterEqual:
1126 Kind = MCBinaryExpr::GTE;
1129 // Intermediate Precedence: <<, >>
1130 case AsmToken::LessLess:
1131 Kind = MCBinaryExpr::Shl;
1133 case AsmToken::GreaterGreater:
1134 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1137 // High Intermediate Precedence: +, -
1138 case AsmToken::Plus:
1139 Kind = MCBinaryExpr::Add;
1141 case AsmToken::Minus:
1142 Kind = MCBinaryExpr::Sub;
1145 // Highest Precedence: *, /, %
1146 case AsmToken::Star:
1147 Kind = MCBinaryExpr::Mul;
1149 case AsmToken::Slash:
1150 Kind = MCBinaryExpr::Div;
1152 case AsmToken::Percent:
1153 Kind = MCBinaryExpr::Mod;
1158 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1159 /// Res contains the LHS of the expression on input.
1160 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1163 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1164 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1166 // If the next token is lower precedence than we are allowed to eat, return
1167 // successfully with what we ate already.
1168 if (TokPrec < Precedence)
1173 // Eat the next primary expression.
1175 if (parsePrimaryExpr(RHS, EndLoc))
1178 // If BinOp binds less tightly with RHS than the operator after RHS, let
1179 // the pending operator take RHS as its LHS.
1180 MCBinaryExpr::Opcode Dummy;
1181 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1182 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1185 // Merge LHS and RHS according to operator.
1186 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1191 /// ::= EndOfStatement
1192 /// ::= Label* Directive ...Operands... EndOfStatement
1193 /// ::= Label* Identifier OperandList* EndOfStatement
1194 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1195 MCAsmParserSemaCallback *SI) {
1196 if (Lexer.is(AsmToken::EndOfStatement)) {
1202 // Statements always start with an identifier or are a full line comment.
1203 AsmToken ID = getTok();
1204 SMLoc IDLoc = ID.getLoc();
1206 int64_t LocalLabelVal = -1;
1207 // A full line comment is a '#' as the first token.
1208 if (Lexer.is(AsmToken::Hash))
1209 return parseCppHashLineFilenameComment(IDLoc);
1211 // Allow an integer followed by a ':' as a directional local label.
1212 if (Lexer.is(AsmToken::Integer)) {
1213 LocalLabelVal = getTok().getIntVal();
1214 if (LocalLabelVal < 0) {
1215 if (!TheCondState.Ignore)
1216 return TokError("unexpected token at start of statement");
1219 IDVal = getTok().getString();
1220 Lex(); // Consume the integer token to be used as an identifier token.
1221 if (Lexer.getKind() != AsmToken::Colon) {
1222 if (!TheCondState.Ignore)
1223 return TokError("unexpected token at start of statement");
1226 } else if (Lexer.is(AsmToken::Dot)) {
1227 // Treat '.' as a valid identifier in this context.
1230 } else if (parseIdentifier(IDVal)) {
1231 if (!TheCondState.Ignore)
1232 return TokError("unexpected token at start of statement");
1236 // Handle conditional assembly here before checking for skipping. We
1237 // have to do this so that .endif isn't skipped in a ".if 0" block for
1239 StringMap<DirectiveKind>::const_iterator DirKindIt =
1240 DirectiveKindMap.find(IDVal);
1241 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1243 : DirKindIt->getValue();
1254 return parseDirectiveIf(IDLoc, DirKind);
1256 return parseDirectiveIfb(IDLoc, true);
1258 return parseDirectiveIfb(IDLoc, false);
1260 return parseDirectiveIfc(IDLoc, true);
1262 return parseDirectiveIfeqs(IDLoc, true);
1264 return parseDirectiveIfc(IDLoc, false);
1266 return parseDirectiveIfeqs(IDLoc, false);
1268 return parseDirectiveIfdef(IDLoc, true);
1271 return parseDirectiveIfdef(IDLoc, false);
1273 return parseDirectiveElseIf(IDLoc);
1275 return parseDirectiveElse(IDLoc);
1277 return parseDirectiveEndIf(IDLoc);
1280 // Ignore the statement if in the middle of inactive conditional
1282 if (TheCondState.Ignore) {
1283 eatToEndOfStatement();
1287 // FIXME: Recurse on local labels?
1289 // See what kind of statement we have.
1290 switch (Lexer.getKind()) {
1291 case AsmToken::Colon: {
1292 checkForValidSection();
1294 // identifier ':' -> Label.
1297 // Diagnose attempt to use '.' as a label.
1299 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1301 // Diagnose attempt to use a variable as a label.
1303 // FIXME: Diagnostics. Note the location of the definition as a label.
1304 // FIXME: This doesn't diagnose assignment to a symbol which has been
1305 // implicitly marked as external.
1307 if (LocalLabelVal == -1) {
1308 if (ParsingInlineAsm && SI) {
1309 StringRef RewrittenLabel =
1310 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1311 assert(RewrittenLabel.size() &&
1312 "We should have an internal name here.");
1313 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1314 IDVal.size(), RewrittenLabel));
1315 IDVal = RewrittenLabel;
1317 Sym = getContext().getOrCreateSymbol(IDVal);
1319 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1321 Sym->redefineIfPossible();
1323 if (!Sym->isUndefined() || Sym->isVariable())
1324 return Error(IDLoc, "invalid symbol redefinition");
1327 if (!ParsingInlineAsm)
1330 // If we are generating dwarf for assembly source files then gather the
1331 // info to make a dwarf label entry for this label if needed.
1332 if (getContext().getGenDwarfForAssembly())
1333 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1336 getTargetParser().onLabelParsed(Sym);
1338 // Consume any end of statement token, if present, to avoid spurious
1339 // AddBlankLine calls().
1340 if (Lexer.is(AsmToken::EndOfStatement)) {
1342 if (Lexer.is(AsmToken::Eof))
1349 case AsmToken::Equal:
1350 // identifier '=' ... -> assignment statement
1353 return parseAssignment(IDVal, true);
1355 default: // Normal instruction or directive.
1359 // If macros are enabled, check to see if this is a macro instantiation.
1360 if (areMacrosEnabled())
1361 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1362 return handleMacroEntry(M, IDLoc);
1365 // Otherwise, we have a normal instruction or directive.
1367 // Directives start with "."
1368 if (IDVal[0] == '.' && IDVal != ".") {
1369 // There are several entities interested in parsing directives:
1371 // 1. The target-specific assembly parser. Some directives are target
1372 // specific or may potentially behave differently on certain targets.
1373 // 2. Asm parser extensions. For example, platform-specific parsers
1374 // (like the ELF parser) register themselves as extensions.
1375 // 3. The generic directive parser implemented by this class. These are
1376 // all the directives that behave in a target and platform independent
1377 // manner, or at least have a default behavior that's shared between
1378 // all targets and platforms.
1380 // First query the target-specific parser. It will return 'true' if it
1381 // isn't interested in this directive.
1382 if (!getTargetParser().ParseDirective(ID))
1385 // Next, check the extension directive map to see if any extension has
1386 // registered itself to parse this directive.
1387 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1388 ExtensionDirectiveMap.lookup(IDVal);
1390 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1392 // Finally, if no one else is interested in this directive, it must be
1393 // generic and familiar to this class.
1399 return parseDirectiveSet(IDVal, true);
1401 return parseDirectiveSet(IDVal, false);
1403 return parseDirectiveAscii(IDVal, false);
1406 return parseDirectiveAscii(IDVal, true);
1408 return parseDirectiveValue(1);
1412 return parseDirectiveValue(2);
1416 return parseDirectiveValue(4);
1419 return parseDirectiveValue(8);
1421 return parseDirectiveOctaValue();
1424 return parseDirectiveRealValue(APFloat::IEEEsingle);
1426 return parseDirectiveRealValue(APFloat::IEEEdouble);
1428 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1429 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1432 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1433 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1436 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1438 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1440 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1442 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1444 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1446 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1448 return parseDirectiveOrg();
1450 return parseDirectiveFill();
1452 return parseDirectiveZero();
1454 eatToEndOfStatement(); // .extern is the default, ignore it.
1458 return parseDirectiveSymbolAttribute(MCSA_Global);
1459 case DK_LAZY_REFERENCE:
1460 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1461 case DK_NO_DEAD_STRIP:
1462 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1463 case DK_SYMBOL_RESOLVER:
1464 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1465 case DK_PRIVATE_EXTERN:
1466 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1468 return parseDirectiveSymbolAttribute(MCSA_Reference);
1469 case DK_WEAK_DEFINITION:
1470 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1471 case DK_WEAK_REFERENCE:
1472 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1473 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1474 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1477 return parseDirectiveComm(/*IsLocal=*/false);
1479 return parseDirectiveComm(/*IsLocal=*/true);
1481 return parseDirectiveAbort();
1483 return parseDirectiveInclude();
1485 return parseDirectiveIncbin();
1488 return TokError(Twine(IDVal) + " not supported yet");
1490 return parseDirectiveRept(IDLoc, IDVal);
1492 return parseDirectiveIrp(IDLoc);
1494 return parseDirectiveIrpc(IDLoc);
1496 return parseDirectiveEndr(IDLoc);
1497 case DK_BUNDLE_ALIGN_MODE:
1498 return parseDirectiveBundleAlignMode();
1499 case DK_BUNDLE_LOCK:
1500 return parseDirectiveBundleLock();
1501 case DK_BUNDLE_UNLOCK:
1502 return parseDirectiveBundleUnlock();
1504 return parseDirectiveLEB128(true);
1506 return parseDirectiveLEB128(false);
1509 return parseDirectiveSpace(IDVal);
1511 return parseDirectiveFile(IDLoc);
1513 return parseDirectiveLine();
1515 return parseDirectiveLoc();
1517 return parseDirectiveStabs();
1518 case DK_CFI_SECTIONS:
1519 return parseDirectiveCFISections();
1520 case DK_CFI_STARTPROC:
1521 return parseDirectiveCFIStartProc();
1522 case DK_CFI_ENDPROC:
1523 return parseDirectiveCFIEndProc();
1524 case DK_CFI_DEF_CFA:
1525 return parseDirectiveCFIDefCfa(IDLoc);
1526 case DK_CFI_DEF_CFA_OFFSET:
1527 return parseDirectiveCFIDefCfaOffset();
1528 case DK_CFI_ADJUST_CFA_OFFSET:
1529 return parseDirectiveCFIAdjustCfaOffset();
1530 case DK_CFI_DEF_CFA_REGISTER:
1531 return parseDirectiveCFIDefCfaRegister(IDLoc);
1533 return parseDirectiveCFIOffset(IDLoc);
1534 case DK_CFI_REL_OFFSET:
1535 return parseDirectiveCFIRelOffset(IDLoc);
1536 case DK_CFI_PERSONALITY:
1537 return parseDirectiveCFIPersonalityOrLsda(true);
1539 return parseDirectiveCFIPersonalityOrLsda(false);
1540 case DK_CFI_REMEMBER_STATE:
1541 return parseDirectiveCFIRememberState();
1542 case DK_CFI_RESTORE_STATE:
1543 return parseDirectiveCFIRestoreState();
1544 case DK_CFI_SAME_VALUE:
1545 return parseDirectiveCFISameValue(IDLoc);
1546 case DK_CFI_RESTORE:
1547 return parseDirectiveCFIRestore(IDLoc);
1549 return parseDirectiveCFIEscape();
1550 case DK_CFI_SIGNAL_FRAME:
1551 return parseDirectiveCFISignalFrame();
1552 case DK_CFI_UNDEFINED:
1553 return parseDirectiveCFIUndefined(IDLoc);
1554 case DK_CFI_REGISTER:
1555 return parseDirectiveCFIRegister(IDLoc);
1556 case DK_CFI_WINDOW_SAVE:
1557 return parseDirectiveCFIWindowSave();
1560 return parseDirectiveMacrosOnOff(IDVal);
1562 return parseDirectiveMacro(IDLoc);
1564 return parseDirectiveExitMacro(IDVal);
1567 return parseDirectiveEndMacro(IDVal);
1569 return parseDirectivePurgeMacro(IDLoc);
1571 return parseDirectiveEnd(IDLoc);
1573 return parseDirectiveError(IDLoc, false);
1575 return parseDirectiveError(IDLoc, true);
1577 return parseDirectiveWarning(IDLoc);
1580 return Error(IDLoc, "unknown directive");
1583 // __asm _emit or __asm __emit
1584 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1585 IDVal == "_EMIT" || IDVal == "__EMIT"))
1586 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1589 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1590 return parseDirectiveMSAlign(IDLoc, Info);
1592 checkForValidSection();
1594 // Canonicalize the opcode to lower case.
1595 std::string OpcodeStr = IDVal.lower();
1596 ParseInstructionInfo IInfo(Info.AsmRewrites);
1597 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1598 Info.ParsedOperands);
1599 Info.ParseError = HadError;
1601 // Dump the parsed representation, if requested.
1602 if (getShowParsedOperands()) {
1603 SmallString<256> Str;
1604 raw_svector_ostream OS(Str);
1605 OS << "parsed instruction: [";
1606 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1609 Info.ParsedOperands[i]->print(OS);
1613 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1616 // If we are generating dwarf for the current section then generate a .loc
1617 // directive for the instruction.
1618 if (!HadError && getContext().getGenDwarfForAssembly() &&
1619 getContext().getGenDwarfSectionSyms().count(
1620 getStreamer().getCurrentSection().first)) {
1622 if (ActiveMacros.empty())
1623 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1625 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1626 ActiveMacros.back()->ExitBuffer);
1628 // If we previously parsed a cpp hash file line comment then make sure the
1629 // current Dwarf File is for the CppHashFilename if not then emit the
1630 // Dwarf File table for it and adjust the line number for the .loc.
1631 if (CppHashFilename.size()) {
1632 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1633 0, StringRef(), CppHashFilename);
1634 getContext().setGenDwarfFileNumber(FileNumber);
1636 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1637 // cache with the different Loc from the call above we save the last
1638 // info we queried here with SrcMgr.FindLineNumber().
1639 unsigned CppHashLocLineNo;
1640 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1641 CppHashLocLineNo = LastQueryLine;
1643 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1644 LastQueryLine = CppHashLocLineNo;
1645 LastQueryIDLoc = CppHashLoc;
1646 LastQueryBuffer = CppHashBuf;
1648 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1651 getStreamer().EmitDwarfLocDirective(
1652 getContext().getGenDwarfFileNumber(), Line, 0,
1653 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1657 // If parsing succeeded, match the instruction.
1660 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1661 Info.ParsedOperands, Out,
1662 ErrorInfo, ParsingInlineAsm);
1665 // Don't skip the rest of the line, the instruction parser is responsible for
1670 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1671 /// since they may not be able to be tokenized to get to the end of line token.
1672 void AsmParser::eatToEndOfLine() {
1673 if (!Lexer.is(AsmToken::EndOfStatement))
1674 Lexer.LexUntilEndOfLine();
1679 /// parseCppHashLineFilenameComment as this:
1680 /// ::= # number "filename"
1681 /// or just as a full line comment if it doesn't have a number and a string.
1682 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1683 Lex(); // Eat the hash token.
1685 if (getLexer().isNot(AsmToken::Integer)) {
1686 // Consume the line since in cases it is not a well-formed line directive,
1687 // as if were simply a full line comment.
1692 int64_t LineNumber = getTok().getIntVal();
1695 if (getLexer().isNot(AsmToken::String)) {
1700 StringRef Filename = getTok().getString();
1701 // Get rid of the enclosing quotes.
1702 Filename = Filename.substr(1, Filename.size() - 2);
1704 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1706 CppHashFilename = Filename;
1707 CppHashLineNumber = LineNumber;
1708 CppHashBuf = CurBuffer;
1710 // Ignore any trailing characters, they're just comment.
1715 /// \brief will use the last parsed cpp hash line filename comment
1716 /// for the Filename and LineNo if any in the diagnostic.
1717 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1718 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1719 raw_ostream &OS = errs();
1721 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1722 const SMLoc &DiagLoc = Diag.getLoc();
1723 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1724 unsigned CppHashBuf =
1725 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1727 // Like SourceMgr::printMessage() we need to print the include stack if any
1728 // before printing the message.
1729 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1730 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1731 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1732 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1733 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1736 // If we have not parsed a cpp hash line filename comment or the source
1737 // manager changed or buffer changed (like in a nested include) then just
1738 // print the normal diagnostic using its Filename and LineNo.
1739 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1740 DiagBuf != CppHashBuf) {
1741 if (Parser->SavedDiagHandler)
1742 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1744 Diag.print(nullptr, OS);
1748 // Use the CppHashFilename and calculate a line number based on the
1749 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1751 const std::string &Filename = Parser->CppHashFilename;
1753 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1754 int CppHashLocLineNo =
1755 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1757 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1759 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1760 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1761 Diag.getLineContents(), Diag.getRanges());
1763 if (Parser->SavedDiagHandler)
1764 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1766 NewDiag.print(nullptr, OS);
1769 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1770 // difference being that that function accepts '@' as part of identifiers and
1771 // we can't do that. AsmLexer.cpp should probably be changed to handle
1772 // '@' as a special case when needed.
1773 static bool isIdentifierChar(char c) {
1774 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1778 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1779 ArrayRef<MCAsmMacroParameter> Parameters,
1780 ArrayRef<MCAsmMacroArgument> A,
1781 bool EnableAtPseudoVariable, const SMLoc &L) {
1782 unsigned NParameters = Parameters.size();
1783 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1784 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1785 return Error(L, "Wrong number of arguments");
1787 // A macro without parameters is handled differently on Darwin:
1788 // gas accepts no arguments and does no substitutions
1789 while (!Body.empty()) {
1790 // Scan for the next substitution.
1791 std::size_t End = Body.size(), Pos = 0;
1792 for (; Pos != End; ++Pos) {
1793 // Check for a substitution or escape.
1794 if (IsDarwin && !NParameters) {
1795 // This macro has no parameters, look for $0, $1, etc.
1796 if (Body[Pos] != '$' || Pos + 1 == End)
1799 char Next = Body[Pos + 1];
1800 if (Next == '$' || Next == 'n' ||
1801 isdigit(static_cast<unsigned char>(Next)))
1804 // This macro has parameters, look for \foo, \bar, etc.
1805 if (Body[Pos] == '\\' && Pos + 1 != End)
1811 OS << Body.slice(0, Pos);
1813 // Check if we reached the end.
1817 if (IsDarwin && !NParameters) {
1818 switch (Body[Pos + 1]) {
1824 // $n => number of arguments
1829 // $[0-9] => argument
1831 // Missing arguments are ignored.
1832 unsigned Index = Body[Pos + 1] - '0';
1833 if (Index >= A.size())
1836 // Otherwise substitute with the token values, with spaces eliminated.
1837 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1838 ie = A[Index].end();
1840 OS << it->getString();
1846 unsigned I = Pos + 1;
1848 // Check for the \@ pseudo-variable.
1849 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1852 while (isIdentifierChar(Body[I]) && I + 1 != End)
1855 const char *Begin = Body.data() + Pos + 1;
1856 StringRef Argument(Begin, I - (Pos + 1));
1859 if (Argument == "@") {
1860 OS << NumOfMacroInstantiations;
1863 for (; Index < NParameters; ++Index)
1864 if (Parameters[Index].Name == Argument)
1867 if (Index == NParameters) {
1868 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1871 OS << '\\' << Argument;
1875 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1876 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1877 ie = A[Index].end();
1879 // We expect no quotes around the string's contents when
1880 // parsing for varargs.
1881 if (it->getKind() != AsmToken::String || VarargParameter)
1882 OS << it->getString();
1884 OS << it->getStringContents();
1886 Pos += 1 + Argument.size();
1890 // Update the scan point.
1891 Body = Body.substr(Pos);
1897 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1898 size_t CondStackDepth)
1899 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1900 CondStackDepth(CondStackDepth) {}
1902 static bool isOperator(AsmToken::TokenKind kind) {
1906 case AsmToken::Plus:
1907 case AsmToken::Minus:
1908 case AsmToken::Tilde:
1909 case AsmToken::Slash:
1910 case AsmToken::Star:
1912 case AsmToken::Equal:
1913 case AsmToken::EqualEqual:
1914 case AsmToken::Pipe:
1915 case AsmToken::PipePipe:
1916 case AsmToken::Caret:
1918 case AsmToken::AmpAmp:
1919 case AsmToken::Exclaim:
1920 case AsmToken::ExclaimEqual:
1921 case AsmToken::Percent:
1922 case AsmToken::Less:
1923 case AsmToken::LessEqual:
1924 case AsmToken::LessLess:
1925 case AsmToken::LessGreater:
1926 case AsmToken::Greater:
1927 case AsmToken::GreaterEqual:
1928 case AsmToken::GreaterGreater:
1934 class AsmLexerSkipSpaceRAII {
1936 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1937 Lexer.setSkipSpace(SkipSpace);
1940 ~AsmLexerSkipSpaceRAII() {
1941 Lexer.setSkipSpace(true);
1949 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1952 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1953 StringRef Str = parseStringToEndOfStatement();
1954 MA.emplace_back(AsmToken::String, Str);
1959 unsigned ParenLevel = 0;
1960 unsigned AddTokens = 0;
1962 // Darwin doesn't use spaces to delmit arguments.
1963 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1966 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1967 return TokError("unexpected token in macro instantiation");
1969 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1972 if (Lexer.is(AsmToken::Space)) {
1973 Lex(); // Eat spaces
1975 // Spaces can delimit parameters, but could also be part an expression.
1976 // If the token after a space is an operator, add the token and the next
1977 // one into this argument
1979 if (isOperator(Lexer.getKind())) {
1980 // Check to see whether the token is used as an operator,
1981 // or part of an identifier
1982 const char *NextChar = getTok().getEndLoc().getPointer();
1983 if (*NextChar == ' ')
1987 if (!AddTokens && ParenLevel == 0) {
1993 // handleMacroEntry relies on not advancing the lexer here
1994 // to be able to fill in the remaining default parameter values
1995 if (Lexer.is(AsmToken::EndOfStatement))
1998 // Adjust the current parentheses level.
1999 if (Lexer.is(AsmToken::LParen))
2001 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2004 // Append the token to the current argument list.
2005 MA.push_back(getTok());
2011 if (ParenLevel != 0)
2012 return TokError("unbalanced parentheses in macro argument");
2016 // Parse the macro instantiation arguments.
2017 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2018 MCAsmMacroArguments &A) {
2019 const unsigned NParameters = M ? M->Parameters.size() : 0;
2020 bool NamedParametersFound = false;
2021 SmallVector<SMLoc, 4> FALocs;
2023 A.resize(NParameters);
2024 FALocs.resize(NParameters);
2026 // Parse two kinds of macro invocations:
2027 // - macros defined without any parameters accept an arbitrary number of them
2028 // - macros defined with parameters accept at most that many of them
2029 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2030 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2032 SMLoc IDLoc = Lexer.getLoc();
2033 MCAsmMacroParameter FA;
2035 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2036 if (parseIdentifier(FA.Name)) {
2037 Error(IDLoc, "invalid argument identifier for formal argument");
2038 eatToEndOfStatement();
2042 if (!Lexer.is(AsmToken::Equal)) {
2043 TokError("expected '=' after formal parameter identifier");
2044 eatToEndOfStatement();
2049 NamedParametersFound = true;
2052 if (NamedParametersFound && FA.Name.empty()) {
2053 Error(IDLoc, "cannot mix positional and keyword arguments");
2054 eatToEndOfStatement();
2058 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2059 if (parseMacroArgument(FA.Value, Vararg))
2062 unsigned PI = Parameter;
2063 if (!FA.Name.empty()) {
2065 for (FAI = 0; FAI < NParameters; ++FAI)
2066 if (M->Parameters[FAI].Name == FA.Name)
2069 if (FAI >= NParameters) {
2070 assert(M && "expected macro to be defined");
2072 "parameter named '" + FA.Name + "' does not exist for macro '" +
2079 if (!FA.Value.empty()) {
2084 if (FALocs.size() <= PI)
2085 FALocs.resize(PI + 1);
2087 FALocs[PI] = Lexer.getLoc();
2090 // At the end of the statement, fill in remaining arguments that have
2091 // default values. If there aren't any, then the next argument is
2092 // required but missing
2093 if (Lexer.is(AsmToken::EndOfStatement)) {
2094 bool Failure = false;
2095 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2096 if (A[FAI].empty()) {
2097 if (M->Parameters[FAI].Required) {
2098 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2099 "missing value for required parameter "
2100 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2104 if (!M->Parameters[FAI].Value.empty())
2105 A[FAI] = M->Parameters[FAI].Value;
2111 if (Lexer.is(AsmToken::Comma))
2115 return TokError("too many positional arguments");
2118 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2119 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2120 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2123 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2124 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2127 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2129 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2130 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2131 // this, although we should protect against infinite loops.
2132 if (ActiveMacros.size() == 20)
2133 return TokError("macros cannot be nested more than 20 levels deep");
2135 MCAsmMacroArguments A;
2136 if (parseMacroArguments(M, A))
2139 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2140 // to hold the macro body with substitutions.
2141 SmallString<256> Buf;
2142 StringRef Body = M->Body;
2143 raw_svector_ostream OS(Buf);
2145 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2148 // We include the .endmacro in the buffer as our cue to exit the macro
2150 OS << ".endmacro\n";
2152 std::unique_ptr<MemoryBuffer> Instantiation =
2153 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2155 // Create the macro instantiation object and add to the current macro
2156 // instantiation stack.
2157 MacroInstantiation *MI = new MacroInstantiation(
2158 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2159 ActiveMacros.push_back(MI);
2161 ++NumOfMacroInstantiations;
2163 // Jump to the macro instantiation and prime the lexer.
2164 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2165 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2171 void AsmParser::handleMacroExit() {
2172 // Jump to the EndOfStatement we should return to, and consume it.
2173 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2176 // Pop the instantiation entry.
2177 delete ActiveMacros.back();
2178 ActiveMacros.pop_back();
2181 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2182 switch (Value->getKind()) {
2183 case MCExpr::Binary: {
2184 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2185 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2187 case MCExpr::Target:
2188 case MCExpr::Constant:
2190 case MCExpr::SymbolRef: {
2192 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2194 return isUsedIn(Sym, S.getVariableValue());
2198 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2201 llvm_unreachable("Unknown expr kind!");
2204 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2206 // FIXME: Use better location, we should use proper tokens.
2207 SMLoc EqualLoc = Lexer.getLoc();
2209 const MCExpr *Value;
2210 if (parseExpression(Value))
2213 // Note: we don't count b as used in "a = b". This is to allow
2217 if (Lexer.isNot(AsmToken::EndOfStatement))
2218 return TokError("unexpected token in assignment");
2220 // Eat the end of statement marker.
2223 // Validate that the LHS is allowed to be a variable (either it has not been
2224 // used as a symbol, or it is an absolute symbol).
2225 MCSymbol *Sym = getContext().lookupSymbol(Name);
2227 // Diagnose assignment to a label.
2229 // FIXME: Diagnostics. Note the location of the definition as a label.
2230 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2231 if (isUsedIn(Sym, Value))
2232 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2233 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2234 ; // Allow redefinitions of undefined symbols only used in directives.
2235 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2236 ; // Allow redefinitions of variables that haven't yet been used.
2237 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2238 return Error(EqualLoc, "redefinition of '" + Name + "'");
2239 else if (!Sym->isVariable())
2240 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2241 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2242 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2245 // Don't count these checks as uses.
2246 Sym->setUsed(false);
2247 } else if (Name == ".") {
2248 if (Out.EmitValueToOffset(Value, 0)) {
2249 Error(EqualLoc, "expected absolute expression");
2250 eatToEndOfStatement();
2254 Sym = getContext().getOrCreateSymbol(Name);
2256 Sym->setRedefinable(allow_redef);
2258 // Do the assignment.
2259 Out.EmitAssignment(Sym, Value);
2261 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2266 /// parseIdentifier:
2269 bool AsmParser::parseIdentifier(StringRef &Res) {
2270 // The assembler has relaxed rules for accepting identifiers, in particular we
2271 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2272 // separate tokens. At this level, we have already lexed so we cannot (currently)
2273 // handle this as a context dependent token, instead we detect adjacent tokens
2274 // and return the combined identifier.
2275 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2276 SMLoc PrefixLoc = getLexer().getLoc();
2278 // Consume the prefix character, and check for a following identifier.
2280 if (Lexer.isNot(AsmToken::Identifier))
2283 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2284 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2287 // Construct the joined identifier and consume the token.
2289 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2294 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2297 Res = getTok().getIdentifier();
2299 Lex(); // Consume the identifier token.
2304 /// parseDirectiveSet:
2305 /// ::= .equ identifier ',' expression
2306 /// ::= .equiv identifier ',' expression
2307 /// ::= .set identifier ',' expression
2308 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2311 if (parseIdentifier(Name))
2312 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2314 if (getLexer().isNot(AsmToken::Comma))
2315 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2318 return parseAssignment(Name, allow_redef, true);
2321 bool AsmParser::parseEscapedString(std::string &Data) {
2322 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2325 StringRef Str = getTok().getStringContents();
2326 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2327 if (Str[i] != '\\') {
2332 // Recognize escaped characters. Note that this escape semantics currently
2333 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2336 return TokError("unexpected backslash at end of string");
2338 // Recognize octal sequences.
2339 if ((unsigned)(Str[i] - '0') <= 7) {
2340 // Consume up to three octal characters.
2341 unsigned Value = Str[i] - '0';
2343 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2345 Value = Value * 8 + (Str[i] - '0');
2347 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2349 Value = Value * 8 + (Str[i] - '0');
2354 return TokError("invalid octal escape sequence (out of range)");
2356 Data += (unsigned char)Value;
2360 // Otherwise recognize individual escapes.
2363 // Just reject invalid escape sequences for now.
2364 return TokError("invalid escape sequence (unrecognized character)");
2366 case 'b': Data += '\b'; break;
2367 case 'f': Data += '\f'; break;
2368 case 'n': Data += '\n'; break;
2369 case 'r': Data += '\r'; break;
2370 case 't': Data += '\t'; break;
2371 case '"': Data += '"'; break;
2372 case '\\': Data += '\\'; break;
2379 /// parseDirectiveAscii:
2380 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2381 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2382 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2383 checkForValidSection();
2386 if (getLexer().isNot(AsmToken::String))
2387 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2390 if (parseEscapedString(Data))
2393 getStreamer().EmitBytes(Data);
2395 getStreamer().EmitBytes(StringRef("\0", 1));
2399 if (getLexer().is(AsmToken::EndOfStatement))
2402 if (getLexer().isNot(AsmToken::Comma))
2403 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2412 /// parseDirectiveValue
2413 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2414 bool AsmParser::parseDirectiveValue(unsigned Size) {
2415 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2416 checkForValidSection();
2419 const MCExpr *Value;
2420 SMLoc ExprLoc = getLexer().getLoc();
2421 if (parseExpression(Value))
2424 // Special case constant expressions to match code generator.
2425 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2426 assert(Size <= 8 && "Invalid size");
2427 uint64_t IntValue = MCE->getValue();
2428 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2429 return Error(ExprLoc, "literal value out of range for directive");
2430 getStreamer().EmitIntValue(IntValue, Size);
2432 getStreamer().EmitValue(Value, Size, ExprLoc);
2434 if (getLexer().is(AsmToken::EndOfStatement))
2437 // FIXME: Improve diagnostic.
2438 if (getLexer().isNot(AsmToken::Comma))
2439 return TokError("unexpected token in directive");
2448 /// ParseDirectiveOctaValue
2449 /// ::= .octa [ hexconstant (, hexconstant)* ]
2450 bool AsmParser::parseDirectiveOctaValue() {
2451 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2452 checkForValidSection();
2455 if (Lexer.getKind() == AsmToken::Error)
2457 if (Lexer.getKind() != AsmToken::Integer &&
2458 Lexer.getKind() != AsmToken::BigNum)
2459 return TokError("unknown token in expression");
2461 SMLoc ExprLoc = getLexer().getLoc();
2462 APInt IntValue = getTok().getAPIntVal();
2466 if (IntValue.isIntN(64)) {
2468 lo = IntValue.getZExtValue();
2469 } else if (IntValue.isIntN(128)) {
2470 // It might actually have more than 128 bits, but the top ones are zero.
2471 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2472 lo = IntValue.getLoBits(64).getZExtValue();
2474 return Error(ExprLoc, "literal value out of range for directive");
2476 if (MAI.isLittleEndian()) {
2477 getStreamer().EmitIntValue(lo, 8);
2478 getStreamer().EmitIntValue(hi, 8);
2480 getStreamer().EmitIntValue(hi, 8);
2481 getStreamer().EmitIntValue(lo, 8);
2484 if (getLexer().is(AsmToken::EndOfStatement))
2487 // FIXME: Improve diagnostic.
2488 if (getLexer().isNot(AsmToken::Comma))
2489 return TokError("unexpected token in directive");
2498 /// parseDirectiveRealValue
2499 /// ::= (.single | .double) [ expression (, expression)* ]
2500 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2501 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2502 checkForValidSection();
2505 // We don't truly support arithmetic on floating point expressions, so we
2506 // have to manually parse unary prefixes.
2508 if (getLexer().is(AsmToken::Minus)) {
2511 } else if (getLexer().is(AsmToken::Plus))
2514 if (getLexer().isNot(AsmToken::Integer) &&
2515 getLexer().isNot(AsmToken::Real) &&
2516 getLexer().isNot(AsmToken::Identifier))
2517 return TokError("unexpected token in directive");
2519 // Convert to an APFloat.
2520 APFloat Value(Semantics);
2521 StringRef IDVal = getTok().getString();
2522 if (getLexer().is(AsmToken::Identifier)) {
2523 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2524 Value = APFloat::getInf(Semantics);
2525 else if (!IDVal.compare_lower("nan"))
2526 Value = APFloat::getNaN(Semantics, false, ~0);
2528 return TokError("invalid floating point literal");
2529 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2530 APFloat::opInvalidOp)
2531 return TokError("invalid floating point literal");
2535 // Consume the numeric token.
2538 // Emit the value as an integer.
2539 APInt AsInt = Value.bitcastToAPInt();
2540 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2541 AsInt.getBitWidth() / 8);
2543 if (getLexer().is(AsmToken::EndOfStatement))
2546 if (getLexer().isNot(AsmToken::Comma))
2547 return TokError("unexpected token in directive");
2556 /// parseDirectiveZero
2557 /// ::= .zero expression
2558 bool AsmParser::parseDirectiveZero() {
2559 checkForValidSection();
2562 if (parseAbsoluteExpression(NumBytes))
2566 if (getLexer().is(AsmToken::Comma)) {
2568 if (parseAbsoluteExpression(Val))
2572 if (getLexer().isNot(AsmToken::EndOfStatement))
2573 return TokError("unexpected token in '.zero' directive");
2577 getStreamer().EmitFill(NumBytes, Val);
2582 /// parseDirectiveFill
2583 /// ::= .fill expression [ , expression [ , expression ] ]
2584 bool AsmParser::parseDirectiveFill() {
2585 checkForValidSection();
2587 SMLoc RepeatLoc = getLexer().getLoc();
2589 if (parseAbsoluteExpression(NumValues))
2592 if (NumValues < 0) {
2594 "'.fill' directive with negative repeat count has no effect");
2598 int64_t FillSize = 1;
2599 int64_t FillExpr = 0;
2601 SMLoc SizeLoc, ExprLoc;
2602 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2603 if (getLexer().isNot(AsmToken::Comma))
2604 return TokError("unexpected token in '.fill' directive");
2607 SizeLoc = getLexer().getLoc();
2608 if (parseAbsoluteExpression(FillSize))
2611 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2612 if (getLexer().isNot(AsmToken::Comma))
2613 return TokError("unexpected token in '.fill' directive");
2616 ExprLoc = getLexer().getLoc();
2617 if (parseAbsoluteExpression(FillExpr))
2620 if (getLexer().isNot(AsmToken::EndOfStatement))
2621 return TokError("unexpected token in '.fill' directive");
2628 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2632 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2636 if (!isUInt<32>(FillExpr) && FillSize > 4)
2637 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2639 if (NumValues > 0) {
2640 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2641 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2642 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2643 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2644 if (NonZeroFillSize < FillSize)
2645 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2652 /// parseDirectiveOrg
2653 /// ::= .org expression [ , expression ]
2654 bool AsmParser::parseDirectiveOrg() {
2655 checkForValidSection();
2657 const MCExpr *Offset;
2658 SMLoc Loc = getTok().getLoc();
2659 if (parseExpression(Offset))
2662 // Parse optional fill expression.
2663 int64_t FillExpr = 0;
2664 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2665 if (getLexer().isNot(AsmToken::Comma))
2666 return TokError("unexpected token in '.org' directive");
2669 if (parseAbsoluteExpression(FillExpr))
2672 if (getLexer().isNot(AsmToken::EndOfStatement))
2673 return TokError("unexpected token in '.org' directive");
2678 // Only limited forms of relocatable expressions are accepted here, it
2679 // has to be relative to the current section. The streamer will return
2680 // 'true' if the expression wasn't evaluatable.
2681 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2682 return Error(Loc, "expected assembly-time absolute expression");
2687 /// parseDirectiveAlign
2688 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2689 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2690 checkForValidSection();
2692 SMLoc AlignmentLoc = getLexer().getLoc();
2694 if (parseAbsoluteExpression(Alignment))
2698 bool HasFillExpr = false;
2699 int64_t FillExpr = 0;
2700 int64_t MaxBytesToFill = 0;
2701 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2702 if (getLexer().isNot(AsmToken::Comma))
2703 return TokError("unexpected token in directive");
2706 // The fill expression can be omitted while specifying a maximum number of
2707 // alignment bytes, e.g:
2709 if (getLexer().isNot(AsmToken::Comma)) {
2711 if (parseAbsoluteExpression(FillExpr))
2715 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2716 if (getLexer().isNot(AsmToken::Comma))
2717 return TokError("unexpected token in directive");
2720 MaxBytesLoc = getLexer().getLoc();
2721 if (parseAbsoluteExpression(MaxBytesToFill))
2724 if (getLexer().isNot(AsmToken::EndOfStatement))
2725 return TokError("unexpected token in directive");
2734 // Compute alignment in bytes.
2736 // FIXME: Diagnose overflow.
2737 if (Alignment >= 32) {
2738 Error(AlignmentLoc, "invalid alignment value");
2742 Alignment = 1ULL << Alignment;
2744 // Reject alignments that aren't a power of two, for gas compatibility.
2745 if (!isPowerOf2_64(Alignment))
2746 Error(AlignmentLoc, "alignment must be a power of 2");
2749 // Diagnose non-sensical max bytes to align.
2750 if (MaxBytesLoc.isValid()) {
2751 if (MaxBytesToFill < 1) {
2752 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2753 "many bytes, ignoring maximum bytes expression");
2757 if (MaxBytesToFill >= Alignment) {
2758 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2764 // Check whether we should use optimal code alignment for this .align
2766 const MCSection *Section = getStreamer().getCurrentSection().first;
2767 assert(Section && "must have section to emit alignment");
2768 bool UseCodeAlign = Section->UseCodeAlign();
2769 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2770 ValueSize == 1 && UseCodeAlign) {
2771 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2773 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2774 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2781 /// parseDirectiveFile
2782 /// ::= .file [number] filename
2783 /// ::= .file number directory filename
2784 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2785 // FIXME: I'm not sure what this is.
2786 int64_t FileNumber = -1;
2787 SMLoc FileNumberLoc = getLexer().getLoc();
2788 if (getLexer().is(AsmToken::Integer)) {
2789 FileNumber = getTok().getIntVal();
2793 return TokError("file number less than one");
2796 if (getLexer().isNot(AsmToken::String))
2797 return TokError("unexpected token in '.file' directive");
2799 // Usually the directory and filename together, otherwise just the directory.
2800 // Allow the strings to have escaped octal character sequence.
2801 std::string Path = getTok().getString();
2802 if (parseEscapedString(Path))
2806 StringRef Directory;
2808 std::string FilenameData;
2809 if (getLexer().is(AsmToken::String)) {
2810 if (FileNumber == -1)
2811 return TokError("explicit path specified, but no file number");
2812 if (parseEscapedString(FilenameData))
2814 Filename = FilenameData;
2821 if (getLexer().isNot(AsmToken::EndOfStatement))
2822 return TokError("unexpected token in '.file' directive");
2824 if (FileNumber == -1)
2825 getStreamer().EmitFileDirective(Filename);
2827 if (getContext().getGenDwarfForAssembly())
2829 "input can't have .file dwarf directives when -g is "
2830 "used to generate dwarf debug info for assembly code");
2832 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2834 Error(FileNumberLoc, "file number already allocated");
2840 /// parseDirectiveLine
2841 /// ::= .line [number]
2842 bool AsmParser::parseDirectiveLine() {
2843 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2844 if (getLexer().isNot(AsmToken::Integer))
2845 return TokError("unexpected token in '.line' directive");
2847 int64_t LineNumber = getTok().getIntVal();
2851 // FIXME: Do something with the .line.
2854 if (getLexer().isNot(AsmToken::EndOfStatement))
2855 return TokError("unexpected token in '.line' directive");
2860 /// parseDirectiveLoc
2861 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2862 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2863 /// The first number is a file number, must have been previously assigned with
2864 /// a .file directive, the second number is the line number and optionally the
2865 /// third number is a column position (zero if not specified). The remaining
2866 /// optional items are .loc sub-directives.
2867 bool AsmParser::parseDirectiveLoc() {
2868 if (getLexer().isNot(AsmToken::Integer))
2869 return TokError("unexpected token in '.loc' directive");
2870 int64_t FileNumber = getTok().getIntVal();
2872 return TokError("file number less than one in '.loc' directive");
2873 if (!getContext().isValidDwarfFileNumber(FileNumber))
2874 return TokError("unassigned file number in '.loc' directive");
2877 int64_t LineNumber = 0;
2878 if (getLexer().is(AsmToken::Integer)) {
2879 LineNumber = getTok().getIntVal();
2881 return TokError("line number less than zero in '.loc' directive");
2885 int64_t ColumnPos = 0;
2886 if (getLexer().is(AsmToken::Integer)) {
2887 ColumnPos = getTok().getIntVal();
2889 return TokError("column position less than zero in '.loc' directive");
2893 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2895 int64_t Discriminator = 0;
2896 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2898 if (getLexer().is(AsmToken::EndOfStatement))
2902 SMLoc Loc = getTok().getLoc();
2903 if (parseIdentifier(Name))
2904 return TokError("unexpected token in '.loc' directive");
2906 if (Name == "basic_block")
2907 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2908 else if (Name == "prologue_end")
2909 Flags |= DWARF2_FLAG_PROLOGUE_END;
2910 else if (Name == "epilogue_begin")
2911 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2912 else if (Name == "is_stmt") {
2913 Loc = getTok().getLoc();
2914 const MCExpr *Value;
2915 if (parseExpression(Value))
2917 // The expression must be the constant 0 or 1.
2918 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2919 int Value = MCE->getValue();
2921 Flags &= ~DWARF2_FLAG_IS_STMT;
2922 else if (Value == 1)
2923 Flags |= DWARF2_FLAG_IS_STMT;
2925 return Error(Loc, "is_stmt value not 0 or 1");
2927 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2929 } else if (Name == "isa") {
2930 Loc = getTok().getLoc();
2931 const MCExpr *Value;
2932 if (parseExpression(Value))
2934 // The expression must be a constant greater or equal to 0.
2935 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2936 int Value = MCE->getValue();
2938 return Error(Loc, "isa number less than zero");
2941 return Error(Loc, "isa number not a constant value");
2943 } else if (Name == "discriminator") {
2944 if (parseAbsoluteExpression(Discriminator))
2947 return Error(Loc, "unknown sub-directive in '.loc' directive");
2950 if (getLexer().is(AsmToken::EndOfStatement))
2955 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2956 Isa, Discriminator, StringRef());
2961 /// parseDirectiveStabs
2962 /// ::= .stabs string, number, number, number
2963 bool AsmParser::parseDirectiveStabs() {
2964 return TokError("unsupported directive '.stabs'");
2967 /// parseDirectiveCFISections
2968 /// ::= .cfi_sections section [, section]
2969 bool AsmParser::parseDirectiveCFISections() {
2974 if (parseIdentifier(Name))
2975 return TokError("Expected an identifier");
2977 if (Name == ".eh_frame")
2979 else if (Name == ".debug_frame")
2982 if (getLexer().is(AsmToken::Comma)) {
2985 if (parseIdentifier(Name))
2986 return TokError("Expected an identifier");
2988 if (Name == ".eh_frame")
2990 else if (Name == ".debug_frame")
2994 getStreamer().EmitCFISections(EH, Debug);
2998 /// parseDirectiveCFIStartProc
2999 /// ::= .cfi_startproc [simple]
3000 bool AsmParser::parseDirectiveCFIStartProc() {
3002 if (getLexer().isNot(AsmToken::EndOfStatement))
3003 if (parseIdentifier(Simple) || Simple != "simple")
3004 return TokError("unexpected token in .cfi_startproc directive");
3006 getStreamer().EmitCFIStartProc(!Simple.empty());
3010 /// parseDirectiveCFIEndProc
3011 /// ::= .cfi_endproc
3012 bool AsmParser::parseDirectiveCFIEndProc() {
3013 getStreamer().EmitCFIEndProc();
3017 /// \brief parse register name or number.
3018 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3019 SMLoc DirectiveLoc) {
3022 if (getLexer().isNot(AsmToken::Integer)) {
3023 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3025 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3027 return parseAbsoluteExpression(Register);
3032 /// parseDirectiveCFIDefCfa
3033 /// ::= .cfi_def_cfa register, offset
3034 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3035 int64_t Register = 0;
3036 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3039 if (getLexer().isNot(AsmToken::Comma))
3040 return TokError("unexpected token in directive");
3044 if (parseAbsoluteExpression(Offset))
3047 getStreamer().EmitCFIDefCfa(Register, Offset);
3051 /// parseDirectiveCFIDefCfaOffset
3052 /// ::= .cfi_def_cfa_offset offset
3053 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3055 if (parseAbsoluteExpression(Offset))
3058 getStreamer().EmitCFIDefCfaOffset(Offset);
3062 /// parseDirectiveCFIRegister
3063 /// ::= .cfi_register register, register
3064 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3065 int64_t Register1 = 0;
3066 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3069 if (getLexer().isNot(AsmToken::Comma))
3070 return TokError("unexpected token in directive");
3073 int64_t Register2 = 0;
3074 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3077 getStreamer().EmitCFIRegister(Register1, Register2);
3081 /// parseDirectiveCFIWindowSave
3082 /// ::= .cfi_window_save
3083 bool AsmParser::parseDirectiveCFIWindowSave() {
3084 getStreamer().EmitCFIWindowSave();
3088 /// parseDirectiveCFIAdjustCfaOffset
3089 /// ::= .cfi_adjust_cfa_offset adjustment
3090 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3091 int64_t Adjustment = 0;
3092 if (parseAbsoluteExpression(Adjustment))
3095 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3099 /// parseDirectiveCFIDefCfaRegister
3100 /// ::= .cfi_def_cfa_register register
3101 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3102 int64_t Register = 0;
3103 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3106 getStreamer().EmitCFIDefCfaRegister(Register);
3110 /// parseDirectiveCFIOffset
3111 /// ::= .cfi_offset register, offset
3112 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3113 int64_t Register = 0;
3116 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3119 if (getLexer().isNot(AsmToken::Comma))
3120 return TokError("unexpected token in directive");
3123 if (parseAbsoluteExpression(Offset))
3126 getStreamer().EmitCFIOffset(Register, Offset);
3130 /// parseDirectiveCFIRelOffset
3131 /// ::= .cfi_rel_offset register, offset
3132 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3133 int64_t Register = 0;
3135 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3138 if (getLexer().isNot(AsmToken::Comma))
3139 return TokError("unexpected token in directive");
3143 if (parseAbsoluteExpression(Offset))
3146 getStreamer().EmitCFIRelOffset(Register, Offset);
3150 static bool isValidEncoding(int64_t Encoding) {
3151 if (Encoding & ~0xff)
3154 if (Encoding == dwarf::DW_EH_PE_omit)
3157 const unsigned Format = Encoding & 0xf;
3158 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3159 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3160 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3161 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3164 const unsigned Application = Encoding & 0x70;
3165 if (Application != dwarf::DW_EH_PE_absptr &&
3166 Application != dwarf::DW_EH_PE_pcrel)
3172 /// parseDirectiveCFIPersonalityOrLsda
3173 /// IsPersonality true for cfi_personality, false for cfi_lsda
3174 /// ::= .cfi_personality encoding, [symbol_name]
3175 /// ::= .cfi_lsda encoding, [symbol_name]
3176 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3177 int64_t Encoding = 0;
3178 if (parseAbsoluteExpression(Encoding))
3180 if (Encoding == dwarf::DW_EH_PE_omit)
3183 if (!isValidEncoding(Encoding))
3184 return TokError("unsupported encoding.");
3186 if (getLexer().isNot(AsmToken::Comma))
3187 return TokError("unexpected token in directive");
3191 if (parseIdentifier(Name))
3192 return TokError("expected identifier in directive");
3194 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3197 getStreamer().EmitCFIPersonality(Sym, Encoding);
3199 getStreamer().EmitCFILsda(Sym, Encoding);
3203 /// parseDirectiveCFIRememberState
3204 /// ::= .cfi_remember_state
3205 bool AsmParser::parseDirectiveCFIRememberState() {
3206 getStreamer().EmitCFIRememberState();
3210 /// parseDirectiveCFIRestoreState
3211 /// ::= .cfi_remember_state
3212 bool AsmParser::parseDirectiveCFIRestoreState() {
3213 getStreamer().EmitCFIRestoreState();
3217 /// parseDirectiveCFISameValue
3218 /// ::= .cfi_same_value register
3219 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3220 int64_t Register = 0;
3222 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3225 getStreamer().EmitCFISameValue(Register);
3229 /// parseDirectiveCFIRestore
3230 /// ::= .cfi_restore register
3231 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3232 int64_t Register = 0;
3233 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3236 getStreamer().EmitCFIRestore(Register);
3240 /// parseDirectiveCFIEscape
3241 /// ::= .cfi_escape expression[,...]
3242 bool AsmParser::parseDirectiveCFIEscape() {
3245 if (parseAbsoluteExpression(CurrValue))
3248 Values.push_back((uint8_t)CurrValue);
3250 while (getLexer().is(AsmToken::Comma)) {
3253 if (parseAbsoluteExpression(CurrValue))
3256 Values.push_back((uint8_t)CurrValue);
3259 getStreamer().EmitCFIEscape(Values);
3263 /// parseDirectiveCFISignalFrame
3264 /// ::= .cfi_signal_frame
3265 bool AsmParser::parseDirectiveCFISignalFrame() {
3266 if (getLexer().isNot(AsmToken::EndOfStatement))
3267 return Error(getLexer().getLoc(),
3268 "unexpected token in '.cfi_signal_frame'");
3270 getStreamer().EmitCFISignalFrame();
3274 /// parseDirectiveCFIUndefined
3275 /// ::= .cfi_undefined register
3276 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3277 int64_t Register = 0;
3279 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3282 getStreamer().EmitCFIUndefined(Register);
3286 /// parseDirectiveMacrosOnOff
3289 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3290 if (getLexer().isNot(AsmToken::EndOfStatement))
3291 return Error(getLexer().getLoc(),
3292 "unexpected token in '" + Directive + "' directive");
3294 setMacrosEnabled(Directive == ".macros_on");
3298 /// parseDirectiveMacro
3299 /// ::= .macro name[,] [parameters]
3300 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3302 if (parseIdentifier(Name))
3303 return TokError("expected identifier in '.macro' directive");
3305 if (getLexer().is(AsmToken::Comma))
3308 MCAsmMacroParameters Parameters;
3309 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3311 if (!Parameters.empty() && Parameters.back().Vararg)
3312 return Error(Lexer.getLoc(),
3313 "Vararg parameter '" + Parameters.back().Name +
3314 "' should be last one in the list of parameters.");
3316 MCAsmMacroParameter Parameter;
3317 if (parseIdentifier(Parameter.Name))
3318 return TokError("expected identifier in '.macro' directive");
3320 if (Lexer.is(AsmToken::Colon)) {
3321 Lex(); // consume ':'
3324 StringRef Qualifier;
3326 QualLoc = Lexer.getLoc();
3327 if (parseIdentifier(Qualifier))
3328 return Error(QualLoc, "missing parameter qualifier for "
3329 "'" + Parameter.Name + "' in macro '" + Name + "'");
3331 if (Qualifier == "req")
3332 Parameter.Required = true;
3333 else if (Qualifier == "vararg")
3334 Parameter.Vararg = true;
3336 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3337 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3340 if (getLexer().is(AsmToken::Equal)) {
3345 ParamLoc = Lexer.getLoc();
3346 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3349 if (Parameter.Required)
3350 Warning(ParamLoc, "pointless default value for required parameter "
3351 "'" + Parameter.Name + "' in macro '" + Name + "'");
3354 Parameters.push_back(std::move(Parameter));
3356 if (getLexer().is(AsmToken::Comma))
3360 // Eat the end of statement.
3363 AsmToken EndToken, StartToken = getTok();
3364 unsigned MacroDepth = 0;
3366 // Lex the macro definition.
3368 // Check whether we have reached the end of the file.
3369 if (getLexer().is(AsmToken::Eof))
3370 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3372 // Otherwise, check whether we have reach the .endmacro.
3373 if (getLexer().is(AsmToken::Identifier)) {
3374 if (getTok().getIdentifier() == ".endm" ||
3375 getTok().getIdentifier() == ".endmacro") {
3376 if (MacroDepth == 0) { // Outermost macro.
3377 EndToken = getTok();
3379 if (getLexer().isNot(AsmToken::EndOfStatement))
3380 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3384 // Otherwise we just found the end of an inner macro.
3387 } else if (getTok().getIdentifier() == ".macro") {
3388 // We allow nested macros. Those aren't instantiated until the outermost
3389 // macro is expanded so just ignore them for now.
3394 // Otherwise, scan til the end of the statement.
3395 eatToEndOfStatement();
3398 if (lookupMacro(Name)) {
3399 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3402 const char *BodyStart = StartToken.getLoc().getPointer();
3403 const char *BodyEnd = EndToken.getLoc().getPointer();
3404 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3405 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3406 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3410 /// checkForBadMacro
3412 /// With the support added for named parameters there may be code out there that
3413 /// is transitioning from positional parameters. In versions of gas that did
3414 /// not support named parameters they would be ignored on the macro definition.
3415 /// But to support both styles of parameters this is not possible so if a macro
3416 /// definition has named parameters but does not use them and has what appears
3417 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3418 /// warning that the positional parameter found in body which have no effect.
3419 /// Hoping the developer will either remove the named parameters from the macro
3420 /// definition so the positional parameters get used if that was what was
3421 /// intended or change the macro to use the named parameters. It is possible
3422 /// this warning will trigger when the none of the named parameters are used
3423 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3424 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3426 ArrayRef<MCAsmMacroParameter> Parameters) {
3427 // If this macro is not defined with named parameters the warning we are
3428 // checking for here doesn't apply.
3429 unsigned NParameters = Parameters.size();
3430 if (NParameters == 0)
3433 bool NamedParametersFound = false;
3434 bool PositionalParametersFound = false;
3436 // Look at the body of the macro for use of both the named parameters and what
3437 // are likely to be positional parameters. This is what expandMacro() is
3438 // doing when it finds the parameters in the body.
3439 while (!Body.empty()) {
3440 // Scan for the next possible parameter.
3441 std::size_t End = Body.size(), Pos = 0;
3442 for (; Pos != End; ++Pos) {
3443 // Check for a substitution or escape.
3444 // This macro is defined with parameters, look for \foo, \bar, etc.
3445 if (Body[Pos] == '\\' && Pos + 1 != End)
3448 // This macro should have parameters, but look for $0, $1, ..., $n too.
3449 if (Body[Pos] != '$' || Pos + 1 == End)
3451 char Next = Body[Pos + 1];
3452 if (Next == '$' || Next == 'n' ||
3453 isdigit(static_cast<unsigned char>(Next)))
3457 // Check if we reached the end.
3461 if (Body[Pos] == '$') {
3462 switch (Body[Pos + 1]) {
3467 // $n => number of arguments
3469 PositionalParametersFound = true;
3472 // $[0-9] => argument
3474 PositionalParametersFound = true;
3480 unsigned I = Pos + 1;
3481 while (isIdentifierChar(Body[I]) && I + 1 != End)
3484 const char *Begin = Body.data() + Pos + 1;
3485 StringRef Argument(Begin, I - (Pos + 1));
3487 for (; Index < NParameters; ++Index)
3488 if (Parameters[Index].Name == Argument)
3491 if (Index == NParameters) {
3492 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3498 NamedParametersFound = true;
3499 Pos += 1 + Argument.size();
3502 // Update the scan point.
3503 Body = Body.substr(Pos);
3506 if (!NamedParametersFound && PositionalParametersFound)
3507 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3508 "used in macro body, possible positional parameter "
3509 "found in body which will have no effect");
3512 /// parseDirectiveExitMacro
3514 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3515 if (getLexer().isNot(AsmToken::EndOfStatement))
3516 return TokError("unexpected token in '" + Directive + "' directive");
3518 if (!isInsideMacroInstantiation())
3519 return TokError("unexpected '" + Directive + "' in file, "
3520 "no current macro definition");
3522 // Exit all conditionals that are active in the current macro.
3523 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3524 TheCondState = TheCondStack.back();
3525 TheCondStack.pop_back();
3532 /// parseDirectiveEndMacro
3535 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3536 if (getLexer().isNot(AsmToken::EndOfStatement))
3537 return TokError("unexpected token in '" + Directive + "' directive");
3539 // If we are inside a macro instantiation, terminate the current
3541 if (isInsideMacroInstantiation()) {
3546 // Otherwise, this .endmacro is a stray entry in the file; well formed
3547 // .endmacro directives are handled during the macro definition parsing.
3548 return TokError("unexpected '" + Directive + "' in file, "
3549 "no current macro definition");
3552 /// parseDirectivePurgeMacro
3554 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3556 if (parseIdentifier(Name))
3557 return TokError("expected identifier in '.purgem' directive");
3559 if (getLexer().isNot(AsmToken::EndOfStatement))
3560 return TokError("unexpected token in '.purgem' directive");
3562 if (!lookupMacro(Name))
3563 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3565 undefineMacro(Name);
3569 /// parseDirectiveBundleAlignMode
3570 /// ::= {.bundle_align_mode} expression
3571 bool AsmParser::parseDirectiveBundleAlignMode() {
3572 checkForValidSection();
3574 // Expect a single argument: an expression that evaluates to a constant
3575 // in the inclusive range 0-30.
3576 SMLoc ExprLoc = getLexer().getLoc();
3577 int64_t AlignSizePow2;
3578 if (parseAbsoluteExpression(AlignSizePow2))
3580 else if (getLexer().isNot(AsmToken::EndOfStatement))
3581 return TokError("unexpected token after expression in"
3582 " '.bundle_align_mode' directive");
3583 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3584 return Error(ExprLoc,
3585 "invalid bundle alignment size (expected between 0 and 30)");
3589 // Because of AlignSizePow2's verified range we can safely truncate it to
3591 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3595 /// parseDirectiveBundleLock
3596 /// ::= {.bundle_lock} [align_to_end]
3597 bool AsmParser::parseDirectiveBundleLock() {
3598 checkForValidSection();
3599 bool AlignToEnd = false;
3601 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3603 SMLoc Loc = getTok().getLoc();
3604 const char *kInvalidOptionError =
3605 "invalid option for '.bundle_lock' directive";
3607 if (parseIdentifier(Option))
3608 return Error(Loc, kInvalidOptionError);
3610 if (Option != "align_to_end")
3611 return Error(Loc, kInvalidOptionError);
3612 else if (getLexer().isNot(AsmToken::EndOfStatement))
3614 "unexpected token after '.bundle_lock' directive option");
3620 getStreamer().EmitBundleLock(AlignToEnd);
3624 /// parseDirectiveBundleLock
3625 /// ::= {.bundle_lock}
3626 bool AsmParser::parseDirectiveBundleUnlock() {
3627 checkForValidSection();
3629 if (getLexer().isNot(AsmToken::EndOfStatement))
3630 return TokError("unexpected token in '.bundle_unlock' directive");
3633 getStreamer().EmitBundleUnlock();
3637 /// parseDirectiveSpace
3638 /// ::= (.skip | .space) expression [ , expression ]
3639 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3640 checkForValidSection();
3643 if (parseAbsoluteExpression(NumBytes))
3646 int64_t FillExpr = 0;
3647 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3648 if (getLexer().isNot(AsmToken::Comma))
3649 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3652 if (parseAbsoluteExpression(FillExpr))
3655 if (getLexer().isNot(AsmToken::EndOfStatement))
3656 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3662 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3665 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3666 getStreamer().EmitFill(NumBytes, FillExpr);
3671 /// parseDirectiveLEB128
3672 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3673 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3674 checkForValidSection();
3675 const MCExpr *Value;
3678 if (parseExpression(Value))
3682 getStreamer().EmitSLEB128Value(Value);
3684 getStreamer().EmitULEB128Value(Value);
3686 if (getLexer().is(AsmToken::EndOfStatement))
3689 if (getLexer().isNot(AsmToken::Comma))
3690 return TokError("unexpected token in directive");
3697 /// parseDirectiveSymbolAttribute
3698 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3699 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3700 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3703 SMLoc Loc = getTok().getLoc();
3705 if (parseIdentifier(Name))
3706 return Error(Loc, "expected identifier in directive");
3708 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3710 // Assembler local symbols don't make any sense here. Complain loudly.
3711 if (Sym->isTemporary())
3712 return Error(Loc, "non-local symbol required in directive");
3714 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3715 return Error(Loc, "unable to emit symbol attribute");
3717 if (getLexer().is(AsmToken::EndOfStatement))
3720 if (getLexer().isNot(AsmToken::Comma))
3721 return TokError("unexpected token in directive");
3730 /// parseDirectiveComm
3731 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3732 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3733 checkForValidSection();
3735 SMLoc IDLoc = getLexer().getLoc();
3737 if (parseIdentifier(Name))
3738 return TokError("expected identifier in directive");
3740 // Handle the identifier as the key symbol.
3741 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3743 if (getLexer().isNot(AsmToken::Comma))
3744 return TokError("unexpected token in directive");
3748 SMLoc SizeLoc = getLexer().getLoc();
3749 if (parseAbsoluteExpression(Size))
3752 int64_t Pow2Alignment = 0;
3753 SMLoc Pow2AlignmentLoc;
3754 if (getLexer().is(AsmToken::Comma)) {
3756 Pow2AlignmentLoc = getLexer().getLoc();
3757 if (parseAbsoluteExpression(Pow2Alignment))
3760 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3761 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3762 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3764 // If this target takes alignments in bytes (not log) validate and convert.
3765 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3766 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3767 if (!isPowerOf2_64(Pow2Alignment))
3768 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3769 Pow2Alignment = Log2_64(Pow2Alignment);
3773 if (getLexer().isNot(AsmToken::EndOfStatement))
3774 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3778 // NOTE: a size of zero for a .comm should create a undefined symbol
3779 // but a size of .lcomm creates a bss symbol of size zero.
3781 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3782 "be less than zero");
3784 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3785 // may internally end up wanting an alignment in bytes.
3786 // FIXME: Diagnose overflow.
3787 if (Pow2Alignment < 0)
3788 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3789 "alignment, can't be less than zero");
3791 if (!Sym->isUndefined())
3792 return Error(IDLoc, "invalid symbol redefinition");
3794 // Create the Symbol as a common or local common with Size and Pow2Alignment
3796 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3800 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3804 /// parseDirectiveAbort
3805 /// ::= .abort [... message ...]
3806 bool AsmParser::parseDirectiveAbort() {
3807 // FIXME: Use loc from directive.
3808 SMLoc Loc = getLexer().getLoc();
3810 StringRef Str = parseStringToEndOfStatement();
3811 if (getLexer().isNot(AsmToken::EndOfStatement))
3812 return TokError("unexpected token in '.abort' directive");
3817 Error(Loc, ".abort detected. Assembly stopping.");
3819 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3820 // FIXME: Actually abort assembly here.
3825 /// parseDirectiveInclude
3826 /// ::= .include "filename"
3827 bool AsmParser::parseDirectiveInclude() {
3828 if (getLexer().isNot(AsmToken::String))
3829 return TokError("expected string in '.include' directive");
3831 // Allow the strings to have escaped octal character sequence.
3832 std::string Filename;
3833 if (parseEscapedString(Filename))
3835 SMLoc IncludeLoc = getLexer().getLoc();
3838 if (getLexer().isNot(AsmToken::EndOfStatement))
3839 return TokError("unexpected token in '.include' directive");
3841 // Attempt to switch the lexer to the included file before consuming the end
3842 // of statement to avoid losing it when we switch.
3843 if (enterIncludeFile(Filename)) {
3844 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3851 /// parseDirectiveIncbin
3852 /// ::= .incbin "filename"
3853 bool AsmParser::parseDirectiveIncbin() {
3854 if (getLexer().isNot(AsmToken::String))
3855 return TokError("expected string in '.incbin' directive");
3857 // Allow the strings to have escaped octal character sequence.
3858 std::string Filename;
3859 if (parseEscapedString(Filename))
3861 SMLoc IncbinLoc = getLexer().getLoc();
3864 if (getLexer().isNot(AsmToken::EndOfStatement))
3865 return TokError("unexpected token in '.incbin' directive");
3867 // Attempt to process the included file.
3868 if (processIncbinFile(Filename)) {
3869 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3876 /// parseDirectiveIf
3877 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3878 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3879 TheCondStack.push_back(TheCondState);
3880 TheCondState.TheCond = AsmCond::IfCond;
3881 if (TheCondState.Ignore) {
3882 eatToEndOfStatement();
3885 if (parseAbsoluteExpression(ExprValue))
3888 if (getLexer().isNot(AsmToken::EndOfStatement))
3889 return TokError("unexpected token in '.if' directive");
3895 llvm_unreachable("unsupported directive");
3900 ExprValue = ExprValue == 0;
3903 ExprValue = ExprValue >= 0;
3906 ExprValue = ExprValue > 0;
3909 ExprValue = ExprValue <= 0;
3912 ExprValue = ExprValue < 0;
3916 TheCondState.CondMet = ExprValue;
3917 TheCondState.Ignore = !TheCondState.CondMet;
3923 /// parseDirectiveIfb
3925 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3926 TheCondStack.push_back(TheCondState);
3927 TheCondState.TheCond = AsmCond::IfCond;
3929 if (TheCondState.Ignore) {
3930 eatToEndOfStatement();
3932 StringRef Str = parseStringToEndOfStatement();
3934 if (getLexer().isNot(AsmToken::EndOfStatement))
3935 return TokError("unexpected token in '.ifb' directive");
3939 TheCondState.CondMet = ExpectBlank == Str.empty();
3940 TheCondState.Ignore = !TheCondState.CondMet;
3946 /// parseDirectiveIfc
3947 /// ::= .ifc string1, string2
3948 /// ::= .ifnc string1, string2
3949 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3950 TheCondStack.push_back(TheCondState);
3951 TheCondState.TheCond = AsmCond::IfCond;
3953 if (TheCondState.Ignore) {
3954 eatToEndOfStatement();
3956 StringRef Str1 = parseStringToComma();
3958 if (getLexer().isNot(AsmToken::Comma))
3959 return TokError("unexpected token in '.ifc' directive");
3963 StringRef Str2 = parseStringToEndOfStatement();
3965 if (getLexer().isNot(AsmToken::EndOfStatement))
3966 return TokError("unexpected token in '.ifc' directive");
3970 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3971 TheCondState.Ignore = !TheCondState.CondMet;
3977 /// parseDirectiveIfeqs
3978 /// ::= .ifeqs string1, string2
3979 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3980 if (Lexer.isNot(AsmToken::String)) {
3982 TokError("expected string parameter for '.ifeqs' directive");
3984 TokError("expected string parameter for '.ifnes' directive");
3985 eatToEndOfStatement();
3989 StringRef String1 = getTok().getStringContents();
3992 if (Lexer.isNot(AsmToken::Comma)) {
3994 TokError("expected comma after first string for '.ifeqs' directive");
3996 TokError("expected comma after first string for '.ifnes' directive");
3997 eatToEndOfStatement();
4003 if (Lexer.isNot(AsmToken::String)) {
4005 TokError("expected string parameter for '.ifeqs' directive");
4007 TokError("expected string parameter for '.ifnes' directive");
4008 eatToEndOfStatement();
4012 StringRef String2 = getTok().getStringContents();
4015 TheCondStack.push_back(TheCondState);
4016 TheCondState.TheCond = AsmCond::IfCond;
4017 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4018 TheCondState.Ignore = !TheCondState.CondMet;
4023 /// parseDirectiveIfdef
4024 /// ::= .ifdef symbol
4025 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4027 TheCondStack.push_back(TheCondState);
4028 TheCondState.TheCond = AsmCond::IfCond;
4030 if (TheCondState.Ignore) {
4031 eatToEndOfStatement();
4033 if (parseIdentifier(Name))
4034 return TokError("expected identifier after '.ifdef'");
4038 MCSymbol *Sym = getContext().lookupSymbol(Name);
4041 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4043 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4044 TheCondState.Ignore = !TheCondState.CondMet;
4050 /// parseDirectiveElseIf
4051 /// ::= .elseif expression
4052 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4053 if (TheCondState.TheCond != AsmCond::IfCond &&
4054 TheCondState.TheCond != AsmCond::ElseIfCond)
4055 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4057 TheCondState.TheCond = AsmCond::ElseIfCond;
4059 bool LastIgnoreState = false;
4060 if (!TheCondStack.empty())
4061 LastIgnoreState = TheCondStack.back().Ignore;
4062 if (LastIgnoreState || TheCondState.CondMet) {
4063 TheCondState.Ignore = true;
4064 eatToEndOfStatement();
4067 if (parseAbsoluteExpression(ExprValue))
4070 if (getLexer().isNot(AsmToken::EndOfStatement))
4071 return TokError("unexpected token in '.elseif' directive");
4074 TheCondState.CondMet = ExprValue;
4075 TheCondState.Ignore = !TheCondState.CondMet;
4081 /// parseDirectiveElse
4083 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4084 if (getLexer().isNot(AsmToken::EndOfStatement))
4085 return TokError("unexpected token in '.else' directive");
4089 if (TheCondState.TheCond != AsmCond::IfCond &&
4090 TheCondState.TheCond != AsmCond::ElseIfCond)
4091 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4093 TheCondState.TheCond = AsmCond::ElseCond;
4094 bool LastIgnoreState = false;
4095 if (!TheCondStack.empty())
4096 LastIgnoreState = TheCondStack.back().Ignore;
4097 if (LastIgnoreState || TheCondState.CondMet)
4098 TheCondState.Ignore = true;
4100 TheCondState.Ignore = false;
4105 /// parseDirectiveEnd
4107 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4108 if (getLexer().isNot(AsmToken::EndOfStatement))
4109 return TokError("unexpected token in '.end' directive");
4113 while (Lexer.isNot(AsmToken::Eof))
4119 /// parseDirectiveError
4121 /// ::= .error [string]
4122 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4123 if (!TheCondStack.empty()) {
4124 if (TheCondStack.back().Ignore) {
4125 eatToEndOfStatement();
4131 return Error(L, ".err encountered");
4133 StringRef Message = ".error directive invoked in source file";
4134 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4135 if (Lexer.isNot(AsmToken::String)) {
4136 TokError(".error argument must be a string");
4137 eatToEndOfStatement();
4141 Message = getTok().getStringContents();
4149 /// parseDirectiveWarning
4150 /// ::= .warning [string]
4151 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4152 if (!TheCondStack.empty()) {
4153 if (TheCondStack.back().Ignore) {
4154 eatToEndOfStatement();
4159 StringRef Message = ".warning directive invoked in source file";
4160 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4161 if (Lexer.isNot(AsmToken::String)) {
4162 TokError(".warning argument must be a string");
4163 eatToEndOfStatement();
4167 Message = getTok().getStringContents();
4171 Warning(L, Message);
4175 /// parseDirectiveEndIf
4177 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4178 if (getLexer().isNot(AsmToken::EndOfStatement))
4179 return TokError("unexpected token in '.endif' directive");
4183 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4184 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4186 if (!TheCondStack.empty()) {
4187 TheCondState = TheCondStack.back();
4188 TheCondStack.pop_back();
4194 void AsmParser::initializeDirectiveKindMap() {
4195 DirectiveKindMap[".set"] = DK_SET;
4196 DirectiveKindMap[".equ"] = DK_EQU;
4197 DirectiveKindMap[".equiv"] = DK_EQUIV;
4198 DirectiveKindMap[".ascii"] = DK_ASCII;
4199 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4200 DirectiveKindMap[".string"] = DK_STRING;
4201 DirectiveKindMap[".byte"] = DK_BYTE;
4202 DirectiveKindMap[".short"] = DK_SHORT;
4203 DirectiveKindMap[".value"] = DK_VALUE;
4204 DirectiveKindMap[".2byte"] = DK_2BYTE;
4205 DirectiveKindMap[".long"] = DK_LONG;
4206 DirectiveKindMap[".int"] = DK_INT;
4207 DirectiveKindMap[".4byte"] = DK_4BYTE;
4208 DirectiveKindMap[".quad"] = DK_QUAD;
4209 DirectiveKindMap[".8byte"] = DK_8BYTE;
4210 DirectiveKindMap[".octa"] = DK_OCTA;
4211 DirectiveKindMap[".single"] = DK_SINGLE;
4212 DirectiveKindMap[".float"] = DK_FLOAT;
4213 DirectiveKindMap[".double"] = DK_DOUBLE;
4214 DirectiveKindMap[".align"] = DK_ALIGN;
4215 DirectiveKindMap[".align32"] = DK_ALIGN32;
4216 DirectiveKindMap[".balign"] = DK_BALIGN;
4217 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4218 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4219 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4220 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4221 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4222 DirectiveKindMap[".org"] = DK_ORG;
4223 DirectiveKindMap[".fill"] = DK_FILL;
4224 DirectiveKindMap[".zero"] = DK_ZERO;
4225 DirectiveKindMap[".extern"] = DK_EXTERN;
4226 DirectiveKindMap[".globl"] = DK_GLOBL;
4227 DirectiveKindMap[".global"] = DK_GLOBAL;
4228 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4229 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4230 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4231 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4232 DirectiveKindMap[".reference"] = DK_REFERENCE;
4233 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4234 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4235 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4236 DirectiveKindMap[".comm"] = DK_COMM;
4237 DirectiveKindMap[".common"] = DK_COMMON;
4238 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4239 DirectiveKindMap[".abort"] = DK_ABORT;
4240 DirectiveKindMap[".include"] = DK_INCLUDE;
4241 DirectiveKindMap[".incbin"] = DK_INCBIN;
4242 DirectiveKindMap[".code16"] = DK_CODE16;
4243 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4244 DirectiveKindMap[".rept"] = DK_REPT;
4245 DirectiveKindMap[".rep"] = DK_REPT;
4246 DirectiveKindMap[".irp"] = DK_IRP;
4247 DirectiveKindMap[".irpc"] = DK_IRPC;
4248 DirectiveKindMap[".endr"] = DK_ENDR;
4249 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4250 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4251 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4252 DirectiveKindMap[".if"] = DK_IF;
4253 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4254 DirectiveKindMap[".ifge"] = DK_IFGE;
4255 DirectiveKindMap[".ifgt"] = DK_IFGT;
4256 DirectiveKindMap[".ifle"] = DK_IFLE;
4257 DirectiveKindMap[".iflt"] = DK_IFLT;
4258 DirectiveKindMap[".ifne"] = DK_IFNE;
4259 DirectiveKindMap[".ifb"] = DK_IFB;
4260 DirectiveKindMap[".ifnb"] = DK_IFNB;
4261 DirectiveKindMap[".ifc"] = DK_IFC;
4262 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4263 DirectiveKindMap[".ifnc"] = DK_IFNC;
4264 DirectiveKindMap[".ifnes"] = DK_IFNES;
4265 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4266 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4267 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4268 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4269 DirectiveKindMap[".else"] = DK_ELSE;
4270 DirectiveKindMap[".end"] = DK_END;
4271 DirectiveKindMap[".endif"] = DK_ENDIF;
4272 DirectiveKindMap[".skip"] = DK_SKIP;
4273 DirectiveKindMap[".space"] = DK_SPACE;
4274 DirectiveKindMap[".file"] = DK_FILE;
4275 DirectiveKindMap[".line"] = DK_LINE;
4276 DirectiveKindMap[".loc"] = DK_LOC;
4277 DirectiveKindMap[".stabs"] = DK_STABS;
4278 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4279 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4280 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4281 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4282 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4283 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4284 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4285 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4286 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4287 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4288 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4289 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4290 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4291 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4292 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4293 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4294 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4295 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4296 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4297 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4298 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4299 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4300 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4301 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4302 DirectiveKindMap[".macro"] = DK_MACRO;
4303 DirectiveKindMap[".exitm"] = DK_EXITM;
4304 DirectiveKindMap[".endm"] = DK_ENDM;
4305 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4306 DirectiveKindMap[".purgem"] = DK_PURGEM;
4307 DirectiveKindMap[".err"] = DK_ERR;
4308 DirectiveKindMap[".error"] = DK_ERROR;
4309 DirectiveKindMap[".warning"] = DK_WARNING;
4312 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4313 AsmToken EndToken, StartToken = getTok();
4315 unsigned NestLevel = 0;
4317 // Check whether we have reached the end of the file.
4318 if (getLexer().is(AsmToken::Eof)) {
4319 Error(DirectiveLoc, "no matching '.endr' in definition");
4323 if (Lexer.is(AsmToken::Identifier) &&
4324 (getTok().getIdentifier() == ".rept")) {
4328 // Otherwise, check whether we have reached the .endr.
4329 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4330 if (NestLevel == 0) {
4331 EndToken = getTok();
4333 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4334 TokError("unexpected token in '.endr' directive");
4342 // Otherwise, scan till the end of the statement.
4343 eatToEndOfStatement();
4346 const char *BodyStart = StartToken.getLoc().getPointer();
4347 const char *BodyEnd = EndToken.getLoc().getPointer();
4348 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4350 // We Are Anonymous.
4351 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4352 return &MacroLikeBodies.back();
4355 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4356 raw_svector_ostream &OS) {
4359 std::unique_ptr<MemoryBuffer> Instantiation =
4360 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4362 // Create the macro instantiation object and add to the current macro
4363 // instantiation stack.
4364 MacroInstantiation *MI = new MacroInstantiation(
4365 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4366 ActiveMacros.push_back(MI);
4368 // Jump to the macro instantiation and prime the lexer.
4369 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4370 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4374 /// parseDirectiveRept
4375 /// ::= .rep | .rept count
4376 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4377 const MCExpr *CountExpr;
4378 SMLoc CountLoc = getTok().getLoc();
4379 if (parseExpression(CountExpr))
4383 if (!CountExpr->evaluateAsAbsolute(Count)) {
4384 eatToEndOfStatement();
4385 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4389 return Error(CountLoc, "Count is negative");
4391 if (Lexer.isNot(AsmToken::EndOfStatement))
4392 return TokError("unexpected token in '" + Dir + "' directive");
4394 // Eat the end of statement.
4397 // Lex the rept definition.
4398 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4402 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4403 // to hold the macro body with substitutions.
4404 SmallString<256> Buf;
4405 raw_svector_ostream OS(Buf);
4407 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4408 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4411 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4416 /// parseDirectiveIrp
4417 /// ::= .irp symbol,values
4418 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4419 MCAsmMacroParameter Parameter;
4421 if (parseIdentifier(Parameter.Name))
4422 return TokError("expected identifier in '.irp' directive");
4424 if (Lexer.isNot(AsmToken::Comma))
4425 return TokError("expected comma in '.irp' directive");
4429 MCAsmMacroArguments A;
4430 if (parseMacroArguments(nullptr, A))
4433 // Eat the end of statement.
4436 // Lex the irp definition.
4437 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4441 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4442 // to hold the macro body with substitutions.
4443 SmallString<256> Buf;
4444 raw_svector_ostream OS(Buf);
4446 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4447 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4448 // This is undocumented, but GAS seems to support it.
4449 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4453 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4458 /// parseDirectiveIrpc
4459 /// ::= .irpc symbol,values
4460 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4461 MCAsmMacroParameter Parameter;
4463 if (parseIdentifier(Parameter.Name))
4464 return TokError("expected identifier in '.irpc' directive");
4466 if (Lexer.isNot(AsmToken::Comma))
4467 return TokError("expected comma in '.irpc' directive");
4471 MCAsmMacroArguments A;
4472 if (parseMacroArguments(nullptr, A))
4475 if (A.size() != 1 || A.front().size() != 1)
4476 return TokError("unexpected token in '.irpc' directive");
4478 // Eat the end of statement.
4481 // Lex the irpc definition.
4482 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4486 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4487 // to hold the macro body with substitutions.
4488 SmallString<256> Buf;
4489 raw_svector_ostream OS(Buf);
4491 StringRef Values = A.front().front().getString();
4492 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4493 MCAsmMacroArgument Arg;
4494 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4496 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4497 // This is undocumented, but GAS seems to support it.
4498 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4502 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4507 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4508 if (ActiveMacros.empty())
4509 return TokError("unmatched '.endr' directive");
4511 // The only .repl that should get here are the ones created by
4512 // instantiateMacroLikeBody.
4513 assert(getLexer().is(AsmToken::EndOfStatement));
4519 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4521 const MCExpr *Value;
4522 SMLoc ExprLoc = getLexer().getLoc();
4523 if (parseExpression(Value))
4525 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4527 return Error(ExprLoc, "unexpected expression in _emit");
4528 uint64_t IntValue = MCE->getValue();
4529 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4530 return Error(ExprLoc, "literal value out of range for directive");
4532 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4536 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4537 const MCExpr *Value;
4538 SMLoc ExprLoc = getLexer().getLoc();
4539 if (parseExpression(Value))
4541 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4543 return Error(ExprLoc, "unexpected expression in align");
4544 uint64_t IntValue = MCE->getValue();
4545 if (!isPowerOf2_64(IntValue))
4546 return Error(ExprLoc, "literal value not a power of two greater then zero");
4548 Info.AsmRewrites->push_back(
4549 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4553 // We are comparing pointers, but the pointers are relative to a single string.
4554 // Thus, this should always be deterministic.
4555 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4556 const AsmRewrite *AsmRewriteB) {
4557 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4559 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4562 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4563 // rewrite to the same location. Make sure the SizeDirective rewrite is
4564 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4565 // ensures the sort algorithm is stable.
4566 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4567 AsmRewritePrecedence[AsmRewriteB->Kind])
4570 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4571 AsmRewritePrecedence[AsmRewriteB->Kind])
4573 llvm_unreachable("Unstable rewrite sort.");
4576 bool AsmParser::parseMSInlineAsm(
4577 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4578 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4579 SmallVectorImpl<std::string> &Constraints,
4580 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4581 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4582 SmallVector<void *, 4> InputDecls;
4583 SmallVector<void *, 4> OutputDecls;
4584 SmallVector<bool, 4> InputDeclsAddressOf;
4585 SmallVector<bool, 4> OutputDeclsAddressOf;
4586 SmallVector<std::string, 4> InputConstraints;
4587 SmallVector<std::string, 4> OutputConstraints;
4588 SmallVector<unsigned, 4> ClobberRegs;
4590 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4595 // While we have input, parse each statement.
4596 unsigned InputIdx = 0;
4597 unsigned OutputIdx = 0;
4598 while (getLexer().isNot(AsmToken::Eof)) {
4599 ParseStatementInfo Info(&AsmStrRewrites);
4600 if (parseStatement(Info, &SI))
4603 if (Info.ParseError)
4606 if (Info.Opcode == ~0U)
4609 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4611 // Build the list of clobbers, outputs and inputs.
4612 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4613 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4616 if (Operand.isImm())
4619 // Register operand.
4620 if (Operand.isReg() && !Operand.needAddressOf() &&
4621 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4622 unsigned NumDefs = Desc.getNumDefs();
4624 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4625 ClobberRegs.push_back(Operand.getReg());
4629 // Expr/Input or Output.
4630 StringRef SymName = Operand.getSymName();
4631 if (SymName.empty())
4634 void *OpDecl = Operand.getOpDecl();
4638 bool isOutput = (i == 1) && Desc.mayStore();
4639 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4642 OutputDecls.push_back(OpDecl);
4643 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4644 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4645 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4647 InputDecls.push_back(OpDecl);
4648 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4649 InputConstraints.push_back(Operand.getConstraint().str());
4650 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4654 // Consider implicit defs to be clobbers. Think of cpuid and push.
4655 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4656 Desc.getNumImplicitDefs());
4657 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4660 // Set the number of Outputs and Inputs.
4661 NumOutputs = OutputDecls.size();
4662 NumInputs = InputDecls.size();
4664 // Set the unique clobbers.
4665 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4666 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4668 Clobbers.assign(ClobberRegs.size(), std::string());
4669 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4670 raw_string_ostream OS(Clobbers[I]);
4671 IP->printRegName(OS, ClobberRegs[I]);
4674 // Merge the various outputs and inputs. Output are expected first.
4675 if (NumOutputs || NumInputs) {
4676 unsigned NumExprs = NumOutputs + NumInputs;
4677 OpDecls.resize(NumExprs);
4678 Constraints.resize(NumExprs);
4679 for (unsigned i = 0; i < NumOutputs; ++i) {
4680 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4681 Constraints[i] = OutputConstraints[i];
4683 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4684 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4685 Constraints[j] = InputConstraints[i];
4689 // Build the IR assembly string.
4690 std::string AsmStringIR;
4691 raw_string_ostream OS(AsmStringIR);
4692 StringRef ASMString =
4693 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4694 const char *AsmStart = ASMString.begin();
4695 const char *AsmEnd = ASMString.end();
4696 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4697 for (const AsmRewrite &AR : AsmStrRewrites) {
4698 AsmRewriteKind Kind = AR.Kind;
4699 if (Kind == AOK_Delete)
4702 const char *Loc = AR.Loc.getPointer();
4703 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4705 // Emit everything up to the immediate/expression.
4706 if (unsigned Len = Loc - AsmStart)
4707 OS << StringRef(AsmStart, Len);
4709 // Skip the original expression.
4710 if (Kind == AOK_Skip) {
4711 AsmStart = Loc + AR.Len;
4715 unsigned AdditionalSkip = 0;
4716 // Rewrite expressions in $N notation.
4721 OS << "$$" << AR.Val;
4727 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4730 OS << '$' << InputIdx++;
4733 OS << '$' << OutputIdx++;
4735 case AOK_SizeDirective:
4738 case 8: OS << "byte ptr "; break;
4739 case 16: OS << "word ptr "; break;
4740 case 32: OS << "dword ptr "; break;
4741 case 64: OS << "qword ptr "; break;
4742 case 80: OS << "xword ptr "; break;
4743 case 128: OS << "xmmword ptr "; break;
4744 case 256: OS << "ymmword ptr "; break;
4751 unsigned Val = AR.Val;
4752 OS << ".align " << Val;
4754 // Skip the original immediate.
4755 assert(Val < 10 && "Expected alignment less then 2^10.");
4756 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4759 case AOK_DotOperator:
4760 // Insert the dot if the user omitted it.
4762 if (AsmStringIR.back() != '.')
4768 // Skip the original expression.
4769 AsmStart = Loc + AR.Len + AdditionalSkip;
4772 // Emit the remainder of the asm string.
4773 if (AsmStart != AsmEnd)
4774 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4776 AsmString = OS.str();
4780 /// \brief Create an MCAsmParser instance.
4781 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4782 MCStreamer &Out, const MCAsmInfo &MAI) {
4783 return new AsmParser(SM, C, Out, MAI);