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 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2621 /// parseDirectiveOrg
2622 /// ::= .org expression [ , expression ]
2623 bool AsmParser::parseDirectiveOrg() {
2624 checkForValidSection();
2626 const MCExpr *Offset;
2627 SMLoc Loc = getTok().getLoc();
2628 if (parseExpression(Offset))
2631 // Parse optional fill expression.
2632 int64_t FillExpr = 0;
2633 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2634 if (getLexer().isNot(AsmToken::Comma))
2635 return TokError("unexpected token in '.org' directive");
2638 if (parseAbsoluteExpression(FillExpr))
2641 if (getLexer().isNot(AsmToken::EndOfStatement))
2642 return TokError("unexpected token in '.org' directive");
2647 // Only limited forms of relocatable expressions are accepted here, it
2648 // has to be relative to the current section. The streamer will return
2649 // 'true' if the expression wasn't evaluatable.
2650 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2651 return Error(Loc, "expected assembly-time absolute expression");
2656 /// parseDirectiveAlign
2657 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2658 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2659 checkForValidSection();
2661 SMLoc AlignmentLoc = getLexer().getLoc();
2663 if (parseAbsoluteExpression(Alignment))
2667 bool HasFillExpr = false;
2668 int64_t FillExpr = 0;
2669 int64_t MaxBytesToFill = 0;
2670 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2671 if (getLexer().isNot(AsmToken::Comma))
2672 return TokError("unexpected token in directive");
2675 // The fill expression can be omitted while specifying a maximum number of
2676 // alignment bytes, e.g:
2678 if (getLexer().isNot(AsmToken::Comma)) {
2680 if (parseAbsoluteExpression(FillExpr))
2684 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2685 if (getLexer().isNot(AsmToken::Comma))
2686 return TokError("unexpected token in directive");
2689 MaxBytesLoc = getLexer().getLoc();
2690 if (parseAbsoluteExpression(MaxBytesToFill))
2693 if (getLexer().isNot(AsmToken::EndOfStatement))
2694 return TokError("unexpected token in directive");
2703 // Compute alignment in bytes.
2705 // FIXME: Diagnose overflow.
2706 if (Alignment >= 32) {
2707 Error(AlignmentLoc, "invalid alignment value");
2711 Alignment = 1ULL << Alignment;
2713 // Reject alignments that aren't a power of two, for gas compatibility.
2714 if (!isPowerOf2_64(Alignment))
2715 Error(AlignmentLoc, "alignment must be a power of 2");
2718 // Diagnose non-sensical max bytes to align.
2719 if (MaxBytesLoc.isValid()) {
2720 if (MaxBytesToFill < 1) {
2721 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2722 "many bytes, ignoring maximum bytes expression");
2726 if (MaxBytesToFill >= Alignment) {
2727 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2733 // Check whether we should use optimal code alignment for this .align
2735 const MCSection *Section = getStreamer().getCurrentSection().first;
2736 assert(Section && "must have section to emit alignment");
2737 bool UseCodeAlign = Section->UseCodeAlign();
2738 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2739 ValueSize == 1 && UseCodeAlign) {
2740 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2742 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2743 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2750 /// parseDirectiveFile
2751 /// ::= .file [number] filename
2752 /// ::= .file number directory filename
2753 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2754 // FIXME: I'm not sure what this is.
2755 int64_t FileNumber = -1;
2756 SMLoc FileNumberLoc = getLexer().getLoc();
2757 if (getLexer().is(AsmToken::Integer)) {
2758 FileNumber = getTok().getIntVal();
2762 return TokError("file number less than one");
2765 if (getLexer().isNot(AsmToken::String))
2766 return TokError("unexpected token in '.file' directive");
2768 // Usually the directory and filename together, otherwise just the directory.
2769 // Allow the strings to have escaped octal character sequence.
2770 std::string Path = getTok().getString();
2771 if (parseEscapedString(Path))
2775 StringRef Directory;
2777 std::string FilenameData;
2778 if (getLexer().is(AsmToken::String)) {
2779 if (FileNumber == -1)
2780 return TokError("explicit path specified, but no file number");
2781 if (parseEscapedString(FilenameData))
2783 Filename = FilenameData;
2790 if (getLexer().isNot(AsmToken::EndOfStatement))
2791 return TokError("unexpected token in '.file' directive");
2793 if (FileNumber == -1)
2794 getStreamer().EmitFileDirective(Filename);
2796 if (getContext().getGenDwarfForAssembly() == true)
2798 "input can't have .file dwarf directives when -g is "
2799 "used to generate dwarf debug info for assembly code");
2801 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2803 Error(FileNumberLoc, "file number already allocated");
2809 /// parseDirectiveLine
2810 /// ::= .line [number]
2811 bool AsmParser::parseDirectiveLine() {
2812 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2813 if (getLexer().isNot(AsmToken::Integer))
2814 return TokError("unexpected token in '.line' directive");
2816 int64_t LineNumber = getTok().getIntVal();
2820 // FIXME: Do something with the .line.
2823 if (getLexer().isNot(AsmToken::EndOfStatement))
2824 return TokError("unexpected token in '.line' directive");
2829 /// parseDirectiveLoc
2830 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2831 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2832 /// The first number is a file number, must have been previously assigned with
2833 /// a .file directive, the second number is the line number and optionally the
2834 /// third number is a column position (zero if not specified). The remaining
2835 /// optional items are .loc sub-directives.
2836 bool AsmParser::parseDirectiveLoc() {
2837 if (getLexer().isNot(AsmToken::Integer))
2838 return TokError("unexpected token in '.loc' directive");
2839 int64_t FileNumber = getTok().getIntVal();
2841 return TokError("file number less than one in '.loc' directive");
2842 if (!getContext().isValidDwarfFileNumber(FileNumber))
2843 return TokError("unassigned file number in '.loc' directive");
2846 int64_t LineNumber = 0;
2847 if (getLexer().is(AsmToken::Integer)) {
2848 LineNumber = getTok().getIntVal();
2850 return TokError("line number less than zero in '.loc' directive");
2854 int64_t ColumnPos = 0;
2855 if (getLexer().is(AsmToken::Integer)) {
2856 ColumnPos = getTok().getIntVal();
2858 return TokError("column position less than zero in '.loc' directive");
2862 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2864 int64_t Discriminator = 0;
2865 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2867 if (getLexer().is(AsmToken::EndOfStatement))
2871 SMLoc Loc = getTok().getLoc();
2872 if (parseIdentifier(Name))
2873 return TokError("unexpected token in '.loc' directive");
2875 if (Name == "basic_block")
2876 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2877 else if (Name == "prologue_end")
2878 Flags |= DWARF2_FLAG_PROLOGUE_END;
2879 else if (Name == "epilogue_begin")
2880 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2881 else if (Name == "is_stmt") {
2882 Loc = getTok().getLoc();
2883 const MCExpr *Value;
2884 if (parseExpression(Value))
2886 // The expression must be the constant 0 or 1.
2887 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2888 int Value = MCE->getValue();
2890 Flags &= ~DWARF2_FLAG_IS_STMT;
2891 else if (Value == 1)
2892 Flags |= DWARF2_FLAG_IS_STMT;
2894 return Error(Loc, "is_stmt value not 0 or 1");
2896 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2898 } else if (Name == "isa") {
2899 Loc = getTok().getLoc();
2900 const MCExpr *Value;
2901 if (parseExpression(Value))
2903 // The expression must be a constant greater or equal to 0.
2904 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2905 int Value = MCE->getValue();
2907 return Error(Loc, "isa number less than zero");
2910 return Error(Loc, "isa number not a constant value");
2912 } else if (Name == "discriminator") {
2913 if (parseAbsoluteExpression(Discriminator))
2916 return Error(Loc, "unknown sub-directive in '.loc' directive");
2919 if (getLexer().is(AsmToken::EndOfStatement))
2924 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2925 Isa, Discriminator, StringRef());
2930 /// parseDirectiveStabs
2931 /// ::= .stabs string, number, number, number
2932 bool AsmParser::parseDirectiveStabs() {
2933 return TokError("unsupported directive '.stabs'");
2936 /// parseDirectiveCFISections
2937 /// ::= .cfi_sections section [, section]
2938 bool AsmParser::parseDirectiveCFISections() {
2943 if (parseIdentifier(Name))
2944 return TokError("Expected an identifier");
2946 if (Name == ".eh_frame")
2948 else if (Name == ".debug_frame")
2951 if (getLexer().is(AsmToken::Comma)) {
2954 if (parseIdentifier(Name))
2955 return TokError("Expected an identifier");
2957 if (Name == ".eh_frame")
2959 else if (Name == ".debug_frame")
2963 getStreamer().EmitCFISections(EH, Debug);
2967 /// parseDirectiveCFIStartProc
2968 /// ::= .cfi_startproc [simple]
2969 bool AsmParser::parseDirectiveCFIStartProc() {
2971 if (getLexer().isNot(AsmToken::EndOfStatement))
2972 if (parseIdentifier(Simple) || Simple != "simple")
2973 return TokError("unexpected token in .cfi_startproc directive");
2975 getStreamer().EmitCFIStartProc(!Simple.empty());
2979 /// parseDirectiveCFIEndProc
2980 /// ::= .cfi_endproc
2981 bool AsmParser::parseDirectiveCFIEndProc() {
2982 getStreamer().EmitCFIEndProc();
2986 /// \brief parse register name or number.
2987 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2988 SMLoc DirectiveLoc) {
2991 if (getLexer().isNot(AsmToken::Integer)) {
2992 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2994 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2996 return parseAbsoluteExpression(Register);
3001 /// parseDirectiveCFIDefCfa
3002 /// ::= .cfi_def_cfa register, offset
3003 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3004 int64_t Register = 0;
3005 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3008 if (getLexer().isNot(AsmToken::Comma))
3009 return TokError("unexpected token in directive");
3013 if (parseAbsoluteExpression(Offset))
3016 getStreamer().EmitCFIDefCfa(Register, Offset);
3020 /// parseDirectiveCFIDefCfaOffset
3021 /// ::= .cfi_def_cfa_offset offset
3022 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3024 if (parseAbsoluteExpression(Offset))
3027 getStreamer().EmitCFIDefCfaOffset(Offset);
3031 /// parseDirectiveCFIRegister
3032 /// ::= .cfi_register register, register
3033 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3034 int64_t Register1 = 0;
3035 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3038 if (getLexer().isNot(AsmToken::Comma))
3039 return TokError("unexpected token in directive");
3042 int64_t Register2 = 0;
3043 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3046 getStreamer().EmitCFIRegister(Register1, Register2);
3050 /// parseDirectiveCFIWindowSave
3051 /// ::= .cfi_window_save
3052 bool AsmParser::parseDirectiveCFIWindowSave() {
3053 getStreamer().EmitCFIWindowSave();
3057 /// parseDirectiveCFIAdjustCfaOffset
3058 /// ::= .cfi_adjust_cfa_offset adjustment
3059 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3060 int64_t Adjustment = 0;
3061 if (parseAbsoluteExpression(Adjustment))
3064 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3068 /// parseDirectiveCFIDefCfaRegister
3069 /// ::= .cfi_def_cfa_register register
3070 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3071 int64_t Register = 0;
3072 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3075 getStreamer().EmitCFIDefCfaRegister(Register);
3079 /// parseDirectiveCFIOffset
3080 /// ::= .cfi_offset register, offset
3081 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3082 int64_t Register = 0;
3085 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3088 if (getLexer().isNot(AsmToken::Comma))
3089 return TokError("unexpected token in directive");
3092 if (parseAbsoluteExpression(Offset))
3095 getStreamer().EmitCFIOffset(Register, Offset);
3099 /// parseDirectiveCFIRelOffset
3100 /// ::= .cfi_rel_offset register, offset
3101 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3102 int64_t Register = 0;
3104 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3107 if (getLexer().isNot(AsmToken::Comma))
3108 return TokError("unexpected token in directive");
3112 if (parseAbsoluteExpression(Offset))
3115 getStreamer().EmitCFIRelOffset(Register, Offset);
3119 static bool isValidEncoding(int64_t Encoding) {
3120 if (Encoding & ~0xff)
3123 if (Encoding == dwarf::DW_EH_PE_omit)
3126 const unsigned Format = Encoding & 0xf;
3127 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3128 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3129 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3130 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3133 const unsigned Application = Encoding & 0x70;
3134 if (Application != dwarf::DW_EH_PE_absptr &&
3135 Application != dwarf::DW_EH_PE_pcrel)
3141 /// parseDirectiveCFIPersonalityOrLsda
3142 /// IsPersonality true for cfi_personality, false for cfi_lsda
3143 /// ::= .cfi_personality encoding, [symbol_name]
3144 /// ::= .cfi_lsda encoding, [symbol_name]
3145 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3146 int64_t Encoding = 0;
3147 if (parseAbsoluteExpression(Encoding))
3149 if (Encoding == dwarf::DW_EH_PE_omit)
3152 if (!isValidEncoding(Encoding))
3153 return TokError("unsupported encoding.");
3155 if (getLexer().isNot(AsmToken::Comma))
3156 return TokError("unexpected token in directive");
3160 if (parseIdentifier(Name))
3161 return TokError("expected identifier in directive");
3163 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3166 getStreamer().EmitCFIPersonality(Sym, Encoding);
3168 getStreamer().EmitCFILsda(Sym, Encoding);
3172 /// parseDirectiveCFIRememberState
3173 /// ::= .cfi_remember_state
3174 bool AsmParser::parseDirectiveCFIRememberState() {
3175 getStreamer().EmitCFIRememberState();
3179 /// parseDirectiveCFIRestoreState
3180 /// ::= .cfi_remember_state
3181 bool AsmParser::parseDirectiveCFIRestoreState() {
3182 getStreamer().EmitCFIRestoreState();
3186 /// parseDirectiveCFISameValue
3187 /// ::= .cfi_same_value register
3188 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3189 int64_t Register = 0;
3191 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3194 getStreamer().EmitCFISameValue(Register);
3198 /// parseDirectiveCFIRestore
3199 /// ::= .cfi_restore register
3200 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3201 int64_t Register = 0;
3202 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3205 getStreamer().EmitCFIRestore(Register);
3209 /// parseDirectiveCFIEscape
3210 /// ::= .cfi_escape expression[,...]
3211 bool AsmParser::parseDirectiveCFIEscape() {
3214 if (parseAbsoluteExpression(CurrValue))
3217 Values.push_back((uint8_t)CurrValue);
3219 while (getLexer().is(AsmToken::Comma)) {
3222 if (parseAbsoluteExpression(CurrValue))
3225 Values.push_back((uint8_t)CurrValue);
3228 getStreamer().EmitCFIEscape(Values);
3232 /// parseDirectiveCFISignalFrame
3233 /// ::= .cfi_signal_frame
3234 bool AsmParser::parseDirectiveCFISignalFrame() {
3235 if (getLexer().isNot(AsmToken::EndOfStatement))
3236 return Error(getLexer().getLoc(),
3237 "unexpected token in '.cfi_signal_frame'");
3239 getStreamer().EmitCFISignalFrame();
3243 /// parseDirectiveCFIUndefined
3244 /// ::= .cfi_undefined register
3245 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3246 int64_t Register = 0;
3248 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3251 getStreamer().EmitCFIUndefined(Register);
3255 /// parseDirectiveMacrosOnOff
3258 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3259 if (getLexer().isNot(AsmToken::EndOfStatement))
3260 return Error(getLexer().getLoc(),
3261 "unexpected token in '" + Directive + "' directive");
3263 setMacrosEnabled(Directive == ".macros_on");
3267 /// parseDirectiveMacro
3268 /// ::= .macro name[,] [parameters]
3269 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3271 if (parseIdentifier(Name))
3272 return TokError("expected identifier in '.macro' directive");
3274 if (getLexer().is(AsmToken::Comma))
3277 MCAsmMacroParameters Parameters;
3278 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3280 if (Parameters.size() && Parameters.back().Vararg)
3281 return Error(Lexer.getLoc(),
3282 "Vararg parameter '" + Parameters.back().Name +
3283 "' should be last one in the list of parameters.");
3285 MCAsmMacroParameter Parameter;
3286 if (parseIdentifier(Parameter.Name))
3287 return TokError("expected identifier in '.macro' directive");
3289 if (Lexer.is(AsmToken::Colon)) {
3290 Lex(); // consume ':'
3293 StringRef Qualifier;
3295 QualLoc = Lexer.getLoc();
3296 if (parseIdentifier(Qualifier))
3297 return Error(QualLoc, "missing parameter qualifier for "
3298 "'" + Parameter.Name + "' in macro '" + Name + "'");
3300 if (Qualifier == "req")
3301 Parameter.Required = true;
3302 else if (Qualifier == "vararg")
3303 Parameter.Vararg = true;
3305 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3306 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3309 if (getLexer().is(AsmToken::Equal)) {
3314 ParamLoc = Lexer.getLoc();
3315 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3318 if (Parameter.Required)
3319 Warning(ParamLoc, "pointless default value for required parameter "
3320 "'" + Parameter.Name + "' in macro '" + Name + "'");
3323 Parameters.push_back(Parameter);
3325 if (getLexer().is(AsmToken::Comma))
3329 // Eat the end of statement.
3332 AsmToken EndToken, StartToken = getTok();
3333 unsigned MacroDepth = 0;
3335 // Lex the macro definition.
3337 // Check whether we have reached the end of the file.
3338 if (getLexer().is(AsmToken::Eof))
3339 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3341 // Otherwise, check whether we have reach the .endmacro.
3342 if (getLexer().is(AsmToken::Identifier)) {
3343 if (getTok().getIdentifier() == ".endm" ||
3344 getTok().getIdentifier() == ".endmacro") {
3345 if (MacroDepth == 0) { // Outermost macro.
3346 EndToken = getTok();
3348 if (getLexer().isNot(AsmToken::EndOfStatement))
3349 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3353 // Otherwise we just found the end of an inner macro.
3356 } else if (getTok().getIdentifier() == ".macro") {
3357 // We allow nested macros. Those aren't instantiated until the outermost
3358 // macro is expanded so just ignore them for now.
3363 // Otherwise, scan til the end of the statement.
3364 eatToEndOfStatement();
3367 if (lookupMacro(Name)) {
3368 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3371 const char *BodyStart = StartToken.getLoc().getPointer();
3372 const char *BodyEnd = EndToken.getLoc().getPointer();
3373 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3374 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3375 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3379 /// checkForBadMacro
3381 /// With the support added for named parameters there may be code out there that
3382 /// is transitioning from positional parameters. In versions of gas that did
3383 /// not support named parameters they would be ignored on the macro definition.
3384 /// But to support both styles of parameters this is not possible so if a macro
3385 /// definition has named parameters but does not use them and has what appears
3386 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3387 /// warning that the positional parameter found in body which have no effect.
3388 /// Hoping the developer will either remove the named parameters from the macro
3389 /// definition so the positional parameters get used if that was what was
3390 /// intended or change the macro to use the named parameters. It is possible
3391 /// this warning will trigger when the none of the named parameters are used
3392 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3393 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3395 ArrayRef<MCAsmMacroParameter> Parameters) {
3396 // If this macro is not defined with named parameters the warning we are
3397 // checking for here doesn't apply.
3398 unsigned NParameters = Parameters.size();
3399 if (NParameters == 0)
3402 bool NamedParametersFound = false;
3403 bool PositionalParametersFound = false;
3405 // Look at the body of the macro for use of both the named parameters and what
3406 // are likely to be positional parameters. This is what expandMacro() is
3407 // doing when it finds the parameters in the body.
3408 while (!Body.empty()) {
3409 // Scan for the next possible parameter.
3410 std::size_t End = Body.size(), Pos = 0;
3411 for (; Pos != End; ++Pos) {
3412 // Check for a substitution or escape.
3413 // This macro is defined with parameters, look for \foo, \bar, etc.
3414 if (Body[Pos] == '\\' && Pos + 1 != End)
3417 // This macro should have parameters, but look for $0, $1, ..., $n too.
3418 if (Body[Pos] != '$' || Pos + 1 == End)
3420 char Next = Body[Pos + 1];
3421 if (Next == '$' || Next == 'n' ||
3422 isdigit(static_cast<unsigned char>(Next)))
3426 // Check if we reached the end.
3430 if (Body[Pos] == '$') {
3431 switch (Body[Pos + 1]) {
3436 // $n => number of arguments
3438 PositionalParametersFound = true;
3441 // $[0-9] => argument
3443 PositionalParametersFound = true;
3449 unsigned I = Pos + 1;
3450 while (isIdentifierChar(Body[I]) && I + 1 != End)
3453 const char *Begin = Body.data() + Pos + 1;
3454 StringRef Argument(Begin, I - (Pos + 1));
3456 for (; Index < NParameters; ++Index)
3457 if (Parameters[Index].Name == Argument)
3460 if (Index == NParameters) {
3461 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3467 NamedParametersFound = true;
3468 Pos += 1 + Argument.size();
3471 // Update the scan point.
3472 Body = Body.substr(Pos);
3475 if (!NamedParametersFound && PositionalParametersFound)
3476 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3477 "used in macro body, possible positional parameter "
3478 "found in body which will have no effect");
3481 /// parseDirectiveExitMacro
3483 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3484 if (getLexer().isNot(AsmToken::EndOfStatement))
3485 return TokError("unexpected token in '" + Directive + "' directive");
3487 if (!isInsideMacroInstantiation())
3488 return TokError("unexpected '" + Directive + "' in file, "
3489 "no current macro definition");
3491 // Exit all conditionals that are active in the current macro.
3492 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3493 TheCondState = TheCondStack.back();
3494 TheCondStack.pop_back();
3501 /// parseDirectiveEndMacro
3504 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3505 if (getLexer().isNot(AsmToken::EndOfStatement))
3506 return TokError("unexpected token in '" + Directive + "' directive");
3508 // If we are inside a macro instantiation, terminate the current
3510 if (isInsideMacroInstantiation()) {
3515 // Otherwise, this .endmacro is a stray entry in the file; well formed
3516 // .endmacro directives are handled during the macro definition parsing.
3517 return TokError("unexpected '" + Directive + "' in file, "
3518 "no current macro definition");
3521 /// parseDirectivePurgeMacro
3523 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3525 if (parseIdentifier(Name))
3526 return TokError("expected identifier in '.purgem' directive");
3528 if (getLexer().isNot(AsmToken::EndOfStatement))
3529 return TokError("unexpected token in '.purgem' directive");
3531 if (!lookupMacro(Name))
3532 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3534 undefineMacro(Name);
3538 /// parseDirectiveBundleAlignMode
3539 /// ::= {.bundle_align_mode} expression
3540 bool AsmParser::parseDirectiveBundleAlignMode() {
3541 checkForValidSection();
3543 // Expect a single argument: an expression that evaluates to a constant
3544 // in the inclusive range 0-30.
3545 SMLoc ExprLoc = getLexer().getLoc();
3546 int64_t AlignSizePow2;
3547 if (parseAbsoluteExpression(AlignSizePow2))
3549 else if (getLexer().isNot(AsmToken::EndOfStatement))
3550 return TokError("unexpected token after expression in"
3551 " '.bundle_align_mode' directive");
3552 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3553 return Error(ExprLoc,
3554 "invalid bundle alignment size (expected between 0 and 30)");
3558 // Because of AlignSizePow2's verified range we can safely truncate it to
3560 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3564 /// parseDirectiveBundleLock
3565 /// ::= {.bundle_lock} [align_to_end]
3566 bool AsmParser::parseDirectiveBundleLock() {
3567 checkForValidSection();
3568 bool AlignToEnd = false;
3570 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3572 SMLoc Loc = getTok().getLoc();
3573 const char *kInvalidOptionError =
3574 "invalid option for '.bundle_lock' directive";
3576 if (parseIdentifier(Option))
3577 return Error(Loc, kInvalidOptionError);
3579 if (Option != "align_to_end")
3580 return Error(Loc, kInvalidOptionError);
3581 else if (getLexer().isNot(AsmToken::EndOfStatement))
3583 "unexpected token after '.bundle_lock' directive option");
3589 getStreamer().EmitBundleLock(AlignToEnd);
3593 /// parseDirectiveBundleLock
3594 /// ::= {.bundle_lock}
3595 bool AsmParser::parseDirectiveBundleUnlock() {
3596 checkForValidSection();
3598 if (getLexer().isNot(AsmToken::EndOfStatement))
3599 return TokError("unexpected token in '.bundle_unlock' directive");
3602 getStreamer().EmitBundleUnlock();
3606 /// parseDirectiveSpace
3607 /// ::= (.skip | .space) expression [ , expression ]
3608 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3609 checkForValidSection();
3612 if (parseAbsoluteExpression(NumBytes))
3615 int64_t FillExpr = 0;
3616 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3617 if (getLexer().isNot(AsmToken::Comma))
3618 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3621 if (parseAbsoluteExpression(FillExpr))
3624 if (getLexer().isNot(AsmToken::EndOfStatement))
3625 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3631 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3634 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3635 getStreamer().EmitFill(NumBytes, FillExpr);
3640 /// parseDirectiveLEB128
3641 /// ::= (.sleb128 | .uleb128) expression
3642 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3643 checkForValidSection();
3644 const MCExpr *Value;
3646 if (parseExpression(Value))
3649 if (getLexer().isNot(AsmToken::EndOfStatement))
3650 return TokError("unexpected token in directive");
3653 getStreamer().EmitSLEB128Value(Value);
3655 getStreamer().EmitULEB128Value(Value);
3660 /// parseDirectiveSymbolAttribute
3661 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3662 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3663 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3666 SMLoc Loc = getTok().getLoc();
3668 if (parseIdentifier(Name))
3669 return Error(Loc, "expected identifier in directive");
3671 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3673 // Assembler local symbols don't make any sense here. Complain loudly.
3674 if (Sym->isTemporary())
3675 return Error(Loc, "non-local symbol required in directive");
3677 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3678 return Error(Loc, "unable to emit symbol attribute");
3680 if (getLexer().is(AsmToken::EndOfStatement))
3683 if (getLexer().isNot(AsmToken::Comma))
3684 return TokError("unexpected token in directive");
3693 /// parseDirectiveComm
3694 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3695 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3696 checkForValidSection();
3698 SMLoc IDLoc = getLexer().getLoc();
3700 if (parseIdentifier(Name))
3701 return TokError("expected identifier in directive");
3703 // Handle the identifier as the key symbol.
3704 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3706 if (getLexer().isNot(AsmToken::Comma))
3707 return TokError("unexpected token in directive");
3711 SMLoc SizeLoc = getLexer().getLoc();
3712 if (parseAbsoluteExpression(Size))
3715 int64_t Pow2Alignment = 0;
3716 SMLoc Pow2AlignmentLoc;
3717 if (getLexer().is(AsmToken::Comma)) {
3719 Pow2AlignmentLoc = getLexer().getLoc();
3720 if (parseAbsoluteExpression(Pow2Alignment))
3723 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3724 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3725 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3727 // If this target takes alignments in bytes (not log) validate and convert.
3728 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3729 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3730 if (!isPowerOf2_64(Pow2Alignment))
3731 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3732 Pow2Alignment = Log2_64(Pow2Alignment);
3736 if (getLexer().isNot(AsmToken::EndOfStatement))
3737 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3741 // NOTE: a size of zero for a .comm should create a undefined symbol
3742 // but a size of .lcomm creates a bss symbol of size zero.
3744 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3745 "be less than zero");
3747 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3748 // may internally end up wanting an alignment in bytes.
3749 // FIXME: Diagnose overflow.
3750 if (Pow2Alignment < 0)
3751 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3752 "alignment, can't be less than zero");
3754 if (!Sym->isUndefined())
3755 return Error(IDLoc, "invalid symbol redefinition");
3757 // Create the Symbol as a common or local common with Size and Pow2Alignment
3759 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3763 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3767 /// parseDirectiveAbort
3768 /// ::= .abort [... message ...]
3769 bool AsmParser::parseDirectiveAbort() {
3770 // FIXME: Use loc from directive.
3771 SMLoc Loc = getLexer().getLoc();
3773 StringRef Str = parseStringToEndOfStatement();
3774 if (getLexer().isNot(AsmToken::EndOfStatement))
3775 return TokError("unexpected token in '.abort' directive");
3780 Error(Loc, ".abort detected. Assembly stopping.");
3782 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3783 // FIXME: Actually abort assembly here.
3788 /// parseDirectiveInclude
3789 /// ::= .include "filename"
3790 bool AsmParser::parseDirectiveInclude() {
3791 if (getLexer().isNot(AsmToken::String))
3792 return TokError("expected string in '.include' directive");
3794 // Allow the strings to have escaped octal character sequence.
3795 std::string Filename;
3796 if (parseEscapedString(Filename))
3798 SMLoc IncludeLoc = getLexer().getLoc();
3801 if (getLexer().isNot(AsmToken::EndOfStatement))
3802 return TokError("unexpected token in '.include' directive");
3804 // Attempt to switch the lexer to the included file before consuming the end
3805 // of statement to avoid losing it when we switch.
3806 if (enterIncludeFile(Filename)) {
3807 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3814 /// parseDirectiveIncbin
3815 /// ::= .incbin "filename"
3816 bool AsmParser::parseDirectiveIncbin() {
3817 if (getLexer().isNot(AsmToken::String))
3818 return TokError("expected string in '.incbin' directive");
3820 // Allow the strings to have escaped octal character sequence.
3821 std::string Filename;
3822 if (parseEscapedString(Filename))
3824 SMLoc IncbinLoc = getLexer().getLoc();
3827 if (getLexer().isNot(AsmToken::EndOfStatement))
3828 return TokError("unexpected token in '.incbin' directive");
3830 // Attempt to process the included file.
3831 if (processIncbinFile(Filename)) {
3832 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3839 /// parseDirectiveIf
3840 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3841 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3842 TheCondStack.push_back(TheCondState);
3843 TheCondState.TheCond = AsmCond::IfCond;
3844 if (TheCondState.Ignore) {
3845 eatToEndOfStatement();
3848 if (parseAbsoluteExpression(ExprValue))
3851 if (getLexer().isNot(AsmToken::EndOfStatement))
3852 return TokError("unexpected token in '.if' directive");
3858 llvm_unreachable("unsupported directive");
3863 ExprValue = ExprValue == 0;
3866 ExprValue = ExprValue >= 0;
3869 ExprValue = ExprValue > 0;
3872 ExprValue = ExprValue <= 0;
3875 ExprValue = ExprValue < 0;
3879 TheCondState.CondMet = ExprValue;
3880 TheCondState.Ignore = !TheCondState.CondMet;
3886 /// parseDirectiveIfb
3888 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3889 TheCondStack.push_back(TheCondState);
3890 TheCondState.TheCond = AsmCond::IfCond;
3892 if (TheCondState.Ignore) {
3893 eatToEndOfStatement();
3895 StringRef Str = parseStringToEndOfStatement();
3897 if (getLexer().isNot(AsmToken::EndOfStatement))
3898 return TokError("unexpected token in '.ifb' directive");
3902 TheCondState.CondMet = ExpectBlank == Str.empty();
3903 TheCondState.Ignore = !TheCondState.CondMet;
3909 /// parseDirectiveIfc
3910 /// ::= .ifc string1, string2
3911 /// ::= .ifnc string1, string2
3912 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3913 TheCondStack.push_back(TheCondState);
3914 TheCondState.TheCond = AsmCond::IfCond;
3916 if (TheCondState.Ignore) {
3917 eatToEndOfStatement();
3919 StringRef Str1 = parseStringToComma();
3921 if (getLexer().isNot(AsmToken::Comma))
3922 return TokError("unexpected token in '.ifc' directive");
3926 StringRef Str2 = parseStringToEndOfStatement();
3928 if (getLexer().isNot(AsmToken::EndOfStatement))
3929 return TokError("unexpected token in '.ifc' directive");
3933 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3934 TheCondState.Ignore = !TheCondState.CondMet;
3940 /// parseDirectiveIfeqs
3941 /// ::= .ifeqs string1, string2
3942 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3943 if (Lexer.isNot(AsmToken::String)) {
3944 TokError("expected string parameter for '.ifeqs' directive");
3945 eatToEndOfStatement();
3949 StringRef String1 = getTok().getStringContents();
3952 if (Lexer.isNot(AsmToken::Comma)) {
3953 TokError("expected comma after first string for '.ifeqs' directive");
3954 eatToEndOfStatement();
3960 if (Lexer.isNot(AsmToken::String)) {
3961 TokError("expected string parameter for '.ifeqs' directive");
3962 eatToEndOfStatement();
3966 StringRef String2 = getTok().getStringContents();
3969 TheCondStack.push_back(TheCondState);
3970 TheCondState.TheCond = AsmCond::IfCond;
3971 TheCondState.CondMet = String1 == String2;
3972 TheCondState.Ignore = !TheCondState.CondMet;
3977 /// parseDirectiveIfdef
3978 /// ::= .ifdef symbol
3979 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3981 TheCondStack.push_back(TheCondState);
3982 TheCondState.TheCond = AsmCond::IfCond;
3984 if (TheCondState.Ignore) {
3985 eatToEndOfStatement();
3987 if (parseIdentifier(Name))
3988 return TokError("expected identifier after '.ifdef'");
3992 MCSymbol *Sym = getContext().LookupSymbol(Name);
3995 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3997 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3998 TheCondState.Ignore = !TheCondState.CondMet;
4004 /// parseDirectiveElseIf
4005 /// ::= .elseif expression
4006 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4007 if (TheCondState.TheCond != AsmCond::IfCond &&
4008 TheCondState.TheCond != AsmCond::ElseIfCond)
4009 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4011 TheCondState.TheCond = AsmCond::ElseIfCond;
4013 bool LastIgnoreState = false;
4014 if (!TheCondStack.empty())
4015 LastIgnoreState = TheCondStack.back().Ignore;
4016 if (LastIgnoreState || TheCondState.CondMet) {
4017 TheCondState.Ignore = true;
4018 eatToEndOfStatement();
4021 if (parseAbsoluteExpression(ExprValue))
4024 if (getLexer().isNot(AsmToken::EndOfStatement))
4025 return TokError("unexpected token in '.elseif' directive");
4028 TheCondState.CondMet = ExprValue;
4029 TheCondState.Ignore = !TheCondState.CondMet;
4035 /// parseDirectiveElse
4037 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4038 if (getLexer().isNot(AsmToken::EndOfStatement))
4039 return TokError("unexpected token in '.else' directive");
4043 if (TheCondState.TheCond != AsmCond::IfCond &&
4044 TheCondState.TheCond != AsmCond::ElseIfCond)
4045 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4047 TheCondState.TheCond = AsmCond::ElseCond;
4048 bool LastIgnoreState = false;
4049 if (!TheCondStack.empty())
4050 LastIgnoreState = TheCondStack.back().Ignore;
4051 if (LastIgnoreState || TheCondState.CondMet)
4052 TheCondState.Ignore = true;
4054 TheCondState.Ignore = false;
4059 /// parseDirectiveEnd
4061 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4062 if (getLexer().isNot(AsmToken::EndOfStatement))
4063 return TokError("unexpected token in '.end' directive");
4067 while (Lexer.isNot(AsmToken::Eof))
4073 /// parseDirectiveError
4075 /// ::= .error [string]
4076 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4077 if (!TheCondStack.empty()) {
4078 if (TheCondStack.back().Ignore) {
4079 eatToEndOfStatement();
4085 return Error(L, ".err encountered");
4087 StringRef Message = ".error directive invoked in source file";
4088 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4089 if (Lexer.isNot(AsmToken::String)) {
4090 TokError(".error argument must be a string");
4091 eatToEndOfStatement();
4095 Message = getTok().getStringContents();
4103 /// parseDirectiveWarning
4104 /// ::= .warning [string]
4105 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4106 if (!TheCondStack.empty()) {
4107 if (TheCondStack.back().Ignore) {
4108 eatToEndOfStatement();
4113 StringRef Message = ".warning directive invoked in source file";
4114 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4115 if (Lexer.isNot(AsmToken::String)) {
4116 TokError(".warning argument must be a string");
4117 eatToEndOfStatement();
4121 Message = getTok().getStringContents();
4125 Warning(L, Message);
4129 /// parseDirectiveEndIf
4131 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4132 if (getLexer().isNot(AsmToken::EndOfStatement))
4133 return TokError("unexpected token in '.endif' directive");
4137 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4138 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4140 if (!TheCondStack.empty()) {
4141 TheCondState = TheCondStack.back();
4142 TheCondStack.pop_back();
4148 void AsmParser::initializeDirectiveKindMap() {
4149 DirectiveKindMap[".set"] = DK_SET;
4150 DirectiveKindMap[".equ"] = DK_EQU;
4151 DirectiveKindMap[".equiv"] = DK_EQUIV;
4152 DirectiveKindMap[".ascii"] = DK_ASCII;
4153 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4154 DirectiveKindMap[".string"] = DK_STRING;
4155 DirectiveKindMap[".byte"] = DK_BYTE;
4156 DirectiveKindMap[".short"] = DK_SHORT;
4157 DirectiveKindMap[".value"] = DK_VALUE;
4158 DirectiveKindMap[".2byte"] = DK_2BYTE;
4159 DirectiveKindMap[".long"] = DK_LONG;
4160 DirectiveKindMap[".int"] = DK_INT;
4161 DirectiveKindMap[".4byte"] = DK_4BYTE;
4162 DirectiveKindMap[".quad"] = DK_QUAD;
4163 DirectiveKindMap[".8byte"] = DK_8BYTE;
4164 DirectiveKindMap[".octa"] = DK_OCTA;
4165 DirectiveKindMap[".single"] = DK_SINGLE;
4166 DirectiveKindMap[".float"] = DK_FLOAT;
4167 DirectiveKindMap[".double"] = DK_DOUBLE;
4168 DirectiveKindMap[".align"] = DK_ALIGN;
4169 DirectiveKindMap[".align32"] = DK_ALIGN32;
4170 DirectiveKindMap[".balign"] = DK_BALIGN;
4171 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4172 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4173 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4174 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4175 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4176 DirectiveKindMap[".org"] = DK_ORG;
4177 DirectiveKindMap[".fill"] = DK_FILL;
4178 DirectiveKindMap[".zero"] = DK_ZERO;
4179 DirectiveKindMap[".extern"] = DK_EXTERN;
4180 DirectiveKindMap[".globl"] = DK_GLOBL;
4181 DirectiveKindMap[".global"] = DK_GLOBAL;
4182 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4183 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4184 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4185 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4186 DirectiveKindMap[".reference"] = DK_REFERENCE;
4187 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4188 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4189 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4190 DirectiveKindMap[".comm"] = DK_COMM;
4191 DirectiveKindMap[".common"] = DK_COMMON;
4192 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4193 DirectiveKindMap[".abort"] = DK_ABORT;
4194 DirectiveKindMap[".include"] = DK_INCLUDE;
4195 DirectiveKindMap[".incbin"] = DK_INCBIN;
4196 DirectiveKindMap[".code16"] = DK_CODE16;
4197 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4198 DirectiveKindMap[".rept"] = DK_REPT;
4199 DirectiveKindMap[".rep"] = DK_REPT;
4200 DirectiveKindMap[".irp"] = DK_IRP;
4201 DirectiveKindMap[".irpc"] = DK_IRPC;
4202 DirectiveKindMap[".endr"] = DK_ENDR;
4203 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4204 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4205 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4206 DirectiveKindMap[".if"] = DK_IF;
4207 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4208 DirectiveKindMap[".ifge"] = DK_IFGE;
4209 DirectiveKindMap[".ifgt"] = DK_IFGT;
4210 DirectiveKindMap[".ifle"] = DK_IFLE;
4211 DirectiveKindMap[".iflt"] = DK_IFLT;
4212 DirectiveKindMap[".ifne"] = DK_IFNE;
4213 DirectiveKindMap[".ifb"] = DK_IFB;
4214 DirectiveKindMap[".ifnb"] = DK_IFNB;
4215 DirectiveKindMap[".ifc"] = DK_IFC;
4216 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4217 DirectiveKindMap[".ifnc"] = DK_IFNC;
4218 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4219 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4220 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4221 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4222 DirectiveKindMap[".else"] = DK_ELSE;
4223 DirectiveKindMap[".end"] = DK_END;
4224 DirectiveKindMap[".endif"] = DK_ENDIF;
4225 DirectiveKindMap[".skip"] = DK_SKIP;
4226 DirectiveKindMap[".space"] = DK_SPACE;
4227 DirectiveKindMap[".file"] = DK_FILE;
4228 DirectiveKindMap[".line"] = DK_LINE;
4229 DirectiveKindMap[".loc"] = DK_LOC;
4230 DirectiveKindMap[".stabs"] = DK_STABS;
4231 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4232 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4233 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4234 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4235 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4236 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4237 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4238 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4239 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4240 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4241 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4242 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4243 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4244 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4245 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4246 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4247 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4248 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4249 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4250 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4251 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4252 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4253 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4254 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4255 DirectiveKindMap[".macro"] = DK_MACRO;
4256 DirectiveKindMap[".exitm"] = DK_EXITM;
4257 DirectiveKindMap[".endm"] = DK_ENDM;
4258 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4259 DirectiveKindMap[".purgem"] = DK_PURGEM;
4260 DirectiveKindMap[".err"] = DK_ERR;
4261 DirectiveKindMap[".error"] = DK_ERROR;
4262 DirectiveKindMap[".warning"] = DK_WARNING;
4265 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4266 AsmToken EndToken, StartToken = getTok();
4268 unsigned NestLevel = 0;
4270 // Check whether we have reached the end of the file.
4271 if (getLexer().is(AsmToken::Eof)) {
4272 Error(DirectiveLoc, "no matching '.endr' in definition");
4276 if (Lexer.is(AsmToken::Identifier) &&
4277 (getTok().getIdentifier() == ".rept")) {
4281 // Otherwise, check whether we have reached the .endr.
4282 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4283 if (NestLevel == 0) {
4284 EndToken = getTok();
4286 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4287 TokError("unexpected token in '.endr' directive");
4295 // Otherwise, scan till the end of the statement.
4296 eatToEndOfStatement();
4299 const char *BodyStart = StartToken.getLoc().getPointer();
4300 const char *BodyEnd = EndToken.getLoc().getPointer();
4301 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4303 // We Are Anonymous.
4304 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4305 return &MacroLikeBodies.back();
4308 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4309 raw_svector_ostream &OS) {
4312 MemoryBuffer *Instantiation =
4313 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4315 // Create the macro instantiation object and add to the current macro
4316 // instantiation stack.
4317 MacroInstantiation *MI =
4318 new MacroInstantiation(DirectiveLoc, CurBuffer, getTok().getLoc(),
4319 Instantiation->getBuffer(), TheCondStack.size());
4320 ActiveMacros.push_back(MI);
4322 // Jump to the macro instantiation and prime the lexer.
4323 CurBuffer = SrcMgr.AddNewSourceBuffer(Instantiation, SMLoc());
4324 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4328 /// parseDirectiveRept
4329 /// ::= .rep | .rept count
4330 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4331 const MCExpr *CountExpr;
4332 SMLoc CountLoc = getTok().getLoc();
4333 if (parseExpression(CountExpr))
4337 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4338 eatToEndOfStatement();
4339 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4343 return Error(CountLoc, "Count is negative");
4345 if (Lexer.isNot(AsmToken::EndOfStatement))
4346 return TokError("unexpected token in '" + Dir + "' directive");
4348 // Eat the end of statement.
4351 // Lex the rept definition.
4352 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4356 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4357 // to hold the macro body with substitutions.
4358 SmallString<256> Buf;
4359 raw_svector_ostream OS(Buf);
4361 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4364 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4369 /// parseDirectiveIrp
4370 /// ::= .irp symbol,values
4371 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4372 MCAsmMacroParameter Parameter;
4374 if (parseIdentifier(Parameter.Name))
4375 return TokError("expected identifier in '.irp' directive");
4377 if (Lexer.isNot(AsmToken::Comma))
4378 return TokError("expected comma in '.irp' directive");
4382 MCAsmMacroArguments A;
4383 if (parseMacroArguments(nullptr, A))
4386 // Eat the end of statement.
4389 // Lex the irp definition.
4390 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4394 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4395 // to hold the macro body with substitutions.
4396 SmallString<256> Buf;
4397 raw_svector_ostream OS(Buf);
4399 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4400 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4404 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4409 /// parseDirectiveIrpc
4410 /// ::= .irpc symbol,values
4411 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4412 MCAsmMacroParameter Parameter;
4414 if (parseIdentifier(Parameter.Name))
4415 return TokError("expected identifier in '.irpc' directive");
4417 if (Lexer.isNot(AsmToken::Comma))
4418 return TokError("expected comma in '.irpc' directive");
4422 MCAsmMacroArguments A;
4423 if (parseMacroArguments(nullptr, A))
4426 if (A.size() != 1 || A.front().size() != 1)
4427 return TokError("unexpected token in '.irpc' directive");
4429 // Eat the end of statement.
4432 // Lex the irpc definition.
4433 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4437 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4438 // to hold the macro body with substitutions.
4439 SmallString<256> Buf;
4440 raw_svector_ostream OS(Buf);
4442 StringRef Values = A.front().front().getString();
4443 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4444 MCAsmMacroArgument Arg;
4445 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4447 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4451 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4456 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4457 if (ActiveMacros.empty())
4458 return TokError("unmatched '.endr' directive");
4460 // The only .repl that should get here are the ones created by
4461 // instantiateMacroLikeBody.
4462 assert(getLexer().is(AsmToken::EndOfStatement));
4468 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4470 const MCExpr *Value;
4471 SMLoc ExprLoc = getLexer().getLoc();
4472 if (parseExpression(Value))
4474 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4476 return Error(ExprLoc, "unexpected expression in _emit");
4477 uint64_t IntValue = MCE->getValue();
4478 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4479 return Error(ExprLoc, "literal value out of range for directive");
4481 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4485 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4486 const MCExpr *Value;
4487 SMLoc ExprLoc = getLexer().getLoc();
4488 if (parseExpression(Value))
4490 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4492 return Error(ExprLoc, "unexpected expression in align");
4493 uint64_t IntValue = MCE->getValue();
4494 if (!isPowerOf2_64(IntValue))
4495 return Error(ExprLoc, "literal value not a power of two greater then zero");
4497 Info.AsmRewrites->push_back(
4498 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4502 // We are comparing pointers, but the pointers are relative to a single string.
4503 // Thus, this should always be deterministic.
4504 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4505 const AsmRewrite *AsmRewriteB) {
4506 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4508 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4511 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4512 // rewrite to the same location. Make sure the SizeDirective rewrite is
4513 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4514 // ensures the sort algorithm is stable.
4515 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4516 AsmRewritePrecedence[AsmRewriteB->Kind])
4519 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4520 AsmRewritePrecedence[AsmRewriteB->Kind])
4522 llvm_unreachable("Unstable rewrite sort.");
4525 bool AsmParser::parseMSInlineAsm(
4526 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4527 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4528 SmallVectorImpl<std::string> &Constraints,
4529 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4530 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4531 SmallVector<void *, 4> InputDecls;
4532 SmallVector<void *, 4> OutputDecls;
4533 SmallVector<bool, 4> InputDeclsAddressOf;
4534 SmallVector<bool, 4> OutputDeclsAddressOf;
4535 SmallVector<std::string, 4> InputConstraints;
4536 SmallVector<std::string, 4> OutputConstraints;
4537 SmallVector<unsigned, 4> ClobberRegs;
4539 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4544 // While we have input, parse each statement.
4545 unsigned InputIdx = 0;
4546 unsigned OutputIdx = 0;
4547 while (getLexer().isNot(AsmToken::Eof)) {
4548 ParseStatementInfo Info(&AsmStrRewrites);
4549 if (parseStatement(Info))
4552 if (Info.ParseError)
4555 if (Info.Opcode == ~0U)
4558 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4560 // Build the list of clobbers, outputs and inputs.
4561 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4562 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4565 if (Operand.isImm())
4568 // Register operand.
4569 if (Operand.isReg() && !Operand.needAddressOf() &&
4570 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4571 unsigned NumDefs = Desc.getNumDefs();
4573 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4574 ClobberRegs.push_back(Operand.getReg());
4578 // Expr/Input or Output.
4579 StringRef SymName = Operand.getSymName();
4580 if (SymName.empty())
4583 void *OpDecl = Operand.getOpDecl();
4587 bool isOutput = (i == 1) && Desc.mayStore();
4588 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4591 OutputDecls.push_back(OpDecl);
4592 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4593 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4594 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4596 InputDecls.push_back(OpDecl);
4597 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4598 InputConstraints.push_back(Operand.getConstraint().str());
4599 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4603 // Consider implicit defs to be clobbers. Think of cpuid and push.
4604 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4605 Desc.getNumImplicitDefs());
4606 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4609 // Set the number of Outputs and Inputs.
4610 NumOutputs = OutputDecls.size();
4611 NumInputs = InputDecls.size();
4613 // Set the unique clobbers.
4614 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4615 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4617 Clobbers.assign(ClobberRegs.size(), std::string());
4618 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4619 raw_string_ostream OS(Clobbers[I]);
4620 IP->printRegName(OS, ClobberRegs[I]);
4623 // Merge the various outputs and inputs. Output are expected first.
4624 if (NumOutputs || NumInputs) {
4625 unsigned NumExprs = NumOutputs + NumInputs;
4626 OpDecls.resize(NumExprs);
4627 Constraints.resize(NumExprs);
4628 for (unsigned i = 0; i < NumOutputs; ++i) {
4629 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4630 Constraints[i] = OutputConstraints[i];
4632 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4633 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4634 Constraints[j] = InputConstraints[i];
4638 // Build the IR assembly string.
4639 std::string AsmStringIR;
4640 raw_string_ostream OS(AsmStringIR);
4641 StringRef ASMString =
4642 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4643 const char *AsmStart = ASMString.begin();
4644 const char *AsmEnd = ASMString.end();
4645 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4646 for (const AsmRewrite &AR : AsmStrRewrites) {
4647 AsmRewriteKind Kind = AR.Kind;
4648 if (Kind == AOK_Delete)
4651 const char *Loc = AR.Loc.getPointer();
4652 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4654 // Emit everything up to the immediate/expression.
4655 if (unsigned Len = Loc - AsmStart)
4656 OS << StringRef(AsmStart, Len);
4658 // Skip the original expression.
4659 if (Kind == AOK_Skip) {
4660 AsmStart = Loc + AR.Len;
4664 unsigned AdditionalSkip = 0;
4665 // Rewrite expressions in $N notation.
4670 OS << "$$" << AR.Val;
4676 OS << '$' << InputIdx++;
4679 OS << '$' << OutputIdx++;
4681 case AOK_SizeDirective:
4684 case 8: OS << "byte ptr "; break;
4685 case 16: OS << "word ptr "; break;
4686 case 32: OS << "dword ptr "; break;
4687 case 64: OS << "qword ptr "; break;
4688 case 80: OS << "xword ptr "; break;
4689 case 128: OS << "xmmword ptr "; break;
4690 case 256: OS << "ymmword ptr "; break;
4697 unsigned Val = AR.Val;
4698 OS << ".align " << Val;
4700 // Skip the original immediate.
4701 assert(Val < 10 && "Expected alignment less then 2^10.");
4702 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4705 case AOK_DotOperator:
4706 // Insert the dot if the user omitted it.
4708 if (AsmStringIR.back() != '.')
4714 // Skip the original expression.
4715 AsmStart = Loc + AR.Len + AdditionalSkip;
4718 // Emit the remainder of the asm string.
4719 if (AsmStart != AsmEnd)
4720 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4722 AsmString = OS.str();
4726 /// \brief Create an MCAsmParser instance.
4727 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4728 MCStreamer &Out, const MCAsmInfo &MAI) {
4729 return new AsmParser(SM, C, Out, MAI);