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"
49 FatalAssemblerWarnings("fatal-assembler-warnings",
50 cl::desc("Consider warnings as error"));
52 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
59 struct MCAsmMacroParameter {
61 MCAsmMacroArgument Value;
65 MCAsmMacroParameter() : Required(false), Vararg(false) {}
68 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
73 MCAsmMacroParameters Parameters;
76 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
77 Name(N), Body(B), Parameters(P) {}
80 /// \brief Helper class for storing information about an active macro
82 struct MacroInstantiation {
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
92 /// The depth of TheCondStack at the start of the instantiation.
93 size_t CondStackDepth;
96 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, StringRef I,
97 size_t CondStackDepth);
100 struct ParseStatementInfo {
101 /// \brief The parsed operands from the last parsed statement.
102 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
104 /// \brief The opcode from the last parsed instruction.
107 /// \brief Was there an error parsing the inline assembly?
110 SmallVectorImpl<AsmRewrite> *AsmRewrites;
112 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
113 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
114 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
117 /// \brief The concrete assembly parser instance.
118 class AsmParser : public MCAsmParser {
119 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
120 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
125 const MCAsmInfo &MAI;
127 SourceMgr::DiagHandlerTy SavedDiagHandler;
128 void *SavedDiagContext;
129 MCAsmParserExtension *PlatformParser;
131 /// This is the current buffer index we're lexing from as managed by the
132 /// SourceMgr object.
135 AsmCond TheCondState;
136 std::vector<AsmCond> TheCondStack;
138 /// \brief maps directive names to handler methods in parser
139 /// extensions. Extensions register themselves in this map by calling
140 /// addDirectiveHandler.
141 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
143 /// \brief Map of currently defined macros.
144 StringMap<MCAsmMacro*> MacroMap;
146 /// \brief Stack of active macro instantiations.
147 std::vector<MacroInstantiation*> ActiveMacros;
149 /// \brief List of bodies of anonymous macros.
150 std::deque<MCAsmMacro> MacroLikeBodies;
152 /// Boolean tracking whether macro substitution is enabled.
153 unsigned MacrosEnabledFlag : 1;
155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
165 /// and current line. Since this is slow and messes up the SourceMgr's
166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
168 unsigned LastQueryBuffer;
169 unsigned LastQueryLine;
171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
174 /// \brief is Darwin compatibility enabled?
177 /// \brief Are we parsing ms-style inline assembly?
178 bool ParsingInlineAsm;
181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
182 const MCAsmInfo &MAI);
183 virtual ~AsmParser();
185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
187 void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) override {
189 ExtensionDirectiveMap[Directive] = Handler;
193 /// @name MCAsmParser Interface
196 SourceMgr &getSourceManager() override { return SrcMgr; }
197 MCAsmLexer &getLexer() override { return Lexer; }
198 MCContext &getContext() override { return Ctx; }
199 MCStreamer &getStreamer() override { return Out; }
200 unsigned getAssemblerDialect() override {
201 if (AssemblerDialect == ~0U)
202 return MAI.getAssemblerDialect();
204 return AssemblerDialect;
206 void setAssemblerDialect(unsigned i) override {
207 AssemblerDialect = i;
210 void Note(SMLoc L, const Twine &Msg,
211 ArrayRef<SMRange> Ranges = None) override;
212 bool Warning(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None) override;
214 bool Error(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
217 const AsmToken &Lex() override;
219 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
220 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
222 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
223 unsigned &NumOutputs, unsigned &NumInputs,
224 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
225 SmallVectorImpl<std::string> &Constraints,
226 SmallVectorImpl<std::string> &Clobbers,
227 const MCInstrInfo *MII, const MCInstPrinter *IP,
228 MCAsmParserSemaCallback &SI) override;
230 bool parseExpression(const MCExpr *&Res);
231 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
232 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
233 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
234 bool parseAbsoluteExpression(int64_t &Res) override;
236 /// \brief Parse an identifier or string (as a quoted identifier)
237 /// and set \p Res to the identifier contents.
238 bool parseIdentifier(StringRef &Res) override;
239 void eatToEndOfStatement() override;
241 void checkForValidSection() override;
246 bool parseStatement(ParseStatementInfo &Info);
247 void eatToEndOfLine();
248 bool parseCppHashLineFilenameComment(const SMLoc &L);
250 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
251 ArrayRef<MCAsmMacroParameter> Parameters);
252 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
253 ArrayRef<MCAsmMacroParameter> Parameters,
254 ArrayRef<MCAsmMacroArgument> A,
257 /// \brief Are macros enabled in the parser?
258 bool areMacrosEnabled() {return MacrosEnabledFlag;}
260 /// \brief Control a flag in the parser that enables or disables macros.
261 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
263 /// \brief Lookup a previously defined macro.
264 /// \param Name Macro name.
265 /// \returns Pointer to macro. NULL if no such macro was defined.
266 const MCAsmMacro* lookupMacro(StringRef Name);
268 /// \brief Define a new macro with the given name and information.
269 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
271 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
272 void undefineMacro(StringRef Name);
274 /// \brief Are we inside a macro instantiation?
275 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
277 /// \brief Handle entry to macro instantiation.
279 /// \param M The macro.
280 /// \param NameLoc Instantiation location.
281 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
283 /// \brief Handle exit from macro instantiation.
284 void handleMacroExit();
286 /// \brief Extract AsmTokens for a macro argument.
287 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
289 /// \brief Parse all macro arguments for a given macro.
290 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
292 void printMacroInstantiations();
293 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
294 ArrayRef<SMRange> Ranges = None) const {
295 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
297 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
299 /// \brief Enter the specified file. This returns true on failure.
300 bool enterIncludeFile(const std::string &Filename);
302 /// \brief Process the specified file for the .incbin directive.
303 /// This returns true on failure.
304 bool processIncbinFile(const std::string &Filename);
306 /// \brief Reset the current lexer position to that given by \p Loc. The
307 /// current token is not set; clients should ensure Lex() is called
310 /// \param InBuffer If not 0, should be the known buffer id that contains the
312 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
314 /// \brief Parse up to the end of statement and a return the contents from the
315 /// current token until the end of the statement; the current token on exit
316 /// will be either the EndOfStatement or EOF.
317 StringRef parseStringToEndOfStatement() override;
319 /// \brief Parse until the end of a statement or a comma is encountered,
320 /// return the contents from the current token up to the end or comma.
321 StringRef parseStringToComma();
323 bool parseAssignment(StringRef Name, bool allow_redef,
324 bool NoDeadStrip = false);
326 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
327 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
328 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
330 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
332 // Generic (target and platform independent) directive parsing.
334 DK_NO_DIRECTIVE, // Placeholder
335 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
336 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
337 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
338 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
339 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
340 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
341 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
342 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
343 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
344 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
345 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
346 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
347 DK_ELSEIF, DK_ELSE, DK_ENDIF,
348 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
349 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
350 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
351 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
352 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
353 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
354 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
355 DK_MACROS_ON, DK_MACROS_OFF,
356 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
357 DK_SLEB128, DK_ULEB128,
358 DK_ERR, DK_ERROR, DK_WARNING,
362 /// \brief Maps directive name --> DirectiveKind enum, for
363 /// directives parsed by this class.
364 StringMap<DirectiveKind> DirectiveKindMap;
366 // ".ascii", ".asciz", ".string"
367 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
368 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
369 bool parseDirectiveOctaValue(); // ".octa"
370 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool parseDirectiveFill(); // ".fill"
372 bool parseDirectiveZero(); // ".zero"
373 // ".set", ".equ", ".equiv"
374 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool parseDirectiveOrg(); // ".org"
376 // ".align{,32}", ".p2align{,w,l}"
377 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
379 // ".file", ".line", ".loc", ".stabs"
380 bool parseDirectiveFile(SMLoc DirectiveLoc);
381 bool parseDirectiveLine();
382 bool parseDirectiveLoc();
383 bool parseDirectiveStabs();
386 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
387 bool parseDirectiveCFIWindowSave();
388 bool parseDirectiveCFISections();
389 bool parseDirectiveCFIStartProc();
390 bool parseDirectiveCFIEndProc();
391 bool parseDirectiveCFIDefCfaOffset();
392 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIAdjustCfaOffset();
394 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
398 bool parseDirectiveCFIRememberState();
399 bool parseDirectiveCFIRestoreState();
400 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIEscape();
403 bool parseDirectiveCFISignalFrame();
404 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
407 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
408 bool parseDirectiveExitMacro(StringRef Directive);
409 bool parseDirectiveEndMacro(StringRef Directive);
410 bool parseDirectiveMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveMacrosOnOff(StringRef Directive);
413 // ".bundle_align_mode"
414 bool parseDirectiveBundleAlignMode();
416 bool parseDirectiveBundleLock();
418 bool parseDirectiveBundleUnlock();
421 bool parseDirectiveSpace(StringRef IDVal);
423 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
424 bool parseDirectiveLEB128(bool Signed);
426 /// \brief Parse a directive like ".globl" which
427 /// accepts a single symbol (which should be a label or an external).
428 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
430 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
432 bool parseDirectiveAbort(); // ".abort"
433 bool parseDirectiveInclude(); // ".include"
434 bool parseDirectiveIncbin(); // ".incbin"
436 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
437 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
438 // ".ifb" or ".ifnb", depending on ExpectBlank.
439 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
440 // ".ifc" or ".ifnc", depending on ExpectEqual.
441 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
443 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
444 // ".ifdef" or ".ifndef", depending on expect_defined
445 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
446 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
447 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
448 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
449 bool parseEscapedString(std::string &Data) override;
451 const MCExpr *applyModifierToExpr(const MCExpr *E,
452 MCSymbolRefExpr::VariantKind Variant);
454 // Macro-like directives
455 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
456 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
457 raw_svector_ostream &OS);
458 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
459 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
460 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
461 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
463 // "_emit" or "__emit"
464 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
468 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
471 bool parseDirectiveEnd(SMLoc DirectiveLoc);
473 // ".err" or ".error"
474 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
477 bool parseDirectiveWarning(SMLoc DirectiveLoc);
479 void initializeDirectiveKindMap();
485 extern MCAsmParserExtension *createDarwinAsmParser();
486 extern MCAsmParserExtension *createELFAsmParser();
487 extern MCAsmParserExtension *createCOFFAsmParser();
491 enum { DEFAULT_ADDRSPACE = 0 };
493 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
494 const MCAsmInfo &_MAI)
495 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
496 PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
497 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
498 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
499 // Save the old handler.
500 SavedDiagHandler = SrcMgr.getDiagHandler();
501 SavedDiagContext = SrcMgr.getDiagContext();
502 // Set our own handler which calls the saved handler.
503 SrcMgr.setDiagHandler(DiagHandler, this);
504 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
506 // Initialize the platform / file format parser.
507 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
508 case MCObjectFileInfo::IsCOFF:
509 PlatformParser = createCOFFAsmParser();
510 PlatformParser->Initialize(*this);
512 case MCObjectFileInfo::IsMachO:
513 PlatformParser = createDarwinAsmParser();
514 PlatformParser->Initialize(*this);
517 case MCObjectFileInfo::IsELF:
518 PlatformParser = createELFAsmParser();
519 PlatformParser->Initialize(*this);
523 initializeDirectiveKindMap();
526 AsmParser::~AsmParser() {
527 assert((HadError || ActiveMacros.empty()) &&
528 "Unexpected active macro instantiation!");
530 // Destroy any macros.
531 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
534 delete it->getValue();
536 delete PlatformParser;
539 void AsmParser::printMacroInstantiations() {
540 // Print the active macro instantiation stack.
541 for (std::vector<MacroInstantiation *>::const_reverse_iterator
542 it = ActiveMacros.rbegin(),
543 ie = ActiveMacros.rend();
545 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
546 "while in macro instantiation");
549 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
550 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
551 printMacroInstantiations();
554 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
555 if (FatalAssemblerWarnings)
556 return Error(L, Msg, Ranges);
557 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
558 printMacroInstantiations();
562 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
564 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
565 printMacroInstantiations();
569 bool AsmParser::enterIncludeFile(const std::string &Filename) {
570 std::string IncludedFile;
572 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
577 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
581 /// Process the specified .incbin file by searching for it in the include paths
582 /// then just emitting the byte contents of the file to the streamer. This
583 /// returns true on failure.
584 bool AsmParser::processIncbinFile(const std::string &Filename) {
585 std::string IncludedFile;
587 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
591 // Pick up the bytes from the file and emit them.
592 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
596 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
597 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
598 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
602 const AsmToken &AsmParser::Lex() {
603 const AsmToken *tok = &Lexer.Lex();
605 if (tok->is(AsmToken::Eof)) {
606 // If this is the end of an included file, pop the parent file off the
608 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
609 if (ParentIncludeLoc != SMLoc()) {
610 jumpToLoc(ParentIncludeLoc);
615 if (tok->is(AsmToken::Error))
616 Error(Lexer.getErrLoc(), Lexer.getErr());
621 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
622 // Create the initial section, if requested.
623 if (!NoInitialTextSection)
630 AsmCond StartingCondState = TheCondState;
632 // If we are generating dwarf for assembly source files save the initial text
633 // section and generate a .file directive.
634 if (getContext().getGenDwarfForAssembly()) {
635 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
636 getStreamer().EmitLabel(SectionStartSym);
637 auto InsertResult = getContext().addGenDwarfSection(
638 getStreamer().getCurrentSection().first);
639 assert(InsertResult.second && ".text section should not have debug info yet");
640 InsertResult.first->second.first = SectionStartSym;
641 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
642 0, StringRef(), getContext().getMainFileName()));
645 // While we have input, parse each statement.
646 while (Lexer.isNot(AsmToken::Eof)) {
647 ParseStatementInfo Info;
648 if (!parseStatement(Info))
651 // We had an error, validate that one was emitted and recover by skipping to
653 assert(HadError && "Parse statement returned an error, but none emitted!");
654 eatToEndOfStatement();
657 if (TheCondState.TheCond != StartingCondState.TheCond ||
658 TheCondState.Ignore != StartingCondState.Ignore)
659 return TokError("unmatched .ifs or .elses");
661 // Check to see there are no empty DwarfFile slots.
662 const auto &LineTables = getContext().getMCDwarfLineTables();
663 if (!LineTables.empty()) {
665 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
666 if (File.Name.empty() && Index != 0)
667 TokError("unassigned file number: " + Twine(Index) +
668 " for .file directives");
673 // Check to see that all assembler local symbols were actually defined.
674 // Targets that don't do subsections via symbols may not want this, though,
675 // so conservatively exclude them. Only do this if we're finalizing, though,
676 // as otherwise we won't necessarilly have seen everything yet.
677 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
678 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
679 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
682 MCSymbol *Sym = i->getValue();
683 // Variable symbols may not be marked as defined, so check those
684 // explicitly. If we know it's a variable, we have a definition for
685 // the purposes of this check.
686 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
687 // FIXME: We would really like to refer back to where the symbol was
688 // first referenced for a source location. We need to add something
689 // to track that. Currently, we just point to the end of the file.
691 getLexer().getLoc(), SourceMgr::DK_Error,
692 "assembler local symbol '" + Sym->getName() + "' not defined");
696 // Finalize the output stream if there are no errors and if the client wants
698 if (!HadError && !NoFinalize)
704 void AsmParser::checkForValidSection() {
705 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
706 TokError("expected section directive before assembly directive");
711 /// \brief Throw away the rest of the line for testing purposes.
712 void AsmParser::eatToEndOfStatement() {
713 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
717 if (Lexer.is(AsmToken::EndOfStatement))
721 StringRef AsmParser::parseStringToEndOfStatement() {
722 const char *Start = getTok().getLoc().getPointer();
724 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
727 const char *End = getTok().getLoc().getPointer();
728 return StringRef(Start, End - Start);
731 StringRef AsmParser::parseStringToComma() {
732 const char *Start = getTok().getLoc().getPointer();
734 while (Lexer.isNot(AsmToken::EndOfStatement) &&
735 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
738 const char *End = getTok().getLoc().getPointer();
739 return StringRef(Start, End - Start);
742 /// \brief Parse a paren expression and return it.
743 /// NOTE: This assumes the leading '(' has already been consumed.
745 /// parenexpr ::= expr)
747 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
748 if (parseExpression(Res))
750 if (Lexer.isNot(AsmToken::RParen))
751 return TokError("expected ')' in parentheses expression");
752 EndLoc = Lexer.getTok().getEndLoc();
757 /// \brief Parse a bracket expression and return it.
758 /// NOTE: This assumes the leading '[' has already been consumed.
760 /// bracketexpr ::= expr]
762 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
763 if (parseExpression(Res))
765 if (Lexer.isNot(AsmToken::RBrac))
766 return TokError("expected ']' in brackets expression");
767 EndLoc = Lexer.getTok().getEndLoc();
772 /// \brief Parse a primary expression and return it.
773 /// primaryexpr ::= (parenexpr
774 /// primaryexpr ::= symbol
775 /// primaryexpr ::= number
776 /// primaryexpr ::= '.'
777 /// primaryexpr ::= ~,+,- primaryexpr
778 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
779 SMLoc FirstTokenLoc = getLexer().getLoc();
780 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
781 switch (FirstTokenKind) {
783 return TokError("unknown token in expression");
784 // If we have an error assume that we've already handled it.
785 case AsmToken::Error:
787 case AsmToken::Exclaim:
788 Lex(); // Eat the operator.
789 if (parsePrimaryExpr(Res, EndLoc))
791 Res = MCUnaryExpr::CreateLNot(Res, getContext());
793 case AsmToken::Dollar:
795 case AsmToken::String:
796 case AsmToken::Identifier: {
797 StringRef Identifier;
798 if (parseIdentifier(Identifier)) {
799 if (FirstTokenKind == AsmToken::Dollar) {
800 if (Lexer.getMAI().getDollarIsPC()) {
801 // This is a '$' reference, which references the current PC. Emit a
802 // temporary label to the streamer and refer to it.
803 MCSymbol *Sym = Ctx.CreateTempSymbol();
805 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
807 EndLoc = FirstTokenLoc;
810 return Error(FirstTokenLoc, "invalid token in expression");
813 // Parse symbol variant
814 std::pair<StringRef, StringRef> Split;
815 if (!MAI.useParensForSymbolVariant()) {
816 if (FirstTokenKind == AsmToken::String) {
817 if (Lexer.is(AsmToken::At)) {
818 Lexer.Lex(); // eat @
819 SMLoc AtLoc = getLexer().getLoc();
821 if (parseIdentifier(VName))
822 return Error(AtLoc, "expected symbol variant after '@'");
824 Split = std::make_pair(Identifier, VName);
827 Split = Identifier.split('@');
829 } else if (Lexer.is(AsmToken::LParen)) {
830 Lexer.Lex(); // eat (
832 parseIdentifier(VName);
833 if (Lexer.isNot(AsmToken::RParen)) {
834 return Error(Lexer.getTok().getLoc(),
835 "unexpected token in variant, expected ')'");
837 Lexer.Lex(); // eat )
838 Split = std::make_pair(Identifier, VName);
841 EndLoc = SMLoc::getFromPointer(Identifier.end());
843 // This is a symbol reference.
844 StringRef SymbolName = Identifier;
845 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
847 // Lookup the symbol variant if used.
848 if (Split.second.size()) {
849 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
850 if (Variant != MCSymbolRefExpr::VK_Invalid) {
851 SymbolName = Split.first;
852 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
853 Variant = MCSymbolRefExpr::VK_None;
855 return Error(SMLoc::getFromPointer(Split.second.begin()),
856 "invalid variant '" + Split.second + "'");
860 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
862 // If this is an absolute variable reference, substitute it now to preserve
863 // semantics in the face of reassignment.
864 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
866 return Error(EndLoc, "unexpected modifier on variable reference");
868 Res = Sym->getVariableValue();
872 // Otherwise create a symbol ref.
873 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
876 case AsmToken::BigNum:
877 return TokError("literal value out of range for directive");
878 case AsmToken::Integer: {
879 SMLoc Loc = getTok().getLoc();
880 int64_t IntVal = getTok().getIntVal();
881 Res = MCConstantExpr::Create(IntVal, getContext());
882 EndLoc = Lexer.getTok().getEndLoc();
884 // Look for 'b' or 'f' following an Integer as a directional label
885 if (Lexer.getKind() == AsmToken::Identifier) {
886 StringRef IDVal = getTok().getString();
887 // Lookup the symbol variant if used.
888 std::pair<StringRef, StringRef> Split = IDVal.split('@');
889 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
890 if (Split.first.size() != IDVal.size()) {
891 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
892 if (Variant == MCSymbolRefExpr::VK_Invalid)
893 return TokError("invalid variant '" + Split.second + "'");
896 if (IDVal == "f" || IDVal == "b") {
898 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
899 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
900 if (IDVal == "b" && Sym->isUndefined())
901 return Error(Loc, "invalid reference to undefined symbol");
902 EndLoc = Lexer.getTok().getEndLoc();
903 Lex(); // Eat identifier.
908 case AsmToken::Real: {
909 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
910 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
911 Res = MCConstantExpr::Create(IntVal, getContext());
912 EndLoc = Lexer.getTok().getEndLoc();
916 case AsmToken::Dot: {
917 // This is a '.' reference, which references the current PC. Emit a
918 // temporary label to the streamer and refer to it.
919 MCSymbol *Sym = Ctx.CreateTempSymbol();
921 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
922 EndLoc = Lexer.getTok().getEndLoc();
923 Lex(); // Eat identifier.
926 case AsmToken::LParen:
927 Lex(); // Eat the '('.
928 return parseParenExpr(Res, EndLoc);
929 case AsmToken::LBrac:
930 if (!PlatformParser->HasBracketExpressions())
931 return TokError("brackets expression not supported on this target");
932 Lex(); // Eat the '['.
933 return parseBracketExpr(Res, EndLoc);
934 case AsmToken::Minus:
935 Lex(); // Eat the operator.
936 if (parsePrimaryExpr(Res, EndLoc))
938 Res = MCUnaryExpr::CreateMinus(Res, getContext());
941 Lex(); // Eat the operator.
942 if (parsePrimaryExpr(Res, EndLoc))
944 Res = MCUnaryExpr::CreatePlus(Res, getContext());
946 case AsmToken::Tilde:
947 Lex(); // Eat the operator.
948 if (parsePrimaryExpr(Res, EndLoc))
950 Res = MCUnaryExpr::CreateNot(Res, getContext());
955 bool AsmParser::parseExpression(const MCExpr *&Res) {
957 return parseExpression(Res, EndLoc);
961 AsmParser::applyModifierToExpr(const MCExpr *E,
962 MCSymbolRefExpr::VariantKind Variant) {
963 // Ask the target implementation about this expression first.
964 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
967 // Recurse over the given expression, rebuilding it to apply the given variant
968 // if there is exactly one symbol.
969 switch (E->getKind()) {
971 case MCExpr::Constant:
974 case MCExpr::SymbolRef: {
975 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
977 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
978 TokError("invalid variant on expression '" + getTok().getIdentifier() +
979 "' (already modified)");
983 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
986 case MCExpr::Unary: {
987 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
988 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
991 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
994 case MCExpr::Binary: {
995 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
996 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
997 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1007 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1011 llvm_unreachable("Invalid expression kind!");
1014 /// \brief Parse an expression and return it.
1016 /// expr ::= expr &&,|| expr -> lowest.
1017 /// expr ::= expr |,^,&,! expr
1018 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1019 /// expr ::= expr <<,>> expr
1020 /// expr ::= expr +,- expr
1021 /// expr ::= expr *,/,% expr -> highest.
1022 /// expr ::= primaryexpr
1024 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1025 // Parse the expression.
1027 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1030 // As a special case, we support 'a op b @ modifier' by rewriting the
1031 // expression to include the modifier. This is inefficient, but in general we
1032 // expect users to use 'a@modifier op b'.
1033 if (Lexer.getKind() == AsmToken::At) {
1036 if (Lexer.isNot(AsmToken::Identifier))
1037 return TokError("unexpected symbol modifier following '@'");
1039 MCSymbolRefExpr::VariantKind Variant =
1040 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1041 if (Variant == MCSymbolRefExpr::VK_Invalid)
1042 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1044 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1046 return TokError("invalid modifier '" + getTok().getIdentifier() +
1047 "' (no symbols present)");
1054 // Try to constant fold it up front, if possible.
1056 if (Res->EvaluateAsAbsolute(Value))
1057 Res = MCConstantExpr::Create(Value, getContext());
1062 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1064 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1067 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1070 SMLoc StartLoc = Lexer.getLoc();
1071 if (parseExpression(Expr))
1074 if (!Expr->EvaluateAsAbsolute(Res))
1075 return Error(StartLoc, "expected absolute expression");
1080 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1081 MCBinaryExpr::Opcode &Kind) {
1084 return 0; // not a binop.
1086 // Lowest Precedence: &&, ||
1087 case AsmToken::AmpAmp:
1088 Kind = MCBinaryExpr::LAnd;
1090 case AsmToken::PipePipe:
1091 Kind = MCBinaryExpr::LOr;
1094 // Low Precedence: |, &, ^
1096 // FIXME: gas seems to support '!' as an infix operator?
1097 case AsmToken::Pipe:
1098 Kind = MCBinaryExpr::Or;
1100 case AsmToken::Caret:
1101 Kind = MCBinaryExpr::Xor;
1104 Kind = MCBinaryExpr::And;
1107 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1108 case AsmToken::EqualEqual:
1109 Kind = MCBinaryExpr::EQ;
1111 case AsmToken::ExclaimEqual:
1112 case AsmToken::LessGreater:
1113 Kind = MCBinaryExpr::NE;
1115 case AsmToken::Less:
1116 Kind = MCBinaryExpr::LT;
1118 case AsmToken::LessEqual:
1119 Kind = MCBinaryExpr::LTE;
1121 case AsmToken::Greater:
1122 Kind = MCBinaryExpr::GT;
1124 case AsmToken::GreaterEqual:
1125 Kind = MCBinaryExpr::GTE;
1128 // Intermediate Precedence: <<, >>
1129 case AsmToken::LessLess:
1130 Kind = MCBinaryExpr::Shl;
1132 case AsmToken::GreaterGreater:
1133 Kind = MCBinaryExpr::Shr;
1136 // High Intermediate Precedence: +, -
1137 case AsmToken::Plus:
1138 Kind = MCBinaryExpr::Add;
1140 case AsmToken::Minus:
1141 Kind = MCBinaryExpr::Sub;
1144 // Highest Precedence: *, /, %
1145 case AsmToken::Star:
1146 Kind = MCBinaryExpr::Mul;
1148 case AsmToken::Slash:
1149 Kind = MCBinaryExpr::Div;
1151 case AsmToken::Percent:
1152 Kind = MCBinaryExpr::Mod;
1157 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1158 /// Res contains the LHS of the expression on input.
1159 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1162 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1163 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1165 // If the next token is lower precedence than we are allowed to eat, return
1166 // successfully with what we ate already.
1167 if (TokPrec < Precedence)
1172 // Eat the next primary expression.
1174 if (parsePrimaryExpr(RHS, EndLoc))
1177 // If BinOp binds less tightly with RHS than the operator after RHS, let
1178 // the pending operator take RHS as its LHS.
1179 MCBinaryExpr::Opcode Dummy;
1180 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1181 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1184 // Merge LHS and RHS according to operator.
1185 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1190 /// ::= EndOfStatement
1191 /// ::= Label* Directive ...Operands... EndOfStatement
1192 /// ::= Label* Identifier OperandList* EndOfStatement
1193 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1194 if (Lexer.is(AsmToken::EndOfStatement)) {
1200 // Statements always start with an identifier or are a full line comment.
1201 AsmToken ID = getTok();
1202 SMLoc IDLoc = ID.getLoc();
1204 int64_t LocalLabelVal = -1;
1205 // A full line comment is a '#' as the first token.
1206 if (Lexer.is(AsmToken::Hash))
1207 return parseCppHashLineFilenameComment(IDLoc);
1209 // Allow an integer followed by a ':' as a directional local label.
1210 if (Lexer.is(AsmToken::Integer)) {
1211 LocalLabelVal = getTok().getIntVal();
1212 if (LocalLabelVal < 0) {
1213 if (!TheCondState.Ignore)
1214 return TokError("unexpected token at start of statement");
1217 IDVal = getTok().getString();
1218 Lex(); // Consume the integer token to be used as an identifier token.
1219 if (Lexer.getKind() != AsmToken::Colon) {
1220 if (!TheCondState.Ignore)
1221 return TokError("unexpected token at start of statement");
1224 } else if (Lexer.is(AsmToken::Dot)) {
1225 // Treat '.' as a valid identifier in this context.
1228 } else if (parseIdentifier(IDVal)) {
1229 if (!TheCondState.Ignore)
1230 return TokError("unexpected token at start of statement");
1234 // Handle conditional assembly here before checking for skipping. We
1235 // have to do this so that .endif isn't skipped in a ".if 0" block for
1237 StringMap<DirectiveKind>::const_iterator DirKindIt =
1238 DirectiveKindMap.find(IDVal);
1239 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1241 : DirKindIt->getValue();
1252 return parseDirectiveIf(IDLoc, DirKind);
1254 return parseDirectiveIfb(IDLoc, true);
1256 return parseDirectiveIfb(IDLoc, false);
1258 return parseDirectiveIfc(IDLoc, true);
1260 return parseDirectiveIfeqs(IDLoc);
1262 return parseDirectiveIfc(IDLoc, false);
1264 return parseDirectiveIfdef(IDLoc, true);
1267 return parseDirectiveIfdef(IDLoc, false);
1269 return parseDirectiveElseIf(IDLoc);
1271 return parseDirectiveElse(IDLoc);
1273 return parseDirectiveEndIf(IDLoc);
1276 // Ignore the statement if in the middle of inactive conditional
1278 if (TheCondState.Ignore) {
1279 eatToEndOfStatement();
1283 // FIXME: Recurse on local labels?
1285 // See what kind of statement we have.
1286 switch (Lexer.getKind()) {
1287 case AsmToken::Colon: {
1288 checkForValidSection();
1290 // identifier ':' -> Label.
1293 // Diagnose attempt to use '.' as a label.
1295 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1297 // Diagnose attempt to use a variable as a label.
1299 // FIXME: Diagnostics. Note the location of the definition as a label.
1300 // FIXME: This doesn't diagnose assignment to a symbol which has been
1301 // implicitly marked as external.
1303 if (LocalLabelVal == -1)
1304 Sym = getContext().GetOrCreateSymbol(IDVal);
1306 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1307 if (!Sym->isUndefined() || Sym->isVariable())
1308 return Error(IDLoc, "invalid symbol redefinition");
1311 if (!ParsingInlineAsm)
1314 // If we are generating dwarf for assembly source files then gather the
1315 // info to make a dwarf label entry for this label if needed.
1316 if (getContext().getGenDwarfForAssembly())
1317 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1320 getTargetParser().onLabelParsed(Sym);
1322 // Consume any end of statement token, if present, to avoid spurious
1323 // AddBlankLine calls().
1324 if (Lexer.is(AsmToken::EndOfStatement)) {
1326 if (Lexer.is(AsmToken::Eof))
1333 case AsmToken::Equal:
1334 // identifier '=' ... -> assignment statement
1337 return parseAssignment(IDVal, true);
1339 default: // Normal instruction or directive.
1343 // If macros are enabled, check to see if this is a macro instantiation.
1344 if (areMacrosEnabled())
1345 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1346 return handleMacroEntry(M, IDLoc);
1349 // Otherwise, we have a normal instruction or directive.
1351 // Directives start with "."
1352 if (IDVal[0] == '.' && IDVal != ".") {
1353 // There are several entities interested in parsing directives:
1355 // 1. The target-specific assembly parser. Some directives are target
1356 // specific or may potentially behave differently on certain targets.
1357 // 2. Asm parser extensions. For example, platform-specific parsers
1358 // (like the ELF parser) register themselves as extensions.
1359 // 3. The generic directive parser implemented by this class. These are
1360 // all the directives that behave in a target and platform independent
1361 // manner, or at least have a default behavior that's shared between
1362 // all targets and platforms.
1364 // First query the target-specific parser. It will return 'true' if it
1365 // isn't interested in this directive.
1366 if (!getTargetParser().ParseDirective(ID))
1369 // Next, check the extension directive map to see if any extension has
1370 // registered itself to parse this directive.
1371 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1372 ExtensionDirectiveMap.lookup(IDVal);
1374 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1376 // Finally, if no one else is interested in this directive, it must be
1377 // generic and familiar to this class.
1383 return parseDirectiveSet(IDVal, true);
1385 return parseDirectiveSet(IDVal, false);
1387 return parseDirectiveAscii(IDVal, false);
1390 return parseDirectiveAscii(IDVal, true);
1392 return parseDirectiveValue(1);
1396 return parseDirectiveValue(2);
1400 return parseDirectiveValue(4);
1403 return parseDirectiveValue(8);
1405 return parseDirectiveOctaValue();
1408 return parseDirectiveRealValue(APFloat::IEEEsingle);
1410 return parseDirectiveRealValue(APFloat::IEEEdouble);
1412 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1413 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1416 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1417 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1420 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1422 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1424 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1426 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1428 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1430 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1432 return parseDirectiveOrg();
1434 return parseDirectiveFill();
1436 return parseDirectiveZero();
1438 eatToEndOfStatement(); // .extern is the default, ignore it.
1442 return parseDirectiveSymbolAttribute(MCSA_Global);
1443 case DK_LAZY_REFERENCE:
1444 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1445 case DK_NO_DEAD_STRIP:
1446 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1447 case DK_SYMBOL_RESOLVER:
1448 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1449 case DK_PRIVATE_EXTERN:
1450 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1452 return parseDirectiveSymbolAttribute(MCSA_Reference);
1453 case DK_WEAK_DEFINITION:
1454 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1455 case DK_WEAK_REFERENCE:
1456 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1457 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1458 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1461 return parseDirectiveComm(/*IsLocal=*/false);
1463 return parseDirectiveComm(/*IsLocal=*/true);
1465 return parseDirectiveAbort();
1467 return parseDirectiveInclude();
1469 return parseDirectiveIncbin();
1472 return TokError(Twine(IDVal) + " not supported yet");
1474 return parseDirectiveRept(IDLoc, IDVal);
1476 return parseDirectiveIrp(IDLoc);
1478 return parseDirectiveIrpc(IDLoc);
1480 return parseDirectiveEndr(IDLoc);
1481 case DK_BUNDLE_ALIGN_MODE:
1482 return parseDirectiveBundleAlignMode();
1483 case DK_BUNDLE_LOCK:
1484 return parseDirectiveBundleLock();
1485 case DK_BUNDLE_UNLOCK:
1486 return parseDirectiveBundleUnlock();
1488 return parseDirectiveLEB128(true);
1490 return parseDirectiveLEB128(false);
1493 return parseDirectiveSpace(IDVal);
1495 return parseDirectiveFile(IDLoc);
1497 return parseDirectiveLine();
1499 return parseDirectiveLoc();
1501 return parseDirectiveStabs();
1502 case DK_CFI_SECTIONS:
1503 return parseDirectiveCFISections();
1504 case DK_CFI_STARTPROC:
1505 return parseDirectiveCFIStartProc();
1506 case DK_CFI_ENDPROC:
1507 return parseDirectiveCFIEndProc();
1508 case DK_CFI_DEF_CFA:
1509 return parseDirectiveCFIDefCfa(IDLoc);
1510 case DK_CFI_DEF_CFA_OFFSET:
1511 return parseDirectiveCFIDefCfaOffset();
1512 case DK_CFI_ADJUST_CFA_OFFSET:
1513 return parseDirectiveCFIAdjustCfaOffset();
1514 case DK_CFI_DEF_CFA_REGISTER:
1515 return parseDirectiveCFIDefCfaRegister(IDLoc);
1517 return parseDirectiveCFIOffset(IDLoc);
1518 case DK_CFI_REL_OFFSET:
1519 return parseDirectiveCFIRelOffset(IDLoc);
1520 case DK_CFI_PERSONALITY:
1521 return parseDirectiveCFIPersonalityOrLsda(true);
1523 return parseDirectiveCFIPersonalityOrLsda(false);
1524 case DK_CFI_REMEMBER_STATE:
1525 return parseDirectiveCFIRememberState();
1526 case DK_CFI_RESTORE_STATE:
1527 return parseDirectiveCFIRestoreState();
1528 case DK_CFI_SAME_VALUE:
1529 return parseDirectiveCFISameValue(IDLoc);
1530 case DK_CFI_RESTORE:
1531 return parseDirectiveCFIRestore(IDLoc);
1533 return parseDirectiveCFIEscape();
1534 case DK_CFI_SIGNAL_FRAME:
1535 return parseDirectiveCFISignalFrame();
1536 case DK_CFI_UNDEFINED:
1537 return parseDirectiveCFIUndefined(IDLoc);
1538 case DK_CFI_REGISTER:
1539 return parseDirectiveCFIRegister(IDLoc);
1540 case DK_CFI_WINDOW_SAVE:
1541 return parseDirectiveCFIWindowSave();
1544 return parseDirectiveMacrosOnOff(IDVal);
1546 return parseDirectiveMacro(IDLoc);
1548 return parseDirectiveExitMacro(IDVal);
1551 return parseDirectiveEndMacro(IDVal);
1553 return parseDirectivePurgeMacro(IDLoc);
1555 return parseDirectiveEnd(IDLoc);
1557 return parseDirectiveError(IDLoc, false);
1559 return parseDirectiveError(IDLoc, true);
1561 return parseDirectiveWarning(IDLoc);
1564 return Error(IDLoc, "unknown directive");
1567 // __asm _emit or __asm __emit
1568 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1569 IDVal == "_EMIT" || IDVal == "__EMIT"))
1570 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1573 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1574 return parseDirectiveMSAlign(IDLoc, Info);
1576 checkForValidSection();
1578 // Canonicalize the opcode to lower case.
1579 std::string OpcodeStr = IDVal.lower();
1580 ParseInstructionInfo IInfo(Info.AsmRewrites);
1581 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1582 Info.ParsedOperands);
1583 Info.ParseError = HadError;
1585 // Dump the parsed representation, if requested.
1586 if (getShowParsedOperands()) {
1587 SmallString<256> Str;
1588 raw_svector_ostream OS(Str);
1589 OS << "parsed instruction: [";
1590 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1593 Info.ParsedOperands[i]->print(OS);
1597 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1600 // If we are generating dwarf for the current section then generate a .loc
1601 // directive for the instruction.
1602 if (!HadError && getContext().getGenDwarfForAssembly() &&
1603 getContext().getGenDwarfSectionSyms().count(
1604 getStreamer().getCurrentSection().first)) {
1606 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1608 // If we previously parsed a cpp hash file line comment then make sure the
1609 // current Dwarf File is for the CppHashFilename if not then emit the
1610 // Dwarf File table for it and adjust the line number for the .loc.
1611 if (CppHashFilename.size() != 0) {
1612 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1613 0, StringRef(), CppHashFilename);
1614 getContext().setGenDwarfFileNumber(FileNumber);
1616 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1617 // cache with the different Loc from the call above we save the last
1618 // info we queried here with SrcMgr.FindLineNumber().
1619 unsigned CppHashLocLineNo;
1620 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1621 CppHashLocLineNo = LastQueryLine;
1623 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1624 LastQueryLine = CppHashLocLineNo;
1625 LastQueryIDLoc = CppHashLoc;
1626 LastQueryBuffer = CppHashBuf;
1628 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1631 getStreamer().EmitDwarfLocDirective(
1632 getContext().getGenDwarfFileNumber(), Line, 0,
1633 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1637 // If parsing succeeded, match the instruction.
1640 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1641 Info.ParsedOperands, Out,
1642 ErrorInfo, ParsingInlineAsm);
1645 // Don't skip the rest of the line, the instruction parser is responsible for
1650 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1651 /// since they may not be able to be tokenized to get to the end of line token.
1652 void AsmParser::eatToEndOfLine() {
1653 if (!Lexer.is(AsmToken::EndOfStatement))
1654 Lexer.LexUntilEndOfLine();
1659 /// parseCppHashLineFilenameComment as this:
1660 /// ::= # number "filename"
1661 /// or just as a full line comment if it doesn't have a number and a string.
1662 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1663 Lex(); // Eat the hash token.
1665 if (getLexer().isNot(AsmToken::Integer)) {
1666 // Consume the line since in cases it is not a well-formed line directive,
1667 // as if were simply a full line comment.
1672 int64_t LineNumber = getTok().getIntVal();
1675 if (getLexer().isNot(AsmToken::String)) {
1680 StringRef Filename = getTok().getString();
1681 // Get rid of the enclosing quotes.
1682 Filename = Filename.substr(1, Filename.size() - 2);
1684 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1686 CppHashFilename = Filename;
1687 CppHashLineNumber = LineNumber;
1688 CppHashBuf = CurBuffer;
1690 // Ignore any trailing characters, they're just comment.
1695 /// \brief will use the last parsed cpp hash line filename comment
1696 /// for the Filename and LineNo if any in the diagnostic.
1697 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1698 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1699 raw_ostream &OS = errs();
1701 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1702 const SMLoc &DiagLoc = Diag.getLoc();
1703 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1704 unsigned CppHashBuf =
1705 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1707 // Like SourceMgr::printMessage() we need to print the include stack if any
1708 // before printing the message.
1709 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1710 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1711 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1712 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1713 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1716 // If we have not parsed a cpp hash line filename comment or the source
1717 // manager changed or buffer changed (like in a nested include) then just
1718 // print the normal diagnostic using its Filename and LineNo.
1719 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1720 DiagBuf != CppHashBuf) {
1721 if (Parser->SavedDiagHandler)
1722 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1724 Diag.print(nullptr, OS);
1728 // Use the CppHashFilename and calculate a line number based on the
1729 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1731 const std::string &Filename = Parser->CppHashFilename;
1733 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1734 int CppHashLocLineNo =
1735 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1737 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1739 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1740 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1741 Diag.getLineContents(), Diag.getRanges());
1743 if (Parser->SavedDiagHandler)
1744 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1746 NewDiag.print(nullptr, OS);
1749 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1750 // difference being that that function accepts '@' as part of identifiers and
1751 // we can't do that. AsmLexer.cpp should probably be changed to handle
1752 // '@' as a special case when needed.
1753 static bool isIdentifierChar(char c) {
1754 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1758 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1759 ArrayRef<MCAsmMacroParameter> Parameters,
1760 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1761 unsigned NParameters = Parameters.size();
1762 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1763 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1764 return Error(L, "Wrong number of arguments");
1766 // A macro without parameters is handled differently on Darwin:
1767 // gas accepts no arguments and does no substitutions
1768 while (!Body.empty()) {
1769 // Scan for the next substitution.
1770 std::size_t End = Body.size(), Pos = 0;
1771 for (; Pos != End; ++Pos) {
1772 // Check for a substitution or escape.
1773 if (IsDarwin && !NParameters) {
1774 // This macro has no parameters, look for $0, $1, etc.
1775 if (Body[Pos] != '$' || Pos + 1 == End)
1778 char Next = Body[Pos + 1];
1779 if (Next == '$' || Next == 'n' ||
1780 isdigit(static_cast<unsigned char>(Next)))
1783 // This macro has parameters, look for \foo, \bar, etc.
1784 if (Body[Pos] == '\\' && Pos + 1 != End)
1790 OS << Body.slice(0, Pos);
1792 // Check if we reached the end.
1796 if (IsDarwin && !NParameters) {
1797 switch (Body[Pos + 1]) {
1803 // $n => number of arguments
1808 // $[0-9] => argument
1810 // Missing arguments are ignored.
1811 unsigned Index = Body[Pos + 1] - '0';
1812 if (Index >= A.size())
1815 // Otherwise substitute with the token values, with spaces eliminated.
1816 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1817 ie = A[Index].end();
1819 OS << it->getString();
1825 unsigned I = Pos + 1;
1826 while (isIdentifierChar(Body[I]) && I + 1 != End)
1829 const char *Begin = Body.data() + Pos + 1;
1830 StringRef Argument(Begin, I - (Pos + 1));
1832 for (; Index < NParameters; ++Index)
1833 if (Parameters[Index].Name == Argument)
1836 if (Index == NParameters) {
1837 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1840 OS << '\\' << Argument;
1844 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1845 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1846 ie = A[Index].end();
1848 // We expect no quotes around the string's contents when
1849 // parsing for varargs.
1850 if (it->getKind() != AsmToken::String || VarargParameter)
1851 OS << it->getString();
1853 OS << it->getStringContents();
1855 Pos += 1 + Argument.size();
1858 // Update the scan point.
1859 Body = Body.substr(Pos);
1865 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1866 StringRef I, size_t CondStackDepth)
1867 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1868 CondStackDepth(CondStackDepth) {}
1870 static bool isOperator(AsmToken::TokenKind kind) {
1874 case AsmToken::Plus:
1875 case AsmToken::Minus:
1876 case AsmToken::Tilde:
1877 case AsmToken::Slash:
1878 case AsmToken::Star:
1880 case AsmToken::Equal:
1881 case AsmToken::EqualEqual:
1882 case AsmToken::Pipe:
1883 case AsmToken::PipePipe:
1884 case AsmToken::Caret:
1886 case AsmToken::AmpAmp:
1887 case AsmToken::Exclaim:
1888 case AsmToken::ExclaimEqual:
1889 case AsmToken::Percent:
1890 case AsmToken::Less:
1891 case AsmToken::LessEqual:
1892 case AsmToken::LessLess:
1893 case AsmToken::LessGreater:
1894 case AsmToken::Greater:
1895 case AsmToken::GreaterEqual:
1896 case AsmToken::GreaterGreater:
1902 class AsmLexerSkipSpaceRAII {
1904 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1905 Lexer.setSkipSpace(SkipSpace);
1908 ~AsmLexerSkipSpaceRAII() {
1909 Lexer.setSkipSpace(true);
1917 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1920 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1921 StringRef Str = parseStringToEndOfStatement();
1922 MA.push_back(AsmToken(AsmToken::String, Str));
1927 unsigned ParenLevel = 0;
1928 unsigned AddTokens = 0;
1930 // Darwin doesn't use spaces to delmit arguments.
1931 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1934 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1935 return TokError("unexpected token in macro instantiation");
1937 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1940 if (Lexer.is(AsmToken::Space)) {
1941 Lex(); // Eat spaces
1943 // Spaces can delimit parameters, but could also be part an expression.
1944 // If the token after a space is an operator, add the token and the next
1945 // one into this argument
1947 if (isOperator(Lexer.getKind())) {
1948 // Check to see whether the token is used as an operator,
1949 // or part of an identifier
1950 const char *NextChar = getTok().getEndLoc().getPointer();
1951 if (*NextChar == ' ')
1955 if (!AddTokens && ParenLevel == 0) {
1961 // handleMacroEntry relies on not advancing the lexer here
1962 // to be able to fill in the remaining default parameter values
1963 if (Lexer.is(AsmToken::EndOfStatement))
1966 // Adjust the current parentheses level.
1967 if (Lexer.is(AsmToken::LParen))
1969 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1972 // Append the token to the current argument list.
1973 MA.push_back(getTok());
1979 if (ParenLevel != 0)
1980 return TokError("unbalanced parentheses in macro argument");
1984 // Parse the macro instantiation arguments.
1985 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1986 MCAsmMacroArguments &A) {
1987 const unsigned NParameters = M ? M->Parameters.size() : 0;
1988 bool NamedParametersFound = false;
1989 SmallVector<SMLoc, 4> FALocs;
1991 A.resize(NParameters);
1992 FALocs.resize(NParameters);
1994 // Parse two kinds of macro invocations:
1995 // - macros defined without any parameters accept an arbitrary number of them
1996 // - macros defined with parameters accept at most that many of them
1997 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1998 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2000 SMLoc IDLoc = Lexer.getLoc();
2001 MCAsmMacroParameter FA;
2003 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2004 if (parseIdentifier(FA.Name)) {
2005 Error(IDLoc, "invalid argument identifier for formal argument");
2006 eatToEndOfStatement();
2010 if (!Lexer.is(AsmToken::Equal)) {
2011 TokError("expected '=' after formal parameter identifier");
2012 eatToEndOfStatement();
2017 NamedParametersFound = true;
2020 if (NamedParametersFound && FA.Name.empty()) {
2021 Error(IDLoc, "cannot mix positional and keyword arguments");
2022 eatToEndOfStatement();
2026 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2027 if (parseMacroArgument(FA.Value, Vararg))
2030 unsigned PI = Parameter;
2031 if (!FA.Name.empty()) {
2033 for (FAI = 0; FAI < NParameters; ++FAI)
2034 if (M->Parameters[FAI].Name == FA.Name)
2037 if (FAI >= NParameters) {
2038 assert(M && "expected macro to be defined");
2040 "parameter named '" + FA.Name + "' does not exist for macro '" +
2047 if (!FA.Value.empty()) {
2052 if (FALocs.size() <= PI)
2053 FALocs.resize(PI + 1);
2055 FALocs[PI] = Lexer.getLoc();
2058 // At the end of the statement, fill in remaining arguments that have
2059 // default values. If there aren't any, then the next argument is
2060 // required but missing
2061 if (Lexer.is(AsmToken::EndOfStatement)) {
2062 bool Failure = false;
2063 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2064 if (A[FAI].empty()) {
2065 if (M->Parameters[FAI].Required) {
2066 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2067 "missing value for required parameter "
2068 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2072 if (!M->Parameters[FAI].Value.empty())
2073 A[FAI] = M->Parameters[FAI].Value;
2079 if (Lexer.is(AsmToken::Comma))
2083 return TokError("too many positional arguments");
2086 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2087 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2088 return (I == MacroMap.end()) ? nullptr : I->getValue();
2091 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2092 MacroMap[Name] = new MCAsmMacro(Macro);
2095 void AsmParser::undefineMacro(StringRef Name) {
2096 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2097 if (I != MacroMap.end()) {
2098 delete I->getValue();
2103 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2104 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2105 // this, although we should protect against infinite loops.
2106 if (ActiveMacros.size() == 20)
2107 return TokError("macros cannot be nested more than 20 levels deep");
2109 MCAsmMacroArguments A;
2110 if (parseMacroArguments(M, A))
2113 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2114 // to hold the macro body with substitutions.
2115 SmallString<256> Buf;
2116 StringRef Body = M->Body;
2117 raw_svector_ostream OS(Buf);
2119 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2122 // We include the .endmacro in the buffer as our cue to exit the macro
2124 OS << ".endmacro\n";
2126 MemoryBuffer *Instantiation =
2127 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2129 // Create the macro instantiation object and add to the current macro
2130 // instantiation stack.
2131 MacroInstantiation *MI =
2132 new MacroInstantiation(NameLoc, CurBuffer, getTok().getLoc(),
2133 Instantiation->getBuffer(), TheCondStack.size());
2134 ActiveMacros.push_back(MI);
2136 // Jump to the macro instantiation and prime the lexer.
2137 CurBuffer = SrcMgr.AddNewSourceBuffer(Instantiation, SMLoc());
2138 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2144 void AsmParser::handleMacroExit() {
2145 // Jump to the EndOfStatement we should return to, and consume it.
2146 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2149 // Pop the instantiation entry.
2150 delete ActiveMacros.back();
2151 ActiveMacros.pop_back();
2154 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2155 switch (Value->getKind()) {
2156 case MCExpr::Binary: {
2157 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2158 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2160 case MCExpr::Target:
2161 case MCExpr::Constant:
2163 case MCExpr::SymbolRef: {
2165 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2167 return isUsedIn(Sym, S.getVariableValue());
2171 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2174 llvm_unreachable("Unknown expr kind!");
2177 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2179 // FIXME: Use better location, we should use proper tokens.
2180 SMLoc EqualLoc = Lexer.getLoc();
2182 const MCExpr *Value;
2183 if (parseExpression(Value))
2186 // Note: we don't count b as used in "a = b". This is to allow
2190 if (Lexer.isNot(AsmToken::EndOfStatement))
2191 return TokError("unexpected token in assignment");
2193 // Eat the end of statement marker.
2196 // Validate that the LHS is allowed to be a variable (either it has not been
2197 // used as a symbol, or it is an absolute symbol).
2198 MCSymbol *Sym = getContext().LookupSymbol(Name);
2200 // Diagnose assignment to a label.
2202 // FIXME: Diagnostics. Note the location of the definition as a label.
2203 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2204 if (isUsedIn(Sym, Value))
2205 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2206 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2207 ; // Allow redefinitions of undefined symbols only used in directives.
2208 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2209 ; // Allow redefinitions of variables that haven't yet been used.
2210 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2211 return Error(EqualLoc, "redefinition of '" + Name + "'");
2212 else if (!Sym->isVariable())
2213 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2214 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2215 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2218 // Don't count these checks as uses.
2219 Sym->setUsed(false);
2220 } else if (Name == ".") {
2221 if (Out.EmitValueToOffset(Value, 0)) {
2222 Error(EqualLoc, "expected absolute expression");
2223 eatToEndOfStatement();
2227 Sym = getContext().GetOrCreateSymbol(Name);
2229 // Do the assignment.
2230 Out.EmitAssignment(Sym, Value);
2232 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2237 /// parseIdentifier:
2240 bool AsmParser::parseIdentifier(StringRef &Res) {
2241 // The assembler has relaxed rules for accepting identifiers, in particular we
2242 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2243 // separate tokens. At this level, we have already lexed so we cannot (currently)
2244 // handle this as a context dependent token, instead we detect adjacent tokens
2245 // and return the combined identifier.
2246 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2247 SMLoc PrefixLoc = getLexer().getLoc();
2249 // Consume the prefix character, and check for a following identifier.
2251 if (Lexer.isNot(AsmToken::Identifier))
2254 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2255 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2258 // Construct the joined identifier and consume the token.
2260 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2265 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2268 Res = getTok().getIdentifier();
2270 Lex(); // Consume the identifier token.
2275 /// parseDirectiveSet:
2276 /// ::= .equ identifier ',' expression
2277 /// ::= .equiv identifier ',' expression
2278 /// ::= .set identifier ',' expression
2279 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2282 if (parseIdentifier(Name))
2283 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2285 if (getLexer().isNot(AsmToken::Comma))
2286 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2289 return parseAssignment(Name, allow_redef, true);
2292 bool AsmParser::parseEscapedString(std::string &Data) {
2293 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2296 StringRef Str = getTok().getStringContents();
2297 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2298 if (Str[i] != '\\') {
2303 // Recognize escaped characters. Note that this escape semantics currently
2304 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2307 return TokError("unexpected backslash at end of string");
2309 // Recognize octal sequences.
2310 if ((unsigned)(Str[i] - '0') <= 7) {
2311 // Consume up to three octal characters.
2312 unsigned Value = Str[i] - '0';
2314 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2316 Value = Value * 8 + (Str[i] - '0');
2318 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2320 Value = Value * 8 + (Str[i] - '0');
2325 return TokError("invalid octal escape sequence (out of range)");
2327 Data += (unsigned char)Value;
2331 // Otherwise recognize individual escapes.
2334 // Just reject invalid escape sequences for now.
2335 return TokError("invalid escape sequence (unrecognized character)");
2337 case 'b': Data += '\b'; break;
2338 case 'f': Data += '\f'; break;
2339 case 'n': Data += '\n'; break;
2340 case 'r': Data += '\r'; break;
2341 case 't': Data += '\t'; break;
2342 case '"': Data += '"'; break;
2343 case '\\': Data += '\\'; break;
2350 /// parseDirectiveAscii:
2351 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2352 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2354 checkForValidSection();
2357 if (getLexer().isNot(AsmToken::String))
2358 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2361 if (parseEscapedString(Data))
2364 getStreamer().EmitBytes(Data);
2366 getStreamer().EmitBytes(StringRef("\0", 1));
2370 if (getLexer().is(AsmToken::EndOfStatement))
2373 if (getLexer().isNot(AsmToken::Comma))
2374 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2383 /// parseDirectiveValue
2384 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2385 bool AsmParser::parseDirectiveValue(unsigned Size) {
2386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2387 checkForValidSection();
2390 const MCExpr *Value;
2391 SMLoc ExprLoc = getLexer().getLoc();
2392 if (parseExpression(Value))
2395 // Special case constant expressions to match code generator.
2396 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2397 assert(Size <= 8 && "Invalid size");
2398 uint64_t IntValue = MCE->getValue();
2399 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2400 return Error(ExprLoc, "literal value out of range for directive");
2401 getStreamer().EmitIntValue(IntValue, Size);
2403 getStreamer().EmitValue(Value, Size, ExprLoc);
2405 if (getLexer().is(AsmToken::EndOfStatement))
2408 // FIXME: Improve diagnostic.
2409 if (getLexer().isNot(AsmToken::Comma))
2410 return TokError("unexpected token in directive");
2419 /// ParseDirectiveOctaValue
2420 /// ::= .octa [ hexconstant (, hexconstant)* ]
2421 bool AsmParser::parseDirectiveOctaValue() {
2422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2423 checkForValidSection();
2426 if (Lexer.getKind() == AsmToken::Error)
2428 if (Lexer.getKind() != AsmToken::Integer &&
2429 Lexer.getKind() != AsmToken::BigNum)
2430 return TokError("unknown token in expression");
2432 SMLoc ExprLoc = getLexer().getLoc();
2433 APInt IntValue = getTok().getAPIntVal();
2437 if (IntValue.isIntN(64)) {
2439 lo = IntValue.getZExtValue();
2440 } else if (IntValue.isIntN(128)) {
2441 // It might actually have more than 128 bits, but the top ones are zero.
2442 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2443 lo = IntValue.getLoBits(64).getZExtValue();
2445 return Error(ExprLoc, "literal value out of range for directive");
2447 if (MAI.isLittleEndian()) {
2448 getStreamer().EmitIntValue(lo, 8);
2449 getStreamer().EmitIntValue(hi, 8);
2451 getStreamer().EmitIntValue(hi, 8);
2452 getStreamer().EmitIntValue(lo, 8);
2455 if (getLexer().is(AsmToken::EndOfStatement))
2458 // FIXME: Improve diagnostic.
2459 if (getLexer().isNot(AsmToken::Comma))
2460 return TokError("unexpected token in directive");
2469 /// parseDirectiveRealValue
2470 /// ::= (.single | .double) [ expression (, expression)* ]
2471 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2472 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2473 checkForValidSection();
2476 // We don't truly support arithmetic on floating point expressions, so we
2477 // have to manually parse unary prefixes.
2479 if (getLexer().is(AsmToken::Minus)) {
2482 } else if (getLexer().is(AsmToken::Plus))
2485 if (getLexer().isNot(AsmToken::Integer) &&
2486 getLexer().isNot(AsmToken::Real) &&
2487 getLexer().isNot(AsmToken::Identifier))
2488 return TokError("unexpected token in directive");
2490 // Convert to an APFloat.
2491 APFloat Value(Semantics);
2492 StringRef IDVal = getTok().getString();
2493 if (getLexer().is(AsmToken::Identifier)) {
2494 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2495 Value = APFloat::getInf(Semantics);
2496 else if (!IDVal.compare_lower("nan"))
2497 Value = APFloat::getNaN(Semantics, false, ~0);
2499 return TokError("invalid floating point literal");
2500 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2501 APFloat::opInvalidOp)
2502 return TokError("invalid floating point literal");
2506 // Consume the numeric token.
2509 // Emit the value as an integer.
2510 APInt AsInt = Value.bitcastToAPInt();
2511 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2512 AsInt.getBitWidth() / 8);
2514 if (getLexer().is(AsmToken::EndOfStatement))
2517 if (getLexer().isNot(AsmToken::Comma))
2518 return TokError("unexpected token in directive");
2527 /// parseDirectiveZero
2528 /// ::= .zero expression
2529 bool AsmParser::parseDirectiveZero() {
2530 checkForValidSection();
2533 if (parseAbsoluteExpression(NumBytes))
2537 if (getLexer().is(AsmToken::Comma)) {
2539 if (parseAbsoluteExpression(Val))
2543 if (getLexer().isNot(AsmToken::EndOfStatement))
2544 return TokError("unexpected token in '.zero' directive");
2548 getStreamer().EmitFill(NumBytes, Val);
2553 /// parseDirectiveFill
2554 /// ::= .fill expression [ , expression [ , expression ] ]
2555 bool AsmParser::parseDirectiveFill() {
2556 checkForValidSection();
2558 SMLoc RepeatLoc = getLexer().getLoc();
2560 if (parseAbsoluteExpression(NumValues))
2563 if (NumValues < 0) {
2565 "'.fill' directive with negative repeat count has no effect");
2569 int64_t FillSize = 1;
2570 int64_t FillExpr = 0;
2572 SMLoc SizeLoc, ExprLoc;
2573 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2574 if (getLexer().isNot(AsmToken::Comma))
2575 return TokError("unexpected token in '.fill' directive");
2578 SizeLoc = getLexer().getLoc();
2579 if (parseAbsoluteExpression(FillSize))
2582 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2583 if (getLexer().isNot(AsmToken::Comma))
2584 return TokError("unexpected token in '.fill' directive");
2587 ExprLoc = getLexer().getLoc();
2588 if (parseAbsoluteExpression(FillExpr))
2591 if (getLexer().isNot(AsmToken::EndOfStatement))
2592 return TokError("unexpected token in '.fill' directive");
2599 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2603 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2607 if (!isUInt<32>(FillExpr) && FillSize > 4)
2608 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2610 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2611 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2613 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2614 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2615 if (NonZeroFillSize < FillSize)
2616 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2622 /// parseDirectiveOrg
2623 /// ::= .org expression [ , expression ]
2624 bool AsmParser::parseDirectiveOrg() {
2625 checkForValidSection();
2627 const MCExpr *Offset;
2628 SMLoc Loc = getTok().getLoc();
2629 if (parseExpression(Offset))
2632 // Parse optional fill expression.
2633 int64_t FillExpr = 0;
2634 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2635 if (getLexer().isNot(AsmToken::Comma))
2636 return TokError("unexpected token in '.org' directive");
2639 if (parseAbsoluteExpression(FillExpr))
2642 if (getLexer().isNot(AsmToken::EndOfStatement))
2643 return TokError("unexpected token in '.org' directive");
2648 // Only limited forms of relocatable expressions are accepted here, it
2649 // has to be relative to the current section. The streamer will return
2650 // 'true' if the expression wasn't evaluatable.
2651 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2652 return Error(Loc, "expected assembly-time absolute expression");
2657 /// parseDirectiveAlign
2658 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2659 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2660 checkForValidSection();
2662 SMLoc AlignmentLoc = getLexer().getLoc();
2664 if (parseAbsoluteExpression(Alignment))
2668 bool HasFillExpr = false;
2669 int64_t FillExpr = 0;
2670 int64_t MaxBytesToFill = 0;
2671 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2672 if (getLexer().isNot(AsmToken::Comma))
2673 return TokError("unexpected token in directive");
2676 // The fill expression can be omitted while specifying a maximum number of
2677 // alignment bytes, e.g:
2679 if (getLexer().isNot(AsmToken::Comma)) {
2681 if (parseAbsoluteExpression(FillExpr))
2685 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2686 if (getLexer().isNot(AsmToken::Comma))
2687 return TokError("unexpected token in directive");
2690 MaxBytesLoc = getLexer().getLoc();
2691 if (parseAbsoluteExpression(MaxBytesToFill))
2694 if (getLexer().isNot(AsmToken::EndOfStatement))
2695 return TokError("unexpected token in directive");
2704 // Compute alignment in bytes.
2706 // FIXME: Diagnose overflow.
2707 if (Alignment >= 32) {
2708 Error(AlignmentLoc, "invalid alignment value");
2712 Alignment = 1ULL << Alignment;
2714 // Reject alignments that aren't a power of two, for gas compatibility.
2715 if (!isPowerOf2_64(Alignment))
2716 Error(AlignmentLoc, "alignment must be a power of 2");
2719 // Diagnose non-sensical max bytes to align.
2720 if (MaxBytesLoc.isValid()) {
2721 if (MaxBytesToFill < 1) {
2722 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2723 "many bytes, ignoring maximum bytes expression");
2727 if (MaxBytesToFill >= Alignment) {
2728 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2734 // Check whether we should use optimal code alignment for this .align
2736 const MCSection *Section = getStreamer().getCurrentSection().first;
2737 assert(Section && "must have section to emit alignment");
2738 bool UseCodeAlign = Section->UseCodeAlign();
2739 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2740 ValueSize == 1 && UseCodeAlign) {
2741 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2743 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2744 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2751 /// parseDirectiveFile
2752 /// ::= .file [number] filename
2753 /// ::= .file number directory filename
2754 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2755 // FIXME: I'm not sure what this is.
2756 int64_t FileNumber = -1;
2757 SMLoc FileNumberLoc = getLexer().getLoc();
2758 if (getLexer().is(AsmToken::Integer)) {
2759 FileNumber = getTok().getIntVal();
2763 return TokError("file number less than one");
2766 if (getLexer().isNot(AsmToken::String))
2767 return TokError("unexpected token in '.file' directive");
2769 // Usually the directory and filename together, otherwise just the directory.
2770 // Allow the strings to have escaped octal character sequence.
2771 std::string Path = getTok().getString();
2772 if (parseEscapedString(Path))
2776 StringRef Directory;
2778 std::string FilenameData;
2779 if (getLexer().is(AsmToken::String)) {
2780 if (FileNumber == -1)
2781 return TokError("explicit path specified, but no file number");
2782 if (parseEscapedString(FilenameData))
2784 Filename = FilenameData;
2791 if (getLexer().isNot(AsmToken::EndOfStatement))
2792 return TokError("unexpected token in '.file' directive");
2794 if (FileNumber == -1)
2795 getStreamer().EmitFileDirective(Filename);
2797 if (getContext().getGenDwarfForAssembly() == true)
2799 "input can't have .file dwarf directives when -g is "
2800 "used to generate dwarf debug info for assembly code");
2802 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2804 Error(FileNumberLoc, "file number already allocated");
2810 /// parseDirectiveLine
2811 /// ::= .line [number]
2812 bool AsmParser::parseDirectiveLine() {
2813 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2814 if (getLexer().isNot(AsmToken::Integer))
2815 return TokError("unexpected token in '.line' directive");
2817 int64_t LineNumber = getTok().getIntVal();
2821 // FIXME: Do something with the .line.
2824 if (getLexer().isNot(AsmToken::EndOfStatement))
2825 return TokError("unexpected token in '.line' directive");
2830 /// parseDirectiveLoc
2831 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2832 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2833 /// The first number is a file number, must have been previously assigned with
2834 /// a .file directive, the second number is the line number and optionally the
2835 /// third number is a column position (zero if not specified). The remaining
2836 /// optional items are .loc sub-directives.
2837 bool AsmParser::parseDirectiveLoc() {
2838 if (getLexer().isNot(AsmToken::Integer))
2839 return TokError("unexpected token in '.loc' directive");
2840 int64_t FileNumber = getTok().getIntVal();
2842 return TokError("file number less than one in '.loc' directive");
2843 if (!getContext().isValidDwarfFileNumber(FileNumber))
2844 return TokError("unassigned file number in '.loc' directive");
2847 int64_t LineNumber = 0;
2848 if (getLexer().is(AsmToken::Integer)) {
2849 LineNumber = getTok().getIntVal();
2851 return TokError("line number less than zero in '.loc' directive");
2855 int64_t ColumnPos = 0;
2856 if (getLexer().is(AsmToken::Integer)) {
2857 ColumnPos = getTok().getIntVal();
2859 return TokError("column position less than zero in '.loc' directive");
2863 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2865 int64_t Discriminator = 0;
2866 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2868 if (getLexer().is(AsmToken::EndOfStatement))
2872 SMLoc Loc = getTok().getLoc();
2873 if (parseIdentifier(Name))
2874 return TokError("unexpected token in '.loc' directive");
2876 if (Name == "basic_block")
2877 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2878 else if (Name == "prologue_end")
2879 Flags |= DWARF2_FLAG_PROLOGUE_END;
2880 else if (Name == "epilogue_begin")
2881 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2882 else if (Name == "is_stmt") {
2883 Loc = getTok().getLoc();
2884 const MCExpr *Value;
2885 if (parseExpression(Value))
2887 // The expression must be the constant 0 or 1.
2888 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2889 int Value = MCE->getValue();
2891 Flags &= ~DWARF2_FLAG_IS_STMT;
2892 else if (Value == 1)
2893 Flags |= DWARF2_FLAG_IS_STMT;
2895 return Error(Loc, "is_stmt value not 0 or 1");
2897 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2899 } else if (Name == "isa") {
2900 Loc = getTok().getLoc();
2901 const MCExpr *Value;
2902 if (parseExpression(Value))
2904 // The expression must be a constant greater or equal to 0.
2905 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2906 int Value = MCE->getValue();
2908 return Error(Loc, "isa number less than zero");
2911 return Error(Loc, "isa number not a constant value");
2913 } else if (Name == "discriminator") {
2914 if (parseAbsoluteExpression(Discriminator))
2917 return Error(Loc, "unknown sub-directive in '.loc' directive");
2920 if (getLexer().is(AsmToken::EndOfStatement))
2925 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2926 Isa, Discriminator, StringRef());
2931 /// parseDirectiveStabs
2932 /// ::= .stabs string, number, number, number
2933 bool AsmParser::parseDirectiveStabs() {
2934 return TokError("unsupported directive '.stabs'");
2937 /// parseDirectiveCFISections
2938 /// ::= .cfi_sections section [, section]
2939 bool AsmParser::parseDirectiveCFISections() {
2944 if (parseIdentifier(Name))
2945 return TokError("Expected an identifier");
2947 if (Name == ".eh_frame")
2949 else if (Name == ".debug_frame")
2952 if (getLexer().is(AsmToken::Comma)) {
2955 if (parseIdentifier(Name))
2956 return TokError("Expected an identifier");
2958 if (Name == ".eh_frame")
2960 else if (Name == ".debug_frame")
2964 getStreamer().EmitCFISections(EH, Debug);
2968 /// parseDirectiveCFIStartProc
2969 /// ::= .cfi_startproc [simple]
2970 bool AsmParser::parseDirectiveCFIStartProc() {
2972 if (getLexer().isNot(AsmToken::EndOfStatement))
2973 if (parseIdentifier(Simple) || Simple != "simple")
2974 return TokError("unexpected token in .cfi_startproc directive");
2976 getStreamer().EmitCFIStartProc(!Simple.empty());
2980 /// parseDirectiveCFIEndProc
2981 /// ::= .cfi_endproc
2982 bool AsmParser::parseDirectiveCFIEndProc() {
2983 getStreamer().EmitCFIEndProc();
2987 /// \brief parse register name or number.
2988 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2989 SMLoc DirectiveLoc) {
2992 if (getLexer().isNot(AsmToken::Integer)) {
2993 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2995 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2997 return parseAbsoluteExpression(Register);
3002 /// parseDirectiveCFIDefCfa
3003 /// ::= .cfi_def_cfa register, offset
3004 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3005 int64_t Register = 0;
3006 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3009 if (getLexer().isNot(AsmToken::Comma))
3010 return TokError("unexpected token in directive");
3014 if (parseAbsoluteExpression(Offset))
3017 getStreamer().EmitCFIDefCfa(Register, Offset);
3021 /// parseDirectiveCFIDefCfaOffset
3022 /// ::= .cfi_def_cfa_offset offset
3023 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3025 if (parseAbsoluteExpression(Offset))
3028 getStreamer().EmitCFIDefCfaOffset(Offset);
3032 /// parseDirectiveCFIRegister
3033 /// ::= .cfi_register register, register
3034 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3035 int64_t Register1 = 0;
3036 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3039 if (getLexer().isNot(AsmToken::Comma))
3040 return TokError("unexpected token in directive");
3043 int64_t Register2 = 0;
3044 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3047 getStreamer().EmitCFIRegister(Register1, Register2);
3051 /// parseDirectiveCFIWindowSave
3052 /// ::= .cfi_window_save
3053 bool AsmParser::parseDirectiveCFIWindowSave() {
3054 getStreamer().EmitCFIWindowSave();
3058 /// parseDirectiveCFIAdjustCfaOffset
3059 /// ::= .cfi_adjust_cfa_offset adjustment
3060 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3061 int64_t Adjustment = 0;
3062 if (parseAbsoluteExpression(Adjustment))
3065 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3069 /// parseDirectiveCFIDefCfaRegister
3070 /// ::= .cfi_def_cfa_register register
3071 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3072 int64_t Register = 0;
3073 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3076 getStreamer().EmitCFIDefCfaRegister(Register);
3080 /// parseDirectiveCFIOffset
3081 /// ::= .cfi_offset register, offset
3082 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3083 int64_t Register = 0;
3086 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3089 if (getLexer().isNot(AsmToken::Comma))
3090 return TokError("unexpected token in directive");
3093 if (parseAbsoluteExpression(Offset))
3096 getStreamer().EmitCFIOffset(Register, Offset);
3100 /// parseDirectiveCFIRelOffset
3101 /// ::= .cfi_rel_offset register, offset
3102 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3103 int64_t Register = 0;
3105 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3108 if (getLexer().isNot(AsmToken::Comma))
3109 return TokError("unexpected token in directive");
3113 if (parseAbsoluteExpression(Offset))
3116 getStreamer().EmitCFIRelOffset(Register, Offset);
3120 static bool isValidEncoding(int64_t Encoding) {
3121 if (Encoding & ~0xff)
3124 if (Encoding == dwarf::DW_EH_PE_omit)
3127 const unsigned Format = Encoding & 0xf;
3128 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3129 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3130 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3131 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3134 const unsigned Application = Encoding & 0x70;
3135 if (Application != dwarf::DW_EH_PE_absptr &&
3136 Application != dwarf::DW_EH_PE_pcrel)
3142 /// parseDirectiveCFIPersonalityOrLsda
3143 /// IsPersonality true for cfi_personality, false for cfi_lsda
3144 /// ::= .cfi_personality encoding, [symbol_name]
3145 /// ::= .cfi_lsda encoding, [symbol_name]
3146 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3147 int64_t Encoding = 0;
3148 if (parseAbsoluteExpression(Encoding))
3150 if (Encoding == dwarf::DW_EH_PE_omit)
3153 if (!isValidEncoding(Encoding))
3154 return TokError("unsupported encoding.");
3156 if (getLexer().isNot(AsmToken::Comma))
3157 return TokError("unexpected token in directive");
3161 if (parseIdentifier(Name))
3162 return TokError("expected identifier in directive");
3164 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3167 getStreamer().EmitCFIPersonality(Sym, Encoding);
3169 getStreamer().EmitCFILsda(Sym, Encoding);
3173 /// parseDirectiveCFIRememberState
3174 /// ::= .cfi_remember_state
3175 bool AsmParser::parseDirectiveCFIRememberState() {
3176 getStreamer().EmitCFIRememberState();
3180 /// parseDirectiveCFIRestoreState
3181 /// ::= .cfi_remember_state
3182 bool AsmParser::parseDirectiveCFIRestoreState() {
3183 getStreamer().EmitCFIRestoreState();
3187 /// parseDirectiveCFISameValue
3188 /// ::= .cfi_same_value register
3189 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3190 int64_t Register = 0;
3192 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3195 getStreamer().EmitCFISameValue(Register);
3199 /// parseDirectiveCFIRestore
3200 /// ::= .cfi_restore register
3201 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3202 int64_t Register = 0;
3203 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3206 getStreamer().EmitCFIRestore(Register);
3210 /// parseDirectiveCFIEscape
3211 /// ::= .cfi_escape expression[,...]
3212 bool AsmParser::parseDirectiveCFIEscape() {
3215 if (parseAbsoluteExpression(CurrValue))
3218 Values.push_back((uint8_t)CurrValue);
3220 while (getLexer().is(AsmToken::Comma)) {
3223 if (parseAbsoluteExpression(CurrValue))
3226 Values.push_back((uint8_t)CurrValue);
3229 getStreamer().EmitCFIEscape(Values);
3233 /// parseDirectiveCFISignalFrame
3234 /// ::= .cfi_signal_frame
3235 bool AsmParser::parseDirectiveCFISignalFrame() {
3236 if (getLexer().isNot(AsmToken::EndOfStatement))
3237 return Error(getLexer().getLoc(),
3238 "unexpected token in '.cfi_signal_frame'");
3240 getStreamer().EmitCFISignalFrame();
3244 /// parseDirectiveCFIUndefined
3245 /// ::= .cfi_undefined register
3246 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3247 int64_t Register = 0;
3249 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3252 getStreamer().EmitCFIUndefined(Register);
3256 /// parseDirectiveMacrosOnOff
3259 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3260 if (getLexer().isNot(AsmToken::EndOfStatement))
3261 return Error(getLexer().getLoc(),
3262 "unexpected token in '" + Directive + "' directive");
3264 setMacrosEnabled(Directive == ".macros_on");
3268 /// parseDirectiveMacro
3269 /// ::= .macro name[,] [parameters]
3270 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3272 if (parseIdentifier(Name))
3273 return TokError("expected identifier in '.macro' directive");
3275 if (getLexer().is(AsmToken::Comma))
3278 MCAsmMacroParameters Parameters;
3279 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3281 if (Parameters.size() && Parameters.back().Vararg)
3282 return Error(Lexer.getLoc(),
3283 "Vararg parameter '" + Parameters.back().Name +
3284 "' should be last one in the list of parameters.");
3286 MCAsmMacroParameter Parameter;
3287 if (parseIdentifier(Parameter.Name))
3288 return TokError("expected identifier in '.macro' directive");
3290 if (Lexer.is(AsmToken::Colon)) {
3291 Lex(); // consume ':'
3294 StringRef Qualifier;
3296 QualLoc = Lexer.getLoc();
3297 if (parseIdentifier(Qualifier))
3298 return Error(QualLoc, "missing parameter qualifier for "
3299 "'" + Parameter.Name + "' in macro '" + Name + "'");
3301 if (Qualifier == "req")
3302 Parameter.Required = true;
3303 else if (Qualifier == "vararg")
3304 Parameter.Vararg = true;
3306 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3307 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3310 if (getLexer().is(AsmToken::Equal)) {
3315 ParamLoc = Lexer.getLoc();
3316 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3319 if (Parameter.Required)
3320 Warning(ParamLoc, "pointless default value for required parameter "
3321 "'" + Parameter.Name + "' in macro '" + Name + "'");
3324 Parameters.push_back(Parameter);
3326 if (getLexer().is(AsmToken::Comma))
3330 // Eat the end of statement.
3333 AsmToken EndToken, StartToken = getTok();
3334 unsigned MacroDepth = 0;
3336 // Lex the macro definition.
3338 // Check whether we have reached the end of the file.
3339 if (getLexer().is(AsmToken::Eof))
3340 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3342 // Otherwise, check whether we have reach the .endmacro.
3343 if (getLexer().is(AsmToken::Identifier)) {
3344 if (getTok().getIdentifier() == ".endm" ||
3345 getTok().getIdentifier() == ".endmacro") {
3346 if (MacroDepth == 0) { // Outermost macro.
3347 EndToken = getTok();
3349 if (getLexer().isNot(AsmToken::EndOfStatement))
3350 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3354 // Otherwise we just found the end of an inner macro.
3357 } else if (getTok().getIdentifier() == ".macro") {
3358 // We allow nested macros. Those aren't instantiated until the outermost
3359 // macro is expanded so just ignore them for now.
3364 // Otherwise, scan til the end of the statement.
3365 eatToEndOfStatement();
3368 if (lookupMacro(Name)) {
3369 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3372 const char *BodyStart = StartToken.getLoc().getPointer();
3373 const char *BodyEnd = EndToken.getLoc().getPointer();
3374 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3375 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3376 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3380 /// checkForBadMacro
3382 /// With the support added for named parameters there may be code out there that
3383 /// is transitioning from positional parameters. In versions of gas that did
3384 /// not support named parameters they would be ignored on the macro definition.
3385 /// But to support both styles of parameters this is not possible so if a macro
3386 /// definition has named parameters but does not use them and has what appears
3387 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3388 /// warning that the positional parameter found in body which have no effect.
3389 /// Hoping the developer will either remove the named parameters from the macro
3390 /// definition so the positional parameters get used if that was what was
3391 /// intended or change the macro to use the named parameters. It is possible
3392 /// this warning will trigger when the none of the named parameters are used
3393 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3394 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3396 ArrayRef<MCAsmMacroParameter> Parameters) {
3397 // If this macro is not defined with named parameters the warning we are
3398 // checking for here doesn't apply.
3399 unsigned NParameters = Parameters.size();
3400 if (NParameters == 0)
3403 bool NamedParametersFound = false;
3404 bool PositionalParametersFound = false;
3406 // Look at the body of the macro for use of both the named parameters and what
3407 // are likely to be positional parameters. This is what expandMacro() is
3408 // doing when it finds the parameters in the body.
3409 while (!Body.empty()) {
3410 // Scan for the next possible parameter.
3411 std::size_t End = Body.size(), Pos = 0;
3412 for (; Pos != End; ++Pos) {
3413 // Check for a substitution or escape.
3414 // This macro is defined with parameters, look for \foo, \bar, etc.
3415 if (Body[Pos] == '\\' && Pos + 1 != End)
3418 // This macro should have parameters, but look for $0, $1, ..., $n too.
3419 if (Body[Pos] != '$' || Pos + 1 == End)
3421 char Next = Body[Pos + 1];
3422 if (Next == '$' || Next == 'n' ||
3423 isdigit(static_cast<unsigned char>(Next)))
3427 // Check if we reached the end.
3431 if (Body[Pos] == '$') {
3432 switch (Body[Pos + 1]) {
3437 // $n => number of arguments
3439 PositionalParametersFound = true;
3442 // $[0-9] => argument
3444 PositionalParametersFound = true;
3450 unsigned I = Pos + 1;
3451 while (isIdentifierChar(Body[I]) && I + 1 != End)
3454 const char *Begin = Body.data() + Pos + 1;
3455 StringRef Argument(Begin, I - (Pos + 1));
3457 for (; Index < NParameters; ++Index)
3458 if (Parameters[Index].Name == Argument)
3461 if (Index == NParameters) {
3462 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3468 NamedParametersFound = true;
3469 Pos += 1 + Argument.size();
3472 // Update the scan point.
3473 Body = Body.substr(Pos);
3476 if (!NamedParametersFound && PositionalParametersFound)
3477 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3478 "used in macro body, possible positional parameter "
3479 "found in body which will have no effect");
3482 /// parseDirectiveExitMacro
3484 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3485 if (getLexer().isNot(AsmToken::EndOfStatement))
3486 return TokError("unexpected token in '" + Directive + "' directive");
3488 if (!isInsideMacroInstantiation())
3489 return TokError("unexpected '" + Directive + "' in file, "
3490 "no current macro definition");
3492 // Exit all conditionals that are active in the current macro.
3493 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3494 TheCondState = TheCondStack.back();
3495 TheCondStack.pop_back();
3502 /// parseDirectiveEndMacro
3505 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3506 if (getLexer().isNot(AsmToken::EndOfStatement))
3507 return TokError("unexpected token in '" + Directive + "' directive");
3509 // If we are inside a macro instantiation, terminate the current
3511 if (isInsideMacroInstantiation()) {
3516 // Otherwise, this .endmacro is a stray entry in the file; well formed
3517 // .endmacro directives are handled during the macro definition parsing.
3518 return TokError("unexpected '" + Directive + "' in file, "
3519 "no current macro definition");
3522 /// parseDirectivePurgeMacro
3524 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3526 if (parseIdentifier(Name))
3527 return TokError("expected identifier in '.purgem' directive");
3529 if (getLexer().isNot(AsmToken::EndOfStatement))
3530 return TokError("unexpected token in '.purgem' directive");
3532 if (!lookupMacro(Name))
3533 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3535 undefineMacro(Name);
3539 /// parseDirectiveBundleAlignMode
3540 /// ::= {.bundle_align_mode} expression
3541 bool AsmParser::parseDirectiveBundleAlignMode() {
3542 checkForValidSection();
3544 // Expect a single argument: an expression that evaluates to a constant
3545 // in the inclusive range 0-30.
3546 SMLoc ExprLoc = getLexer().getLoc();
3547 int64_t AlignSizePow2;
3548 if (parseAbsoluteExpression(AlignSizePow2))
3550 else if (getLexer().isNot(AsmToken::EndOfStatement))
3551 return TokError("unexpected token after expression in"
3552 " '.bundle_align_mode' directive");
3553 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3554 return Error(ExprLoc,
3555 "invalid bundle alignment size (expected between 0 and 30)");
3559 // Because of AlignSizePow2's verified range we can safely truncate it to
3561 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3565 /// parseDirectiveBundleLock
3566 /// ::= {.bundle_lock} [align_to_end]
3567 bool AsmParser::parseDirectiveBundleLock() {
3568 checkForValidSection();
3569 bool AlignToEnd = false;
3571 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3573 SMLoc Loc = getTok().getLoc();
3574 const char *kInvalidOptionError =
3575 "invalid option for '.bundle_lock' directive";
3577 if (parseIdentifier(Option))
3578 return Error(Loc, kInvalidOptionError);
3580 if (Option != "align_to_end")
3581 return Error(Loc, kInvalidOptionError);
3582 else if (getLexer().isNot(AsmToken::EndOfStatement))
3584 "unexpected token after '.bundle_lock' directive option");
3590 getStreamer().EmitBundleLock(AlignToEnd);
3594 /// parseDirectiveBundleLock
3595 /// ::= {.bundle_lock}
3596 bool AsmParser::parseDirectiveBundleUnlock() {
3597 checkForValidSection();
3599 if (getLexer().isNot(AsmToken::EndOfStatement))
3600 return TokError("unexpected token in '.bundle_unlock' directive");
3603 getStreamer().EmitBundleUnlock();
3607 /// parseDirectiveSpace
3608 /// ::= (.skip | .space) expression [ , expression ]
3609 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3610 checkForValidSection();
3613 if (parseAbsoluteExpression(NumBytes))
3616 int64_t FillExpr = 0;
3617 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3618 if (getLexer().isNot(AsmToken::Comma))
3619 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3622 if (parseAbsoluteExpression(FillExpr))
3625 if (getLexer().isNot(AsmToken::EndOfStatement))
3626 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3632 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3635 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3636 getStreamer().EmitFill(NumBytes, FillExpr);
3641 /// parseDirectiveLEB128
3642 /// ::= (.sleb128 | .uleb128) expression
3643 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3644 checkForValidSection();
3645 const MCExpr *Value;
3647 if (parseExpression(Value))
3650 if (getLexer().isNot(AsmToken::EndOfStatement))
3651 return TokError("unexpected token in directive");
3654 getStreamer().EmitSLEB128Value(Value);
3656 getStreamer().EmitULEB128Value(Value);
3661 /// parseDirectiveSymbolAttribute
3662 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3663 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3664 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3667 SMLoc Loc = getTok().getLoc();
3669 if (parseIdentifier(Name))
3670 return Error(Loc, "expected identifier in directive");
3672 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3674 // Assembler local symbols don't make any sense here. Complain loudly.
3675 if (Sym->isTemporary())
3676 return Error(Loc, "non-local symbol required in directive");
3678 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3679 return Error(Loc, "unable to emit symbol attribute");
3681 if (getLexer().is(AsmToken::EndOfStatement))
3684 if (getLexer().isNot(AsmToken::Comma))
3685 return TokError("unexpected token in directive");
3694 /// parseDirectiveComm
3695 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3696 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3697 checkForValidSection();
3699 SMLoc IDLoc = getLexer().getLoc();
3701 if (parseIdentifier(Name))
3702 return TokError("expected identifier in directive");
3704 // Handle the identifier as the key symbol.
3705 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3707 if (getLexer().isNot(AsmToken::Comma))
3708 return TokError("unexpected token in directive");
3712 SMLoc SizeLoc = getLexer().getLoc();
3713 if (parseAbsoluteExpression(Size))
3716 int64_t Pow2Alignment = 0;
3717 SMLoc Pow2AlignmentLoc;
3718 if (getLexer().is(AsmToken::Comma)) {
3720 Pow2AlignmentLoc = getLexer().getLoc();
3721 if (parseAbsoluteExpression(Pow2Alignment))
3724 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3725 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3726 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3728 // If this target takes alignments in bytes (not log) validate and convert.
3729 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3730 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3731 if (!isPowerOf2_64(Pow2Alignment))
3732 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3733 Pow2Alignment = Log2_64(Pow2Alignment);
3737 if (getLexer().isNot(AsmToken::EndOfStatement))
3738 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3742 // NOTE: a size of zero for a .comm should create a undefined symbol
3743 // but a size of .lcomm creates a bss symbol of size zero.
3745 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3746 "be less than zero");
3748 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3749 // may internally end up wanting an alignment in bytes.
3750 // FIXME: Diagnose overflow.
3751 if (Pow2Alignment < 0)
3752 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3753 "alignment, can't be less than zero");
3755 if (!Sym->isUndefined())
3756 return Error(IDLoc, "invalid symbol redefinition");
3758 // Create the Symbol as a common or local common with Size and Pow2Alignment
3760 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3764 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3768 /// parseDirectiveAbort
3769 /// ::= .abort [... message ...]
3770 bool AsmParser::parseDirectiveAbort() {
3771 // FIXME: Use loc from directive.
3772 SMLoc Loc = getLexer().getLoc();
3774 StringRef Str = parseStringToEndOfStatement();
3775 if (getLexer().isNot(AsmToken::EndOfStatement))
3776 return TokError("unexpected token in '.abort' directive");
3781 Error(Loc, ".abort detected. Assembly stopping.");
3783 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3784 // FIXME: Actually abort assembly here.
3789 /// parseDirectiveInclude
3790 /// ::= .include "filename"
3791 bool AsmParser::parseDirectiveInclude() {
3792 if (getLexer().isNot(AsmToken::String))
3793 return TokError("expected string in '.include' directive");
3795 // Allow the strings to have escaped octal character sequence.
3796 std::string Filename;
3797 if (parseEscapedString(Filename))
3799 SMLoc IncludeLoc = getLexer().getLoc();
3802 if (getLexer().isNot(AsmToken::EndOfStatement))
3803 return TokError("unexpected token in '.include' directive");
3805 // Attempt to switch the lexer to the included file before consuming the end
3806 // of statement to avoid losing it when we switch.
3807 if (enterIncludeFile(Filename)) {
3808 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3815 /// parseDirectiveIncbin
3816 /// ::= .incbin "filename"
3817 bool AsmParser::parseDirectiveIncbin() {
3818 if (getLexer().isNot(AsmToken::String))
3819 return TokError("expected string in '.incbin' directive");
3821 // Allow the strings to have escaped octal character sequence.
3822 std::string Filename;
3823 if (parseEscapedString(Filename))
3825 SMLoc IncbinLoc = getLexer().getLoc();
3828 if (getLexer().isNot(AsmToken::EndOfStatement))
3829 return TokError("unexpected token in '.incbin' directive");
3831 // Attempt to process the included file.
3832 if (processIncbinFile(Filename)) {
3833 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3840 /// parseDirectiveIf
3841 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3842 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3843 TheCondStack.push_back(TheCondState);
3844 TheCondState.TheCond = AsmCond::IfCond;
3845 if (TheCondState.Ignore) {
3846 eatToEndOfStatement();
3849 if (parseAbsoluteExpression(ExprValue))
3852 if (getLexer().isNot(AsmToken::EndOfStatement))
3853 return TokError("unexpected token in '.if' directive");
3859 llvm_unreachable("unsupported directive");
3864 ExprValue = ExprValue == 0;
3867 ExprValue = ExprValue >= 0;
3870 ExprValue = ExprValue > 0;
3873 ExprValue = ExprValue <= 0;
3876 ExprValue = ExprValue < 0;
3880 TheCondState.CondMet = ExprValue;
3881 TheCondState.Ignore = !TheCondState.CondMet;
3887 /// parseDirectiveIfb
3889 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3890 TheCondStack.push_back(TheCondState);
3891 TheCondState.TheCond = AsmCond::IfCond;
3893 if (TheCondState.Ignore) {
3894 eatToEndOfStatement();
3896 StringRef Str = parseStringToEndOfStatement();
3898 if (getLexer().isNot(AsmToken::EndOfStatement))
3899 return TokError("unexpected token in '.ifb' directive");
3903 TheCondState.CondMet = ExpectBlank == Str.empty();
3904 TheCondState.Ignore = !TheCondState.CondMet;
3910 /// parseDirectiveIfc
3911 /// ::= .ifc string1, string2
3912 /// ::= .ifnc string1, string2
3913 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3914 TheCondStack.push_back(TheCondState);
3915 TheCondState.TheCond = AsmCond::IfCond;
3917 if (TheCondState.Ignore) {
3918 eatToEndOfStatement();
3920 StringRef Str1 = parseStringToComma();
3922 if (getLexer().isNot(AsmToken::Comma))
3923 return TokError("unexpected token in '.ifc' directive");
3927 StringRef Str2 = parseStringToEndOfStatement();
3929 if (getLexer().isNot(AsmToken::EndOfStatement))
3930 return TokError("unexpected token in '.ifc' directive");
3934 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3935 TheCondState.Ignore = !TheCondState.CondMet;
3941 /// parseDirectiveIfeqs
3942 /// ::= .ifeqs string1, string2
3943 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3944 if (Lexer.isNot(AsmToken::String)) {
3945 TokError("expected string parameter for '.ifeqs' directive");
3946 eatToEndOfStatement();
3950 StringRef String1 = getTok().getStringContents();
3953 if (Lexer.isNot(AsmToken::Comma)) {
3954 TokError("expected comma after first string for '.ifeqs' directive");
3955 eatToEndOfStatement();
3961 if (Lexer.isNot(AsmToken::String)) {
3962 TokError("expected string parameter for '.ifeqs' directive");
3963 eatToEndOfStatement();
3967 StringRef String2 = getTok().getStringContents();
3970 TheCondStack.push_back(TheCondState);
3971 TheCondState.TheCond = AsmCond::IfCond;
3972 TheCondState.CondMet = String1 == String2;
3973 TheCondState.Ignore = !TheCondState.CondMet;
3978 /// parseDirectiveIfdef
3979 /// ::= .ifdef symbol
3980 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3982 TheCondStack.push_back(TheCondState);
3983 TheCondState.TheCond = AsmCond::IfCond;
3985 if (TheCondState.Ignore) {
3986 eatToEndOfStatement();
3988 if (parseIdentifier(Name))
3989 return TokError("expected identifier after '.ifdef'");
3993 MCSymbol *Sym = getContext().LookupSymbol(Name);
3996 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3998 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3999 TheCondState.Ignore = !TheCondState.CondMet;
4005 /// parseDirectiveElseIf
4006 /// ::= .elseif expression
4007 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4008 if (TheCondState.TheCond != AsmCond::IfCond &&
4009 TheCondState.TheCond != AsmCond::ElseIfCond)
4010 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4012 TheCondState.TheCond = AsmCond::ElseIfCond;
4014 bool LastIgnoreState = false;
4015 if (!TheCondStack.empty())
4016 LastIgnoreState = TheCondStack.back().Ignore;
4017 if (LastIgnoreState || TheCondState.CondMet) {
4018 TheCondState.Ignore = true;
4019 eatToEndOfStatement();
4022 if (parseAbsoluteExpression(ExprValue))
4025 if (getLexer().isNot(AsmToken::EndOfStatement))
4026 return TokError("unexpected token in '.elseif' directive");
4029 TheCondState.CondMet = ExprValue;
4030 TheCondState.Ignore = !TheCondState.CondMet;
4036 /// parseDirectiveElse
4038 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4039 if (getLexer().isNot(AsmToken::EndOfStatement))
4040 return TokError("unexpected token in '.else' directive");
4044 if (TheCondState.TheCond != AsmCond::IfCond &&
4045 TheCondState.TheCond != AsmCond::ElseIfCond)
4046 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4048 TheCondState.TheCond = AsmCond::ElseCond;
4049 bool LastIgnoreState = false;
4050 if (!TheCondStack.empty())
4051 LastIgnoreState = TheCondStack.back().Ignore;
4052 if (LastIgnoreState || TheCondState.CondMet)
4053 TheCondState.Ignore = true;
4055 TheCondState.Ignore = false;
4060 /// parseDirectiveEnd
4062 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4063 if (getLexer().isNot(AsmToken::EndOfStatement))
4064 return TokError("unexpected token in '.end' directive");
4068 while (Lexer.isNot(AsmToken::Eof))
4074 /// parseDirectiveError
4076 /// ::= .error [string]
4077 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4078 if (!TheCondStack.empty()) {
4079 if (TheCondStack.back().Ignore) {
4080 eatToEndOfStatement();
4086 return Error(L, ".err encountered");
4088 StringRef Message = ".error directive invoked in source file";
4089 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4090 if (Lexer.isNot(AsmToken::String)) {
4091 TokError(".error argument must be a string");
4092 eatToEndOfStatement();
4096 Message = getTok().getStringContents();
4104 /// parseDirectiveWarning
4105 /// ::= .warning [string]
4106 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4107 if (!TheCondStack.empty()) {
4108 if (TheCondStack.back().Ignore) {
4109 eatToEndOfStatement();
4114 StringRef Message = ".warning directive invoked in source file";
4115 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4116 if (Lexer.isNot(AsmToken::String)) {
4117 TokError(".warning argument must be a string");
4118 eatToEndOfStatement();
4122 Message = getTok().getStringContents();
4126 Warning(L, Message);
4130 /// parseDirectiveEndIf
4132 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4133 if (getLexer().isNot(AsmToken::EndOfStatement))
4134 return TokError("unexpected token in '.endif' directive");
4138 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4139 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4141 if (!TheCondStack.empty()) {
4142 TheCondState = TheCondStack.back();
4143 TheCondStack.pop_back();
4149 void AsmParser::initializeDirectiveKindMap() {
4150 DirectiveKindMap[".set"] = DK_SET;
4151 DirectiveKindMap[".equ"] = DK_EQU;
4152 DirectiveKindMap[".equiv"] = DK_EQUIV;
4153 DirectiveKindMap[".ascii"] = DK_ASCII;
4154 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4155 DirectiveKindMap[".string"] = DK_STRING;
4156 DirectiveKindMap[".byte"] = DK_BYTE;
4157 DirectiveKindMap[".short"] = DK_SHORT;
4158 DirectiveKindMap[".value"] = DK_VALUE;
4159 DirectiveKindMap[".2byte"] = DK_2BYTE;
4160 DirectiveKindMap[".long"] = DK_LONG;
4161 DirectiveKindMap[".int"] = DK_INT;
4162 DirectiveKindMap[".4byte"] = DK_4BYTE;
4163 DirectiveKindMap[".quad"] = DK_QUAD;
4164 DirectiveKindMap[".8byte"] = DK_8BYTE;
4165 DirectiveKindMap[".octa"] = DK_OCTA;
4166 DirectiveKindMap[".single"] = DK_SINGLE;
4167 DirectiveKindMap[".float"] = DK_FLOAT;
4168 DirectiveKindMap[".double"] = DK_DOUBLE;
4169 DirectiveKindMap[".align"] = DK_ALIGN;
4170 DirectiveKindMap[".align32"] = DK_ALIGN32;
4171 DirectiveKindMap[".balign"] = DK_BALIGN;
4172 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4173 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4174 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4175 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4176 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4177 DirectiveKindMap[".org"] = DK_ORG;
4178 DirectiveKindMap[".fill"] = DK_FILL;
4179 DirectiveKindMap[".zero"] = DK_ZERO;
4180 DirectiveKindMap[".extern"] = DK_EXTERN;
4181 DirectiveKindMap[".globl"] = DK_GLOBL;
4182 DirectiveKindMap[".global"] = DK_GLOBAL;
4183 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4184 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4185 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4186 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4187 DirectiveKindMap[".reference"] = DK_REFERENCE;
4188 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4189 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4190 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4191 DirectiveKindMap[".comm"] = DK_COMM;
4192 DirectiveKindMap[".common"] = DK_COMMON;
4193 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4194 DirectiveKindMap[".abort"] = DK_ABORT;
4195 DirectiveKindMap[".include"] = DK_INCLUDE;
4196 DirectiveKindMap[".incbin"] = DK_INCBIN;
4197 DirectiveKindMap[".code16"] = DK_CODE16;
4198 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4199 DirectiveKindMap[".rept"] = DK_REPT;
4200 DirectiveKindMap[".rep"] = DK_REPT;
4201 DirectiveKindMap[".irp"] = DK_IRP;
4202 DirectiveKindMap[".irpc"] = DK_IRPC;
4203 DirectiveKindMap[".endr"] = DK_ENDR;
4204 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4205 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4206 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4207 DirectiveKindMap[".if"] = DK_IF;
4208 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4209 DirectiveKindMap[".ifge"] = DK_IFGE;
4210 DirectiveKindMap[".ifgt"] = DK_IFGT;
4211 DirectiveKindMap[".ifle"] = DK_IFLE;
4212 DirectiveKindMap[".iflt"] = DK_IFLT;
4213 DirectiveKindMap[".ifne"] = DK_IFNE;
4214 DirectiveKindMap[".ifb"] = DK_IFB;
4215 DirectiveKindMap[".ifnb"] = DK_IFNB;
4216 DirectiveKindMap[".ifc"] = DK_IFC;
4217 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4218 DirectiveKindMap[".ifnc"] = DK_IFNC;
4219 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4220 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4221 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4222 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4223 DirectiveKindMap[".else"] = DK_ELSE;
4224 DirectiveKindMap[".end"] = DK_END;
4225 DirectiveKindMap[".endif"] = DK_ENDIF;
4226 DirectiveKindMap[".skip"] = DK_SKIP;
4227 DirectiveKindMap[".space"] = DK_SPACE;
4228 DirectiveKindMap[".file"] = DK_FILE;
4229 DirectiveKindMap[".line"] = DK_LINE;
4230 DirectiveKindMap[".loc"] = DK_LOC;
4231 DirectiveKindMap[".stabs"] = DK_STABS;
4232 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4233 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4234 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4235 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4236 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4237 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4238 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4239 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4240 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4241 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4242 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4243 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4244 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4245 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4246 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4247 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4248 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4249 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4250 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4251 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4252 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4253 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4254 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4255 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4256 DirectiveKindMap[".macro"] = DK_MACRO;
4257 DirectiveKindMap[".exitm"] = DK_EXITM;
4258 DirectiveKindMap[".endm"] = DK_ENDM;
4259 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4260 DirectiveKindMap[".purgem"] = DK_PURGEM;
4261 DirectiveKindMap[".err"] = DK_ERR;
4262 DirectiveKindMap[".error"] = DK_ERROR;
4263 DirectiveKindMap[".warning"] = DK_WARNING;
4266 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4267 AsmToken EndToken, StartToken = getTok();
4269 unsigned NestLevel = 0;
4271 // Check whether we have reached the end of the file.
4272 if (getLexer().is(AsmToken::Eof)) {
4273 Error(DirectiveLoc, "no matching '.endr' in definition");
4277 if (Lexer.is(AsmToken::Identifier) &&
4278 (getTok().getIdentifier() == ".rept")) {
4282 // Otherwise, check whether we have reached the .endr.
4283 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4284 if (NestLevel == 0) {
4285 EndToken = getTok();
4287 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4288 TokError("unexpected token in '.endr' directive");
4296 // Otherwise, scan till the end of the statement.
4297 eatToEndOfStatement();
4300 const char *BodyStart = StartToken.getLoc().getPointer();
4301 const char *BodyEnd = EndToken.getLoc().getPointer();
4302 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4304 // We Are Anonymous.
4305 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4306 return &MacroLikeBodies.back();
4309 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4310 raw_svector_ostream &OS) {
4313 MemoryBuffer *Instantiation =
4314 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4316 // Create the macro instantiation object and add to the current macro
4317 // instantiation stack.
4318 MacroInstantiation *MI =
4319 new MacroInstantiation(DirectiveLoc, CurBuffer, getTok().getLoc(),
4320 Instantiation->getBuffer(), TheCondStack.size());
4321 ActiveMacros.push_back(MI);
4323 // Jump to the macro instantiation and prime the lexer.
4324 CurBuffer = SrcMgr.AddNewSourceBuffer(Instantiation, SMLoc());
4325 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4329 /// parseDirectiveRept
4330 /// ::= .rep | .rept count
4331 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4332 const MCExpr *CountExpr;
4333 SMLoc CountLoc = getTok().getLoc();
4334 if (parseExpression(CountExpr))
4338 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4339 eatToEndOfStatement();
4340 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4344 return Error(CountLoc, "Count is negative");
4346 if (Lexer.isNot(AsmToken::EndOfStatement))
4347 return TokError("unexpected token in '" + Dir + "' directive");
4349 // Eat the end of statement.
4352 // Lex the rept definition.
4353 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4357 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4358 // to hold the macro body with substitutions.
4359 SmallString<256> Buf;
4360 raw_svector_ostream OS(Buf);
4362 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4365 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4370 /// parseDirectiveIrp
4371 /// ::= .irp symbol,values
4372 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4373 MCAsmMacroParameter Parameter;
4375 if (parseIdentifier(Parameter.Name))
4376 return TokError("expected identifier in '.irp' directive");
4378 if (Lexer.isNot(AsmToken::Comma))
4379 return TokError("expected comma in '.irp' directive");
4383 MCAsmMacroArguments A;
4384 if (parseMacroArguments(nullptr, A))
4387 // Eat the end of statement.
4390 // Lex the irp definition.
4391 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4395 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4396 // to hold the macro body with substitutions.
4397 SmallString<256> Buf;
4398 raw_svector_ostream OS(Buf);
4400 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4401 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4405 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4410 /// parseDirectiveIrpc
4411 /// ::= .irpc symbol,values
4412 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4413 MCAsmMacroParameter Parameter;
4415 if (parseIdentifier(Parameter.Name))
4416 return TokError("expected identifier in '.irpc' directive");
4418 if (Lexer.isNot(AsmToken::Comma))
4419 return TokError("expected comma in '.irpc' directive");
4423 MCAsmMacroArguments A;
4424 if (parseMacroArguments(nullptr, A))
4427 if (A.size() != 1 || A.front().size() != 1)
4428 return TokError("unexpected token in '.irpc' directive");
4430 // Eat the end of statement.
4433 // Lex the irpc definition.
4434 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4438 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4439 // to hold the macro body with substitutions.
4440 SmallString<256> Buf;
4441 raw_svector_ostream OS(Buf);
4443 StringRef Values = A.front().front().getString();
4444 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4445 MCAsmMacroArgument Arg;
4446 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4448 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4452 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4457 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4458 if (ActiveMacros.empty())
4459 return TokError("unmatched '.endr' directive");
4461 // The only .repl that should get here are the ones created by
4462 // instantiateMacroLikeBody.
4463 assert(getLexer().is(AsmToken::EndOfStatement));
4469 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4471 const MCExpr *Value;
4472 SMLoc ExprLoc = getLexer().getLoc();
4473 if (parseExpression(Value))
4475 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4477 return Error(ExprLoc, "unexpected expression in _emit");
4478 uint64_t IntValue = MCE->getValue();
4479 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4480 return Error(ExprLoc, "literal value out of range for directive");
4482 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4486 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4487 const MCExpr *Value;
4488 SMLoc ExprLoc = getLexer().getLoc();
4489 if (parseExpression(Value))
4491 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4493 return Error(ExprLoc, "unexpected expression in align");
4494 uint64_t IntValue = MCE->getValue();
4495 if (!isPowerOf2_64(IntValue))
4496 return Error(ExprLoc, "literal value not a power of two greater then zero");
4498 Info.AsmRewrites->push_back(
4499 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4503 // We are comparing pointers, but the pointers are relative to a single string.
4504 // Thus, this should always be deterministic.
4505 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4506 const AsmRewrite *AsmRewriteB) {
4507 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4509 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4512 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4513 // rewrite to the same location. Make sure the SizeDirective rewrite is
4514 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4515 // ensures the sort algorithm is stable.
4516 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4517 AsmRewritePrecedence[AsmRewriteB->Kind])
4520 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4521 AsmRewritePrecedence[AsmRewriteB->Kind])
4523 llvm_unreachable("Unstable rewrite sort.");
4526 bool AsmParser::parseMSInlineAsm(
4527 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4528 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4529 SmallVectorImpl<std::string> &Constraints,
4530 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4531 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4532 SmallVector<void *, 4> InputDecls;
4533 SmallVector<void *, 4> OutputDecls;
4534 SmallVector<bool, 4> InputDeclsAddressOf;
4535 SmallVector<bool, 4> OutputDeclsAddressOf;
4536 SmallVector<std::string, 4> InputConstraints;
4537 SmallVector<std::string, 4> OutputConstraints;
4538 SmallVector<unsigned, 4> ClobberRegs;
4540 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4545 // While we have input, parse each statement.
4546 unsigned InputIdx = 0;
4547 unsigned OutputIdx = 0;
4548 while (getLexer().isNot(AsmToken::Eof)) {
4549 ParseStatementInfo Info(&AsmStrRewrites);
4550 if (parseStatement(Info))
4553 if (Info.ParseError)
4556 if (Info.Opcode == ~0U)
4559 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4561 // Build the list of clobbers, outputs and inputs.
4562 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4563 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4566 if (Operand.isImm())
4569 // Register operand.
4570 if (Operand.isReg() && !Operand.needAddressOf() &&
4571 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4572 unsigned NumDefs = Desc.getNumDefs();
4574 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4575 ClobberRegs.push_back(Operand.getReg());
4579 // Expr/Input or Output.
4580 StringRef SymName = Operand.getSymName();
4581 if (SymName.empty())
4584 void *OpDecl = Operand.getOpDecl();
4588 bool isOutput = (i == 1) && Desc.mayStore();
4589 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4592 OutputDecls.push_back(OpDecl);
4593 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4594 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4595 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4597 InputDecls.push_back(OpDecl);
4598 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4599 InputConstraints.push_back(Operand.getConstraint().str());
4600 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4604 // Consider implicit defs to be clobbers. Think of cpuid and push.
4605 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4606 Desc.getNumImplicitDefs());
4607 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4610 // Set the number of Outputs and Inputs.
4611 NumOutputs = OutputDecls.size();
4612 NumInputs = InputDecls.size();
4614 // Set the unique clobbers.
4615 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4616 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4618 Clobbers.assign(ClobberRegs.size(), std::string());
4619 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4620 raw_string_ostream OS(Clobbers[I]);
4621 IP->printRegName(OS, ClobberRegs[I]);
4624 // Merge the various outputs and inputs. Output are expected first.
4625 if (NumOutputs || NumInputs) {
4626 unsigned NumExprs = NumOutputs + NumInputs;
4627 OpDecls.resize(NumExprs);
4628 Constraints.resize(NumExprs);
4629 for (unsigned i = 0; i < NumOutputs; ++i) {
4630 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4631 Constraints[i] = OutputConstraints[i];
4633 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4634 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4635 Constraints[j] = InputConstraints[i];
4639 // Build the IR assembly string.
4640 std::string AsmStringIR;
4641 raw_string_ostream OS(AsmStringIR);
4642 StringRef ASMString =
4643 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4644 const char *AsmStart = ASMString.begin();
4645 const char *AsmEnd = ASMString.end();
4646 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4647 for (const AsmRewrite &AR : AsmStrRewrites) {
4648 AsmRewriteKind Kind = AR.Kind;
4649 if (Kind == AOK_Delete)
4652 const char *Loc = AR.Loc.getPointer();
4653 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4655 // Emit everything up to the immediate/expression.
4656 if (unsigned Len = Loc - AsmStart)
4657 OS << StringRef(AsmStart, Len);
4659 // Skip the original expression.
4660 if (Kind == AOK_Skip) {
4661 AsmStart = Loc + AR.Len;
4665 unsigned AdditionalSkip = 0;
4666 // Rewrite expressions in $N notation.
4671 OS << "$$" << AR.Val;
4677 OS << '$' << InputIdx++;
4680 OS << '$' << OutputIdx++;
4682 case AOK_SizeDirective:
4685 case 8: OS << "byte ptr "; break;
4686 case 16: OS << "word ptr "; break;
4687 case 32: OS << "dword ptr "; break;
4688 case 64: OS << "qword ptr "; break;
4689 case 80: OS << "xword ptr "; break;
4690 case 128: OS << "xmmword ptr "; break;
4691 case 256: OS << "ymmword ptr "; break;
4698 unsigned Val = AR.Val;
4699 OS << ".align " << Val;
4701 // Skip the original immediate.
4702 assert(Val < 10 && "Expected alignment less then 2^10.");
4703 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4706 case AOK_DotOperator:
4707 // Insert the dot if the user omitted it.
4709 if (AsmStringIR.back() != '.')
4715 // Skip the original expression.
4716 AsmStart = Loc + AR.Len + AdditionalSkip;
4719 // Emit the remainder of the asm string.
4720 if (AsmStart != AsmEnd)
4721 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4723 AsmString = OS.str();
4727 /// \brief Create an MCAsmParser instance.
4728 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4729 MCStreamer &Out, const MCAsmInfo &MAI) {
4730 return new AsmParser(SM, C, Out, MAI);