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/MCAsmParserUtils.h"
30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCTargetAsmParser.h"
36 #include "llvm/MC/MCValue.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/raw_ostream.h"
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper types for tracking macro definitions.
54 typedef std::vector<AsmToken> MCAsmMacroArgument;
55 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 struct MCAsmMacroParameter {
59 MCAsmMacroArgument Value;
63 MCAsmMacroParameter() : Required(false), Vararg(false) {}
66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71 MCAsmMacroParameters Parameters;
74 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
75 : Name(N), Body(B), Parameters(std::move(P)) {}
78 /// \brief Helper class for storing information about an active macro
80 struct MacroInstantiation {
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
84 /// The buffer where parsing should resume upon instantiation completion.
87 /// The location where parsing should resume upon instantiation completion.
90 /// The depth of TheCondStack at the start of the instantiation.
91 size_t CondStackDepth;
94 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
114 /// \brief The concrete assembly parser instance.
115 class AsmParser : public MCAsmParser {
116 AsmParser(const AsmParser &) = delete;
117 void operator=(const AsmParser &) = delete;
122 const MCAsmInfo &MAI;
124 SourceMgr::DiagHandlerTy SavedDiagHandler;
125 void *SavedDiagContext;
126 std::unique_ptr<MCAsmParserExtension> PlatformParser;
128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
135 /// \brief maps directive names to handler methods in parser
136 /// extensions. Extensions register themselves in this map by calling
137 /// addDirectiveHandler.
138 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
140 /// \brief Map of currently defined macros.
141 StringMap<MCAsmMacro> MacroMap;
143 /// \brief Stack of active macro instantiations.
144 std::vector<MacroInstantiation*> ActiveMacros;
146 /// \brief List of bodies of anonymous macros.
147 std::deque<MCAsmMacro> MacroLikeBodies;
149 /// Boolean tracking whether macro substitution is enabled.
150 unsigned MacrosEnabledFlag : 1;
152 /// \brief Keeps track of how many .macro's have been instantiated.
153 unsigned NumOfMacroInstantiations;
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 ~AsmParser() override;
185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
187 void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) override {
189 ExtensionDirectiveMap[Directive] = Handler;
192 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
193 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
197 /// @name MCAsmParser Interface
200 SourceMgr &getSourceManager() override { return SrcMgr; }
201 MCAsmLexer &getLexer() override { return Lexer; }
202 MCContext &getContext() override { return Ctx; }
203 MCStreamer &getStreamer() override { return Out; }
204 unsigned getAssemblerDialect() override {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 void setAssemblerDialect(unsigned i) override {
211 AssemblerDialect = i;
214 void Note(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Warning(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
218 bool Error(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
221 const AsmToken &Lex() override;
223 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
224 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
227 unsigned &NumOutputs, unsigned &NumInputs,
228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
229 SmallVectorImpl<std::string> &Constraints,
230 SmallVectorImpl<std::string> &Clobbers,
231 const MCInstrInfo *MII, const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI) override;
234 bool parseExpression(const MCExpr *&Res);
235 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
238 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
239 SMLoc &EndLoc) override;
240 bool parseAbsoluteExpression(int64_t &Res) override;
242 /// \brief Parse an identifier or string (as a quoted identifier)
243 /// and set \p Res to the identifier contents.
244 bool parseIdentifier(StringRef &Res) override;
245 void eatToEndOfStatement() override;
247 void checkForValidSection() override;
252 bool parseStatement(ParseStatementInfo &Info,
253 MCAsmParserSemaCallback *SI);
254 void eatToEndOfLine();
255 bool parseCppHashLineFilenameComment(SMLoc L);
257 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
258 ArrayRef<MCAsmMacroParameter> Parameters);
259 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
260 ArrayRef<MCAsmMacroParameter> Parameters,
261 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
264 /// \brief Are macros enabled in the parser?
265 bool areMacrosEnabled() {return MacrosEnabledFlag;}
267 /// \brief Control a flag in the parser that enables or disables macros.
268 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
270 /// \brief Lookup a previously defined macro.
271 /// \param Name Macro name.
272 /// \returns Pointer to macro. NULL if no such macro was defined.
273 const MCAsmMacro* lookupMacro(StringRef Name);
275 /// \brief Define a new macro with the given name and information.
276 void defineMacro(StringRef Name, MCAsmMacro Macro);
278 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
279 void undefineMacro(StringRef Name);
281 /// \brief Are we inside a macro instantiation?
282 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
284 /// \brief Handle entry to macro instantiation.
286 /// \param M The macro.
287 /// \param NameLoc Instantiation location.
288 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
290 /// \brief Handle exit from macro instantiation.
291 void handleMacroExit();
293 /// \brief Extract AsmTokens for a macro argument.
294 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
296 /// \brief Parse all macro arguments for a given macro.
297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
301 ArrayRef<SMRange> Ranges = None) const {
302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
309 /// \brief Process the specified file for the .incbin directive.
310 /// This returns true on failure.
311 bool processIncbinFile(const std::string &Filename);
313 /// \brief Reset the current lexer position to that given by \p Loc. The
314 /// current token is not set; clients should ensure Lex() is called
317 /// \param InBuffer If not 0, should be the known buffer id that contains the
319 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
324 StringRef parseStringToEndOfStatement() override;
326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
328 StringRef parseStringToComma();
330 bool parseAssignment(StringRef Name, bool allow_redef,
331 bool NoDeadStrip = false);
333 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
334 MCBinaryExpr::Opcode &Kind);
336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
342 // Generic (target and platform independent) directive parsing.
344 DK_NO_DIRECTIVE, // Placeholder
345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
347 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
348 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
349 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
350 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
351 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
352 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
353 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
354 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
355 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
356 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
357 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
358 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
359 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
360 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
361 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
362 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
363 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
364 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
365 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
366 DK_MACROS_ON, DK_MACROS_OFF,
367 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
368 DK_SLEB128, DK_ULEB128,
369 DK_ERR, DK_ERROR, DK_WARNING,
373 /// \brief Maps directive name --> DirectiveKind enum, for
374 /// directives parsed by this class.
375 StringMap<DirectiveKind> DirectiveKindMap;
377 // ".ascii", ".asciz", ".string"
378 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
379 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
380 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
381 bool parseDirectiveOctaValue(); // ".octa"
382 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
383 bool parseDirectiveFill(); // ".fill"
384 bool parseDirectiveZero(); // ".zero"
385 // ".set", ".equ", ".equiv"
386 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
387 bool parseDirectiveOrg(); // ".org"
388 // ".align{,32}", ".p2align{,w,l}"
389 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
391 // ".file", ".line", ".loc", ".stabs"
392 bool parseDirectiveFile(SMLoc DirectiveLoc);
393 bool parseDirectiveLine();
394 bool parseDirectiveLoc();
395 bool parseDirectiveStabs();
398 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIWindowSave();
400 bool parseDirectiveCFISections();
401 bool parseDirectiveCFIStartProc();
402 bool parseDirectiveCFIEndProc();
403 bool parseDirectiveCFIDefCfaOffset();
404 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIAdjustCfaOffset();
406 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
410 bool parseDirectiveCFIRememberState();
411 bool parseDirectiveCFIRestoreState();
412 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
413 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
414 bool parseDirectiveCFIEscape();
415 bool parseDirectiveCFISignalFrame();
416 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
419 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveExitMacro(StringRef Directive);
421 bool parseDirectiveEndMacro(StringRef Directive);
422 bool parseDirectiveMacro(SMLoc DirectiveLoc);
423 bool parseDirectiveMacrosOnOff(StringRef Directive);
425 // ".bundle_align_mode"
426 bool parseDirectiveBundleAlignMode();
428 bool parseDirectiveBundleLock();
430 bool parseDirectiveBundleUnlock();
433 bool parseDirectiveSpace(StringRef IDVal);
435 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
436 bool parseDirectiveLEB128(bool Signed);
438 /// \brief Parse a directive like ".globl" which
439 /// accepts a single symbol (which should be a label or an external).
440 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
442 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
444 bool parseDirectiveAbort(); // ".abort"
445 bool parseDirectiveInclude(); // ".include"
446 bool parseDirectiveIncbin(); // ".incbin"
448 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
449 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
450 // ".ifb" or ".ifnb", depending on ExpectBlank.
451 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
452 // ".ifc" or ".ifnc", depending on ExpectEqual.
453 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
454 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
455 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
456 // ".ifdef" or ".ifndef", depending on expect_defined
457 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
458 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
459 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
460 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
461 bool parseEscapedString(std::string &Data) override;
463 const MCExpr *applyModifierToExpr(const MCExpr *E,
464 MCSymbolRefExpr::VariantKind Variant);
466 // Macro-like directives
467 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
468 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
469 raw_svector_ostream &OS);
470 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
471 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
472 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
473 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
475 // "_emit" or "__emit"
476 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
480 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
483 bool parseDirectiveEnd(SMLoc DirectiveLoc);
485 // ".err" or ".error"
486 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
489 bool parseDirectiveWarning(SMLoc DirectiveLoc);
491 void initializeDirectiveKindMap();
497 extern MCAsmParserExtension *createDarwinAsmParser();
498 extern MCAsmParserExtension *createELFAsmParser();
499 extern MCAsmParserExtension *createCOFFAsmParser();
503 enum { DEFAULT_ADDRSPACE = 0 };
505 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
506 const MCAsmInfo &MAI)
507 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
508 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
509 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
510 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
511 // Save the old handler.
512 SavedDiagHandler = SrcMgr.getDiagHandler();
513 SavedDiagContext = SrcMgr.getDiagContext();
514 // Set our own handler which calls the saved handler.
515 SrcMgr.setDiagHandler(DiagHandler, this);
516 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
518 // Initialize the platform / file format parser.
519 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
520 case MCObjectFileInfo::IsCOFF:
521 PlatformParser.reset(createCOFFAsmParser());
523 case MCObjectFileInfo::IsMachO:
524 PlatformParser.reset(createDarwinAsmParser());
527 case MCObjectFileInfo::IsELF:
528 PlatformParser.reset(createELFAsmParser());
532 PlatformParser->Initialize(*this);
533 initializeDirectiveKindMap();
535 NumOfMacroInstantiations = 0;
538 AsmParser::~AsmParser() {
539 assert((HadError || ActiveMacros.empty()) &&
540 "Unexpected active macro instantiation!");
543 void AsmParser::printMacroInstantiations() {
544 // Print the active macro instantiation stack.
545 for (std::vector<MacroInstantiation *>::const_reverse_iterator
546 it = ActiveMacros.rbegin(),
547 ie = ActiveMacros.rend();
549 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
550 "while in macro instantiation");
553 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
555 printMacroInstantiations();
558 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559 if(getTargetParser().getTargetOptions().MCNoWarn)
561 if (getTargetParser().getTargetOptions().MCFatalWarnings)
562 return Error(L, Msg, Ranges);
563 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
564 printMacroInstantiations();
568 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
570 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
571 printMacroInstantiations();
575 bool AsmParser::enterIncludeFile(const std::string &Filename) {
576 std::string IncludedFile;
578 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
587 /// Process the specified .incbin file by searching for it in the include paths
588 /// then just emitting the byte contents of the file to the streamer. This
589 /// returns true on failure.
590 bool AsmParser::processIncbinFile(const std::string &Filename) {
591 std::string IncludedFile;
593 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
597 // Pick up the bytes from the file and emit them.
598 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
602 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
603 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
608 const AsmToken &AsmParser::Lex() {
609 const AsmToken *tok = &Lexer.Lex();
611 if (tok->is(AsmToken::Eof)) {
612 // If this is the end of an included file, pop the parent file off the
614 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
615 if (ParentIncludeLoc != SMLoc()) {
616 jumpToLoc(ParentIncludeLoc);
621 if (tok->is(AsmToken::Error))
622 Error(Lexer.getErrLoc(), Lexer.getErr());
627 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
628 // Create the initial section, if requested.
629 if (!NoInitialTextSection)
630 Out.InitSections(false);
636 AsmCond StartingCondState = TheCondState;
638 // If we are generating dwarf for assembly source files save the initial text
639 // section and generate a .file directive.
640 if (getContext().getGenDwarfForAssembly()) {
641 MCSection *Sec = getStreamer().getCurrentSection().first;
642 if (!Sec->getBeginSymbol()) {
643 MCSymbol *SectionStartSym = getContext().createTempSymbol();
644 getStreamer().EmitLabel(SectionStartSym);
645 Sec->setBeginSymbol(SectionStartSym);
647 bool InsertResult = getContext().addGenDwarfSection(Sec);
648 assert(InsertResult && ".text section should not have debug info yet");
650 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
651 0, StringRef(), getContext().getMainFileName()));
654 // While we have input, parse each statement.
655 while (Lexer.isNot(AsmToken::Eof)) {
656 ParseStatementInfo Info;
657 if (!parseStatement(Info, nullptr))
660 // We had an error, validate that one was emitted and recover by skipping to
662 assert(HadError && "Parse statement returned an error, but none emitted!");
663 eatToEndOfStatement();
666 if (TheCondState.TheCond != StartingCondState.TheCond ||
667 TheCondState.Ignore != StartingCondState.Ignore)
668 return TokError("unmatched .ifs or .elses");
670 // Check to see there are no empty DwarfFile slots.
671 const auto &LineTables = getContext().getMCDwarfLineTables();
672 if (!LineTables.empty()) {
674 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
675 if (File.Name.empty() && Index != 0)
676 TokError("unassigned file number: " + Twine(Index) +
677 " for .file directives");
682 // Check to see that all assembler local symbols were actually defined.
683 // Targets that don't do subsections via symbols may not want this, though,
684 // so conservatively exclude them. Only do this if we're finalizing, though,
685 // as otherwise we won't necessarilly have seen everything yet.
686 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
687 for (const auto &TableEntry : getContext().getSymbols()) {
688 MCSymbol *Sym = TableEntry.getValue();
689 // Variable symbols may not be marked as defined, so check those
690 // explicitly. If we know it's a variable, we have a definition for
691 // the purposes of this check.
692 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
693 // FIXME: We would really like to refer back to where the symbol was
694 // first referenced for a source location. We need to add something
695 // to track that. Currently, we just point to the end of the file.
696 return Error(getLexer().getLoc(), "assembler local symbol '" +
697 Sym->getName() + "' not defined");
701 // Finalize the output stream if there are no errors and if the client wants
703 if (!HadError && !NoFinalize)
709 void AsmParser::checkForValidSection() {
710 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
711 TokError("expected section directive before assembly directive");
712 Out.InitSections(false);
716 /// \brief Throw away the rest of the line for testing purposes.
717 void AsmParser::eatToEndOfStatement() {
718 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
722 if (Lexer.is(AsmToken::EndOfStatement))
726 StringRef AsmParser::parseStringToEndOfStatement() {
727 const char *Start = getTok().getLoc().getPointer();
729 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
732 const char *End = getTok().getLoc().getPointer();
733 return StringRef(Start, End - Start);
736 StringRef AsmParser::parseStringToComma() {
737 const char *Start = getTok().getLoc().getPointer();
739 while (Lexer.isNot(AsmToken::EndOfStatement) &&
740 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
743 const char *End = getTok().getLoc().getPointer();
744 return StringRef(Start, End - Start);
747 /// \brief Parse a paren expression and return it.
748 /// NOTE: This assumes the leading '(' has already been consumed.
750 /// parenexpr ::= expr)
752 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
753 if (parseExpression(Res))
755 if (Lexer.isNot(AsmToken::RParen))
756 return TokError("expected ')' in parentheses expression");
757 EndLoc = Lexer.getTok().getEndLoc();
762 /// \brief Parse a bracket expression and return it.
763 /// NOTE: This assumes the leading '[' has already been consumed.
765 /// bracketexpr ::= expr]
767 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
768 if (parseExpression(Res))
770 if (Lexer.isNot(AsmToken::RBrac))
771 return TokError("expected ']' in brackets expression");
772 EndLoc = Lexer.getTok().getEndLoc();
777 /// \brief Parse a primary expression and return it.
778 /// primaryexpr ::= (parenexpr
779 /// primaryexpr ::= symbol
780 /// primaryexpr ::= number
781 /// primaryexpr ::= '.'
782 /// primaryexpr ::= ~,+,- primaryexpr
783 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
784 SMLoc FirstTokenLoc = getLexer().getLoc();
785 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
786 switch (FirstTokenKind) {
788 return TokError("unknown token in expression");
789 // If we have an error assume that we've already handled it.
790 case AsmToken::Error:
792 case AsmToken::Exclaim:
793 Lex(); // Eat the operator.
794 if (parsePrimaryExpr(Res, EndLoc))
796 Res = MCUnaryExpr::createLNot(Res, getContext());
798 case AsmToken::Dollar:
800 case AsmToken::String:
801 case AsmToken::Identifier: {
802 StringRef Identifier;
803 if (parseIdentifier(Identifier)) {
804 if (FirstTokenKind == AsmToken::Dollar) {
805 if (Lexer.getMAI().getDollarIsPC()) {
806 // This is a '$' reference, which references the current PC. Emit a
807 // temporary label to the streamer and refer to it.
808 MCSymbol *Sym = Ctx.createTempSymbol();
810 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
812 EndLoc = FirstTokenLoc;
815 return Error(FirstTokenLoc, "invalid token in expression");
818 // Parse symbol variant
819 std::pair<StringRef, StringRef> Split;
820 if (!MAI.useParensForSymbolVariant()) {
821 if (FirstTokenKind == AsmToken::String) {
822 if (Lexer.is(AsmToken::At)) {
823 Lexer.Lex(); // eat @
824 SMLoc AtLoc = getLexer().getLoc();
826 if (parseIdentifier(VName))
827 return Error(AtLoc, "expected symbol variant after '@'");
829 Split = std::make_pair(Identifier, VName);
832 Split = Identifier.split('@');
834 } else if (Lexer.is(AsmToken::LParen)) {
835 Lexer.Lex(); // eat (
837 parseIdentifier(VName);
838 if (Lexer.isNot(AsmToken::RParen)) {
839 return Error(Lexer.getTok().getLoc(),
840 "unexpected token in variant, expected ')'");
842 Lexer.Lex(); // eat )
843 Split = std::make_pair(Identifier, VName);
846 EndLoc = SMLoc::getFromPointer(Identifier.end());
848 // This is a symbol reference.
849 StringRef SymbolName = Identifier;
850 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
852 // Lookup the symbol variant if used.
853 if (Split.second.size()) {
854 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
855 if (Variant != MCSymbolRefExpr::VK_Invalid) {
856 SymbolName = Split.first;
857 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
858 Variant = MCSymbolRefExpr::VK_None;
860 return Error(SMLoc::getFromPointer(Split.second.begin()),
861 "invalid variant '" + Split.second + "'");
865 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
867 // If this is an absolute variable reference, substitute it now to preserve
868 // semantics in the face of reassignment.
869 if (Sym->isVariable() &&
870 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
872 return Error(EndLoc, "unexpected modifier on variable reference");
874 Res = Sym->getVariableValue(/*SetUsed*/ false);
878 // Otherwise create a symbol ref.
879 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
882 case AsmToken::BigNum:
883 return TokError("literal value out of range for directive");
884 case AsmToken::Integer: {
885 SMLoc Loc = getTok().getLoc();
886 int64_t IntVal = getTok().getIntVal();
887 Res = MCConstantExpr::create(IntVal, getContext());
888 EndLoc = Lexer.getTok().getEndLoc();
890 // Look for 'b' or 'f' following an Integer as a directional label
891 if (Lexer.getKind() == AsmToken::Identifier) {
892 StringRef IDVal = getTok().getString();
893 // Lookup the symbol variant if used.
894 std::pair<StringRef, StringRef> Split = IDVal.split('@');
895 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
896 if (Split.first.size() != IDVal.size()) {
897 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
898 if (Variant == MCSymbolRefExpr::VK_Invalid)
899 return TokError("invalid variant '" + Split.second + "'");
902 if (IDVal == "f" || IDVal == "b") {
904 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
905 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
906 if (IDVal == "b" && Sym->isUndefined())
907 return Error(Loc, "invalid reference to undefined symbol");
908 EndLoc = Lexer.getTok().getEndLoc();
909 Lex(); // Eat identifier.
914 case AsmToken::Real: {
915 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
916 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
917 Res = MCConstantExpr::create(IntVal, getContext());
918 EndLoc = Lexer.getTok().getEndLoc();
922 case AsmToken::Dot: {
923 // This is a '.' reference, which references the current PC. Emit a
924 // temporary label to the streamer and refer to it.
925 MCSymbol *Sym = Ctx.createTempSymbol();
927 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
928 EndLoc = Lexer.getTok().getEndLoc();
929 Lex(); // Eat identifier.
932 case AsmToken::LParen:
933 Lex(); // Eat the '('.
934 return parseParenExpr(Res, EndLoc);
935 case AsmToken::LBrac:
936 if (!PlatformParser->HasBracketExpressions())
937 return TokError("brackets expression not supported on this target");
938 Lex(); // Eat the '['.
939 return parseBracketExpr(Res, EndLoc);
940 case AsmToken::Minus:
941 Lex(); // Eat the operator.
942 if (parsePrimaryExpr(Res, EndLoc))
944 Res = MCUnaryExpr::createMinus(Res, getContext());
947 Lex(); // Eat the operator.
948 if (parsePrimaryExpr(Res, EndLoc))
950 Res = MCUnaryExpr::createPlus(Res, getContext());
952 case AsmToken::Tilde:
953 Lex(); // Eat the operator.
954 if (parsePrimaryExpr(Res, EndLoc))
956 Res = MCUnaryExpr::createNot(Res, getContext());
961 bool AsmParser::parseExpression(const MCExpr *&Res) {
963 return parseExpression(Res, EndLoc);
967 AsmParser::applyModifierToExpr(const MCExpr *E,
968 MCSymbolRefExpr::VariantKind Variant) {
969 // Ask the target implementation about this expression first.
970 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
973 // Recurse over the given expression, rebuilding it to apply the given variant
974 // if there is exactly one symbol.
975 switch (E->getKind()) {
977 case MCExpr::Constant:
980 case MCExpr::SymbolRef: {
981 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
983 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
984 TokError("invalid variant on expression '" + getTok().getIdentifier() +
985 "' (already modified)");
989 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
992 case MCExpr::Unary: {
993 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
994 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
997 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1000 case MCExpr::Binary: {
1001 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1002 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1003 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1013 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1017 llvm_unreachable("Invalid expression kind!");
1020 /// \brief Parse an expression and return it.
1022 /// expr ::= expr &&,|| expr -> lowest.
1023 /// expr ::= expr |,^,&,! expr
1024 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1025 /// expr ::= expr <<,>> expr
1026 /// expr ::= expr +,- expr
1027 /// expr ::= expr *,/,% expr -> highest.
1028 /// expr ::= primaryexpr
1030 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1031 // Parse the expression.
1033 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1036 // As a special case, we support 'a op b @ modifier' by rewriting the
1037 // expression to include the modifier. This is inefficient, but in general we
1038 // expect users to use 'a@modifier op b'.
1039 if (Lexer.getKind() == AsmToken::At) {
1042 if (Lexer.isNot(AsmToken::Identifier))
1043 return TokError("unexpected symbol modifier following '@'");
1045 MCSymbolRefExpr::VariantKind Variant =
1046 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1047 if (Variant == MCSymbolRefExpr::VK_Invalid)
1048 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1050 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1052 return TokError("invalid modifier '" + getTok().getIdentifier() +
1053 "' (no symbols present)");
1060 // Try to constant fold it up front, if possible.
1062 if (Res->evaluateAsAbsolute(Value))
1063 Res = MCConstantExpr::create(Value, getContext());
1068 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1070 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1073 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1075 if (parseParenExpr(Res, EndLoc))
1078 for (; ParenDepth > 0; --ParenDepth) {
1079 if (parseBinOpRHS(1, Res, EndLoc))
1082 // We don't Lex() the last RParen.
1083 // This is the same behavior as parseParenExpression().
1084 if (ParenDepth - 1 > 0) {
1085 if (Lexer.isNot(AsmToken::RParen))
1086 return TokError("expected ')' in parentheses expression");
1087 EndLoc = Lexer.getTok().getEndLoc();
1094 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1097 SMLoc StartLoc = Lexer.getLoc();
1098 if (parseExpression(Expr))
1101 if (!Expr->evaluateAsAbsolute(Res))
1102 return Error(StartLoc, "expected absolute expression");
1107 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1108 MCBinaryExpr::Opcode &Kind,
1109 bool ShouldUseLogicalShr) {
1112 return 0; // not a binop.
1114 // Lowest Precedence: &&, ||
1115 case AsmToken::AmpAmp:
1116 Kind = MCBinaryExpr::LAnd;
1118 case AsmToken::PipePipe:
1119 Kind = MCBinaryExpr::LOr;
1122 // Low Precedence: |, &, ^
1124 // FIXME: gas seems to support '!' as an infix operator?
1125 case AsmToken::Pipe:
1126 Kind = MCBinaryExpr::Or;
1128 case AsmToken::Caret:
1129 Kind = MCBinaryExpr::Xor;
1132 Kind = MCBinaryExpr::And;
1135 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1136 case AsmToken::EqualEqual:
1137 Kind = MCBinaryExpr::EQ;
1139 case AsmToken::ExclaimEqual:
1140 case AsmToken::LessGreater:
1141 Kind = MCBinaryExpr::NE;
1143 case AsmToken::Less:
1144 Kind = MCBinaryExpr::LT;
1146 case AsmToken::LessEqual:
1147 Kind = MCBinaryExpr::LTE;
1149 case AsmToken::Greater:
1150 Kind = MCBinaryExpr::GT;
1152 case AsmToken::GreaterEqual:
1153 Kind = MCBinaryExpr::GTE;
1156 // Intermediate Precedence: <<, >>
1157 case AsmToken::LessLess:
1158 Kind = MCBinaryExpr::Shl;
1160 case AsmToken::GreaterGreater:
1161 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1164 // High Intermediate Precedence: +, -
1165 case AsmToken::Plus:
1166 Kind = MCBinaryExpr::Add;
1168 case AsmToken::Minus:
1169 Kind = MCBinaryExpr::Sub;
1172 // Highest Precedence: *, /, %
1173 case AsmToken::Star:
1174 Kind = MCBinaryExpr::Mul;
1176 case AsmToken::Slash:
1177 Kind = MCBinaryExpr::Div;
1179 case AsmToken::Percent:
1180 Kind = MCBinaryExpr::Mod;
1185 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1186 MCBinaryExpr::Opcode &Kind,
1187 bool ShouldUseLogicalShr) {
1190 return 0; // not a binop.
1192 // Lowest Precedence: &&, ||
1193 case AsmToken::AmpAmp:
1194 Kind = MCBinaryExpr::LAnd;
1196 case AsmToken::PipePipe:
1197 Kind = MCBinaryExpr::LOr;
1200 // Low Precedence: ==, !=, <>, <, <=, >, >=
1201 case AsmToken::EqualEqual:
1202 Kind = MCBinaryExpr::EQ;
1204 case AsmToken::ExclaimEqual:
1205 case AsmToken::LessGreater:
1206 Kind = MCBinaryExpr::NE;
1208 case AsmToken::Less:
1209 Kind = MCBinaryExpr::LT;
1211 case AsmToken::LessEqual:
1212 Kind = MCBinaryExpr::LTE;
1214 case AsmToken::Greater:
1215 Kind = MCBinaryExpr::GT;
1217 case AsmToken::GreaterEqual:
1218 Kind = MCBinaryExpr::GTE;
1221 // Low Intermediate Precedence: +, -
1222 case AsmToken::Plus:
1223 Kind = MCBinaryExpr::Add;
1225 case AsmToken::Minus:
1226 Kind = MCBinaryExpr::Sub;
1229 // High Intermediate Precedence: |, &, ^
1231 // FIXME: gas seems to support '!' as an infix operator?
1232 case AsmToken::Pipe:
1233 Kind = MCBinaryExpr::Or;
1235 case AsmToken::Caret:
1236 Kind = MCBinaryExpr::Xor;
1239 Kind = MCBinaryExpr::And;
1242 // Highest Precedence: *, /, %, <<, >>
1243 case AsmToken::Star:
1244 Kind = MCBinaryExpr::Mul;
1246 case AsmToken::Slash:
1247 Kind = MCBinaryExpr::Div;
1249 case AsmToken::Percent:
1250 Kind = MCBinaryExpr::Mod;
1252 case AsmToken::LessLess:
1253 Kind = MCBinaryExpr::Shl;
1255 case AsmToken::GreaterGreater:
1256 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1261 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1262 MCBinaryExpr::Opcode &Kind) {
1263 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1264 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1265 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1268 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1269 /// Res contains the LHS of the expression on input.
1270 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1273 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1274 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1276 // If the next token is lower precedence than we are allowed to eat, return
1277 // successfully with what we ate already.
1278 if (TokPrec < Precedence)
1283 // Eat the next primary expression.
1285 if (parsePrimaryExpr(RHS, EndLoc))
1288 // If BinOp binds less tightly with RHS than the operator after RHS, let
1289 // the pending operator take RHS as its LHS.
1290 MCBinaryExpr::Opcode Dummy;
1291 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1292 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1295 // Merge LHS and RHS according to operator.
1296 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1301 /// ::= EndOfStatement
1302 /// ::= Label* Directive ...Operands... EndOfStatement
1303 /// ::= Label* Identifier OperandList* EndOfStatement
1304 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1305 MCAsmParserSemaCallback *SI) {
1306 if (Lexer.is(AsmToken::EndOfStatement)) {
1312 // Statements always start with an identifier or are a full line comment.
1313 AsmToken ID = getTok();
1314 SMLoc IDLoc = ID.getLoc();
1316 int64_t LocalLabelVal = -1;
1317 // A full line comment is a '#' as the first token.
1318 if (Lexer.is(AsmToken::Hash))
1319 return parseCppHashLineFilenameComment(IDLoc);
1321 // Allow an integer followed by a ':' as a directional local label.
1322 if (Lexer.is(AsmToken::Integer)) {
1323 LocalLabelVal = getTok().getIntVal();
1324 if (LocalLabelVal < 0) {
1325 if (!TheCondState.Ignore)
1326 return TokError("unexpected token at start of statement");
1329 IDVal = getTok().getString();
1330 Lex(); // Consume the integer token to be used as an identifier token.
1331 if (Lexer.getKind() != AsmToken::Colon) {
1332 if (!TheCondState.Ignore)
1333 return TokError("unexpected token at start of statement");
1336 } else if (Lexer.is(AsmToken::Dot)) {
1337 // Treat '.' as a valid identifier in this context.
1340 } else if (Lexer.is(AsmToken::LCurly)) {
1341 // Treat '{' as a valid identifier in this context.
1345 } else if (Lexer.is(AsmToken::RCurly)) {
1346 // Treat '}' as a valid identifier in this context.
1349 } else if (parseIdentifier(IDVal)) {
1350 if (!TheCondState.Ignore)
1351 return TokError("unexpected token at start of statement");
1355 // Handle conditional assembly here before checking for skipping. We
1356 // have to do this so that .endif isn't skipped in a ".if 0" block for
1358 StringMap<DirectiveKind>::const_iterator DirKindIt =
1359 DirectiveKindMap.find(IDVal);
1360 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1362 : DirKindIt->getValue();
1373 return parseDirectiveIf(IDLoc, DirKind);
1375 return parseDirectiveIfb(IDLoc, true);
1377 return parseDirectiveIfb(IDLoc, false);
1379 return parseDirectiveIfc(IDLoc, true);
1381 return parseDirectiveIfeqs(IDLoc, true);
1383 return parseDirectiveIfc(IDLoc, false);
1385 return parseDirectiveIfeqs(IDLoc, false);
1387 return parseDirectiveIfdef(IDLoc, true);
1390 return parseDirectiveIfdef(IDLoc, false);
1392 return parseDirectiveElseIf(IDLoc);
1394 return parseDirectiveElse(IDLoc);
1396 return parseDirectiveEndIf(IDLoc);
1399 // Ignore the statement if in the middle of inactive conditional
1401 if (TheCondState.Ignore) {
1402 eatToEndOfStatement();
1406 // FIXME: Recurse on local labels?
1408 // See what kind of statement we have.
1409 switch (Lexer.getKind()) {
1410 case AsmToken::Colon: {
1411 if (!getTargetParser().isLabel(ID))
1413 checkForValidSection();
1415 // identifier ':' -> Label.
1418 // Diagnose attempt to use '.' as a label.
1420 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1422 // Diagnose attempt to use a variable as a label.
1424 // FIXME: Diagnostics. Note the location of the definition as a label.
1425 // FIXME: This doesn't diagnose assignment to a symbol which has been
1426 // implicitly marked as external.
1428 if (LocalLabelVal == -1) {
1429 if (ParsingInlineAsm && SI) {
1430 StringRef RewrittenLabel =
1431 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1432 assert(RewrittenLabel.size() &&
1433 "We should have an internal name here.");
1434 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1436 IDVal = RewrittenLabel;
1438 Sym = getContext().getOrCreateSymbol(IDVal);
1440 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1442 Sym->redefineIfPossible();
1444 if (!Sym->isUndefined() || Sym->isVariable())
1445 return Error(IDLoc, "invalid symbol redefinition");
1448 if (!ParsingInlineAsm)
1451 // If we are generating dwarf for assembly source files then gather the
1452 // info to make a dwarf label entry for this label if needed.
1453 if (getContext().getGenDwarfForAssembly())
1454 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1457 getTargetParser().onLabelParsed(Sym);
1459 // Consume any end of statement token, if present, to avoid spurious
1460 // AddBlankLine calls().
1461 if (Lexer.is(AsmToken::EndOfStatement)) {
1463 if (Lexer.is(AsmToken::Eof))
1470 case AsmToken::Equal:
1471 if (!getTargetParser().equalIsAsmAssignment())
1473 // identifier '=' ... -> assignment statement
1476 return parseAssignment(IDVal, true);
1478 default: // Normal instruction or directive.
1482 // If macros are enabled, check to see if this is a macro instantiation.
1483 if (areMacrosEnabled())
1484 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1485 return handleMacroEntry(M, IDLoc);
1488 // Otherwise, we have a normal instruction or directive.
1490 // Directives start with "."
1491 if (IDVal[0] == '.' && IDVal != ".") {
1492 // There are several entities interested in parsing directives:
1494 // 1. The target-specific assembly parser. Some directives are target
1495 // specific or may potentially behave differently on certain targets.
1496 // 2. Asm parser extensions. For example, platform-specific parsers
1497 // (like the ELF parser) register themselves as extensions.
1498 // 3. The generic directive parser implemented by this class. These are
1499 // all the directives that behave in a target and platform independent
1500 // manner, or at least have a default behavior that's shared between
1501 // all targets and platforms.
1503 // First query the target-specific parser. It will return 'true' if it
1504 // isn't interested in this directive.
1505 if (!getTargetParser().ParseDirective(ID))
1508 // Next, check the extension directive map to see if any extension has
1509 // registered itself to parse this directive.
1510 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1511 ExtensionDirectiveMap.lookup(IDVal);
1513 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1515 // Finally, if no one else is interested in this directive, it must be
1516 // generic and familiar to this class.
1522 return parseDirectiveSet(IDVal, true);
1524 return parseDirectiveSet(IDVal, false);
1526 return parseDirectiveAscii(IDVal, false);
1529 return parseDirectiveAscii(IDVal, true);
1531 return parseDirectiveValue(1);
1535 return parseDirectiveValue(2);
1539 return parseDirectiveValue(4);
1542 return parseDirectiveValue(8);
1544 return parseDirectiveOctaValue();
1547 return parseDirectiveRealValue(APFloat::IEEEsingle);
1549 return parseDirectiveRealValue(APFloat::IEEEdouble);
1551 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1552 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1555 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1556 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1559 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1561 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1563 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1565 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1567 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1569 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1571 return parseDirectiveOrg();
1573 return parseDirectiveFill();
1575 return parseDirectiveZero();
1577 eatToEndOfStatement(); // .extern is the default, ignore it.
1581 return parseDirectiveSymbolAttribute(MCSA_Global);
1582 case DK_LAZY_REFERENCE:
1583 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1584 case DK_NO_DEAD_STRIP:
1585 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1586 case DK_SYMBOL_RESOLVER:
1587 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1588 case DK_PRIVATE_EXTERN:
1589 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1591 return parseDirectiveSymbolAttribute(MCSA_Reference);
1592 case DK_WEAK_DEFINITION:
1593 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1594 case DK_WEAK_REFERENCE:
1595 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1596 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1597 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1600 return parseDirectiveComm(/*IsLocal=*/false);
1602 return parseDirectiveComm(/*IsLocal=*/true);
1604 return parseDirectiveAbort();
1606 return parseDirectiveInclude();
1608 return parseDirectiveIncbin();
1611 return TokError(Twine(IDVal) + " not supported yet");
1613 return parseDirectiveRept(IDLoc, IDVal);
1615 return parseDirectiveIrp(IDLoc);
1617 return parseDirectiveIrpc(IDLoc);
1619 return parseDirectiveEndr(IDLoc);
1620 case DK_BUNDLE_ALIGN_MODE:
1621 return parseDirectiveBundleAlignMode();
1622 case DK_BUNDLE_LOCK:
1623 return parseDirectiveBundleLock();
1624 case DK_BUNDLE_UNLOCK:
1625 return parseDirectiveBundleUnlock();
1627 return parseDirectiveLEB128(true);
1629 return parseDirectiveLEB128(false);
1632 return parseDirectiveSpace(IDVal);
1634 return parseDirectiveFile(IDLoc);
1636 return parseDirectiveLine();
1638 return parseDirectiveLoc();
1640 return parseDirectiveStabs();
1641 case DK_CFI_SECTIONS:
1642 return parseDirectiveCFISections();
1643 case DK_CFI_STARTPROC:
1644 return parseDirectiveCFIStartProc();
1645 case DK_CFI_ENDPROC:
1646 return parseDirectiveCFIEndProc();
1647 case DK_CFI_DEF_CFA:
1648 return parseDirectiveCFIDefCfa(IDLoc);
1649 case DK_CFI_DEF_CFA_OFFSET:
1650 return parseDirectiveCFIDefCfaOffset();
1651 case DK_CFI_ADJUST_CFA_OFFSET:
1652 return parseDirectiveCFIAdjustCfaOffset();
1653 case DK_CFI_DEF_CFA_REGISTER:
1654 return parseDirectiveCFIDefCfaRegister(IDLoc);
1656 return parseDirectiveCFIOffset(IDLoc);
1657 case DK_CFI_REL_OFFSET:
1658 return parseDirectiveCFIRelOffset(IDLoc);
1659 case DK_CFI_PERSONALITY:
1660 return parseDirectiveCFIPersonalityOrLsda(true);
1662 return parseDirectiveCFIPersonalityOrLsda(false);
1663 case DK_CFI_REMEMBER_STATE:
1664 return parseDirectiveCFIRememberState();
1665 case DK_CFI_RESTORE_STATE:
1666 return parseDirectiveCFIRestoreState();
1667 case DK_CFI_SAME_VALUE:
1668 return parseDirectiveCFISameValue(IDLoc);
1669 case DK_CFI_RESTORE:
1670 return parseDirectiveCFIRestore(IDLoc);
1672 return parseDirectiveCFIEscape();
1673 case DK_CFI_SIGNAL_FRAME:
1674 return parseDirectiveCFISignalFrame();
1675 case DK_CFI_UNDEFINED:
1676 return parseDirectiveCFIUndefined(IDLoc);
1677 case DK_CFI_REGISTER:
1678 return parseDirectiveCFIRegister(IDLoc);
1679 case DK_CFI_WINDOW_SAVE:
1680 return parseDirectiveCFIWindowSave();
1683 return parseDirectiveMacrosOnOff(IDVal);
1685 return parseDirectiveMacro(IDLoc);
1687 return parseDirectiveExitMacro(IDVal);
1690 return parseDirectiveEndMacro(IDVal);
1692 return parseDirectivePurgeMacro(IDLoc);
1694 return parseDirectiveEnd(IDLoc);
1696 return parseDirectiveError(IDLoc, false);
1698 return parseDirectiveError(IDLoc, true);
1700 return parseDirectiveWarning(IDLoc);
1702 return parseDirectiveReloc(IDLoc);
1705 return Error(IDLoc, "unknown directive");
1708 // __asm _emit or __asm __emit
1709 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1710 IDVal == "_EMIT" || IDVal == "__EMIT"))
1711 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1714 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1715 return parseDirectiveMSAlign(IDLoc, Info);
1717 checkForValidSection();
1719 // Canonicalize the opcode to lower case.
1720 std::string OpcodeStr = IDVal.lower();
1721 ParseInstructionInfo IInfo(Info.AsmRewrites);
1722 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1723 Info.ParsedOperands);
1724 Info.ParseError = HadError;
1726 // Dump the parsed representation, if requested.
1727 if (getShowParsedOperands()) {
1728 SmallString<256> Str;
1729 raw_svector_ostream OS(Str);
1730 OS << "parsed instruction: [";
1731 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1734 Info.ParsedOperands[i]->print(OS);
1738 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1741 // If we are generating dwarf for the current section then generate a .loc
1742 // directive for the instruction.
1743 if (!HadError && getContext().getGenDwarfForAssembly() &&
1744 getContext().getGenDwarfSectionSyms().count(
1745 getStreamer().getCurrentSection().first)) {
1747 if (ActiveMacros.empty())
1748 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1750 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1751 ActiveMacros.front()->ExitBuffer);
1753 // If we previously parsed a cpp hash file line comment then make sure the
1754 // current Dwarf File is for the CppHashFilename if not then emit the
1755 // Dwarf File table for it and adjust the line number for the .loc.
1756 if (CppHashFilename.size()) {
1757 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1758 0, StringRef(), CppHashFilename);
1759 getContext().setGenDwarfFileNumber(FileNumber);
1761 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1762 // cache with the different Loc from the call above we save the last
1763 // info we queried here with SrcMgr.FindLineNumber().
1764 unsigned CppHashLocLineNo;
1765 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1766 CppHashLocLineNo = LastQueryLine;
1768 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1769 LastQueryLine = CppHashLocLineNo;
1770 LastQueryIDLoc = CppHashLoc;
1771 LastQueryBuffer = CppHashBuf;
1773 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1776 getStreamer().EmitDwarfLocDirective(
1777 getContext().getGenDwarfFileNumber(), Line, 0,
1778 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1782 // If parsing succeeded, match the instruction.
1785 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1786 Info.ParsedOperands, Out,
1787 ErrorInfo, ParsingInlineAsm);
1790 // Don't skip the rest of the line, the instruction parser is responsible for
1795 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1796 /// since they may not be able to be tokenized to get to the end of line token.
1797 void AsmParser::eatToEndOfLine() {
1798 if (!Lexer.is(AsmToken::EndOfStatement))
1799 Lexer.LexUntilEndOfLine();
1804 /// parseCppHashLineFilenameComment as this:
1805 /// ::= # number "filename"
1806 /// or just as a full line comment if it doesn't have a number and a string.
1807 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1808 Lex(); // Eat the hash token.
1810 if (getLexer().isNot(AsmToken::Integer)) {
1811 // Consume the line since in cases it is not a well-formed line directive,
1812 // as if were simply a full line comment.
1817 int64_t LineNumber = getTok().getIntVal();
1820 if (getLexer().isNot(AsmToken::String)) {
1825 StringRef Filename = getTok().getString();
1826 // Get rid of the enclosing quotes.
1827 Filename = Filename.substr(1, Filename.size() - 2);
1829 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1831 CppHashFilename = Filename;
1832 CppHashLineNumber = LineNumber;
1833 CppHashBuf = CurBuffer;
1835 // Ignore any trailing characters, they're just comment.
1840 /// \brief will use the last parsed cpp hash line filename comment
1841 /// for the Filename and LineNo if any in the diagnostic.
1842 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1843 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1844 raw_ostream &OS = errs();
1846 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1847 SMLoc DiagLoc = Diag.getLoc();
1848 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1849 unsigned CppHashBuf =
1850 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1852 // Like SourceMgr::printMessage() we need to print the include stack if any
1853 // before printing the message.
1854 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1855 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1856 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1857 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1858 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1861 // If we have not parsed a cpp hash line filename comment or the source
1862 // manager changed or buffer changed (like in a nested include) then just
1863 // print the normal diagnostic using its Filename and LineNo.
1864 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1865 DiagBuf != CppHashBuf) {
1866 if (Parser->SavedDiagHandler)
1867 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1869 Diag.print(nullptr, OS);
1873 // Use the CppHashFilename and calculate a line number based on the
1874 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1876 const std::string &Filename = Parser->CppHashFilename;
1878 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1879 int CppHashLocLineNo =
1880 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1882 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1884 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1885 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1886 Diag.getLineContents(), Diag.getRanges());
1888 if (Parser->SavedDiagHandler)
1889 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1891 NewDiag.print(nullptr, OS);
1894 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1895 // difference being that that function accepts '@' as part of identifiers and
1896 // we can't do that. AsmLexer.cpp should probably be changed to handle
1897 // '@' as a special case when needed.
1898 static bool isIdentifierChar(char c) {
1899 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1903 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1904 ArrayRef<MCAsmMacroParameter> Parameters,
1905 ArrayRef<MCAsmMacroArgument> A,
1906 bool EnableAtPseudoVariable, SMLoc L) {
1907 unsigned NParameters = Parameters.size();
1908 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1909 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1910 return Error(L, "Wrong number of arguments");
1912 // A macro without parameters is handled differently on Darwin:
1913 // gas accepts no arguments and does no substitutions
1914 while (!Body.empty()) {
1915 // Scan for the next substitution.
1916 std::size_t End = Body.size(), Pos = 0;
1917 for (; Pos != End; ++Pos) {
1918 // Check for a substitution or escape.
1919 if (IsDarwin && !NParameters) {
1920 // This macro has no parameters, look for $0, $1, etc.
1921 if (Body[Pos] != '$' || Pos + 1 == End)
1924 char Next = Body[Pos + 1];
1925 if (Next == '$' || Next == 'n' ||
1926 isdigit(static_cast<unsigned char>(Next)))
1929 // This macro has parameters, look for \foo, \bar, etc.
1930 if (Body[Pos] == '\\' && Pos + 1 != End)
1936 OS << Body.slice(0, Pos);
1938 // Check if we reached the end.
1942 if (IsDarwin && !NParameters) {
1943 switch (Body[Pos + 1]) {
1949 // $n => number of arguments
1954 // $[0-9] => argument
1956 // Missing arguments are ignored.
1957 unsigned Index = Body[Pos + 1] - '0';
1958 if (Index >= A.size())
1961 // Otherwise substitute with the token values, with spaces eliminated.
1962 for (const AsmToken &Token : A[Index])
1963 OS << Token.getString();
1969 unsigned I = Pos + 1;
1971 // Check for the \@ pseudo-variable.
1972 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1975 while (isIdentifierChar(Body[I]) && I + 1 != End)
1978 const char *Begin = Body.data() + Pos + 1;
1979 StringRef Argument(Begin, I - (Pos + 1));
1982 if (Argument == "@") {
1983 OS << NumOfMacroInstantiations;
1986 for (; Index < NParameters; ++Index)
1987 if (Parameters[Index].Name == Argument)
1990 if (Index == NParameters) {
1991 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1994 OS << '\\' << Argument;
1998 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1999 for (const AsmToken &Token : A[Index])
2000 // We expect no quotes around the string's contents when
2001 // parsing for varargs.
2002 if (Token.getKind() != AsmToken::String || VarargParameter)
2003 OS << Token.getString();
2005 OS << Token.getStringContents();
2007 Pos += 1 + Argument.size();
2011 // Update the scan point.
2012 Body = Body.substr(Pos);
2018 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2019 size_t CondStackDepth)
2020 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2021 CondStackDepth(CondStackDepth) {}
2023 static bool isOperator(AsmToken::TokenKind kind) {
2027 case AsmToken::Plus:
2028 case AsmToken::Minus:
2029 case AsmToken::Tilde:
2030 case AsmToken::Slash:
2031 case AsmToken::Star:
2033 case AsmToken::Equal:
2034 case AsmToken::EqualEqual:
2035 case AsmToken::Pipe:
2036 case AsmToken::PipePipe:
2037 case AsmToken::Caret:
2039 case AsmToken::AmpAmp:
2040 case AsmToken::Exclaim:
2041 case AsmToken::ExclaimEqual:
2042 case AsmToken::Percent:
2043 case AsmToken::Less:
2044 case AsmToken::LessEqual:
2045 case AsmToken::LessLess:
2046 case AsmToken::LessGreater:
2047 case AsmToken::Greater:
2048 case AsmToken::GreaterEqual:
2049 case AsmToken::GreaterGreater:
2055 class AsmLexerSkipSpaceRAII {
2057 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2058 Lexer.setSkipSpace(SkipSpace);
2061 ~AsmLexerSkipSpaceRAII() {
2062 Lexer.setSkipSpace(true);
2070 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2073 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2074 StringRef Str = parseStringToEndOfStatement();
2075 MA.emplace_back(AsmToken::String, Str);
2080 unsigned ParenLevel = 0;
2081 unsigned AddTokens = 0;
2083 // Darwin doesn't use spaces to delmit arguments.
2084 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2087 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2088 return TokError("unexpected token in macro instantiation");
2090 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2093 if (Lexer.is(AsmToken::Space)) {
2094 Lex(); // Eat spaces
2096 // Spaces can delimit parameters, but could also be part an expression.
2097 // If the token after a space is an operator, add the token and the next
2098 // one into this argument
2100 if (isOperator(Lexer.getKind())) {
2101 // Check to see whether the token is used as an operator,
2102 // or part of an identifier
2103 const char *NextChar = getTok().getEndLoc().getPointer();
2104 if (*NextChar == ' ')
2108 if (!AddTokens && ParenLevel == 0) {
2114 // handleMacroEntry relies on not advancing the lexer here
2115 // to be able to fill in the remaining default parameter values
2116 if (Lexer.is(AsmToken::EndOfStatement))
2119 // Adjust the current parentheses level.
2120 if (Lexer.is(AsmToken::LParen))
2122 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2125 // Append the token to the current argument list.
2126 MA.push_back(getTok());
2132 if (ParenLevel != 0)
2133 return TokError("unbalanced parentheses in macro argument");
2137 // Parse the macro instantiation arguments.
2138 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2139 MCAsmMacroArguments &A) {
2140 const unsigned NParameters = M ? M->Parameters.size() : 0;
2141 bool NamedParametersFound = false;
2142 SmallVector<SMLoc, 4> FALocs;
2144 A.resize(NParameters);
2145 FALocs.resize(NParameters);
2147 // Parse two kinds of macro invocations:
2148 // - macros defined without any parameters accept an arbitrary number of them
2149 // - macros defined with parameters accept at most that many of them
2150 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2151 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2153 SMLoc IDLoc = Lexer.getLoc();
2154 MCAsmMacroParameter FA;
2156 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2157 if (parseIdentifier(FA.Name)) {
2158 Error(IDLoc, "invalid argument identifier for formal argument");
2159 eatToEndOfStatement();
2163 if (!Lexer.is(AsmToken::Equal)) {
2164 TokError("expected '=' after formal parameter identifier");
2165 eatToEndOfStatement();
2170 NamedParametersFound = true;
2173 if (NamedParametersFound && FA.Name.empty()) {
2174 Error(IDLoc, "cannot mix positional and keyword arguments");
2175 eatToEndOfStatement();
2179 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2180 if (parseMacroArgument(FA.Value, Vararg))
2183 unsigned PI = Parameter;
2184 if (!FA.Name.empty()) {
2186 for (FAI = 0; FAI < NParameters; ++FAI)
2187 if (M->Parameters[FAI].Name == FA.Name)
2190 if (FAI >= NParameters) {
2191 assert(M && "expected macro to be defined");
2193 "parameter named '" + FA.Name + "' does not exist for macro '" +
2200 if (!FA.Value.empty()) {
2205 if (FALocs.size() <= PI)
2206 FALocs.resize(PI + 1);
2208 FALocs[PI] = Lexer.getLoc();
2211 // At the end of the statement, fill in remaining arguments that have
2212 // default values. If there aren't any, then the next argument is
2213 // required but missing
2214 if (Lexer.is(AsmToken::EndOfStatement)) {
2215 bool Failure = false;
2216 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2217 if (A[FAI].empty()) {
2218 if (M->Parameters[FAI].Required) {
2219 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2220 "missing value for required parameter "
2221 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2225 if (!M->Parameters[FAI].Value.empty())
2226 A[FAI] = M->Parameters[FAI].Value;
2232 if (Lexer.is(AsmToken::Comma))
2236 return TokError("too many positional arguments");
2239 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2240 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2241 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2244 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2245 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2248 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2250 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2251 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2252 // this, although we should protect against infinite loops.
2253 if (ActiveMacros.size() == 20)
2254 return TokError("macros cannot be nested more than 20 levels deep");
2256 MCAsmMacroArguments A;
2257 if (parseMacroArguments(M, A))
2260 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2261 // to hold the macro body with substitutions.
2262 SmallString<256> Buf;
2263 StringRef Body = M->Body;
2264 raw_svector_ostream OS(Buf);
2266 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2269 // We include the .endmacro in the buffer as our cue to exit the macro
2271 OS << ".endmacro\n";
2273 std::unique_ptr<MemoryBuffer> Instantiation =
2274 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2276 // Create the macro instantiation object and add to the current macro
2277 // instantiation stack.
2278 MacroInstantiation *MI = new MacroInstantiation(
2279 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2280 ActiveMacros.push_back(MI);
2282 ++NumOfMacroInstantiations;
2284 // Jump to the macro instantiation and prime the lexer.
2285 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2286 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2292 void AsmParser::handleMacroExit() {
2293 // Jump to the EndOfStatement we should return to, and consume it.
2294 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2297 // Pop the instantiation entry.
2298 delete ActiveMacros.back();
2299 ActiveMacros.pop_back();
2302 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2305 const MCExpr *Value;
2306 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2311 // In the case where we parse an expression starting with a '.', we will
2312 // not generate an error, nor will we create a symbol. In this case we
2313 // should just return out.
2317 // Do the assignment.
2318 Out.EmitAssignment(Sym, Value);
2320 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2325 /// parseIdentifier:
2328 bool AsmParser::parseIdentifier(StringRef &Res) {
2329 // The assembler has relaxed rules for accepting identifiers, in particular we
2330 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2331 // separate tokens. At this level, we have already lexed so we cannot (currently)
2332 // handle this as a context dependent token, instead we detect adjacent tokens
2333 // and return the combined identifier.
2334 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2335 SMLoc PrefixLoc = getLexer().getLoc();
2337 // Consume the prefix character, and check for a following identifier.
2339 if (Lexer.isNot(AsmToken::Identifier))
2342 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2343 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2346 // Construct the joined identifier and consume the token.
2348 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2353 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2356 Res = getTok().getIdentifier();
2358 Lex(); // Consume the identifier token.
2363 /// parseDirectiveSet:
2364 /// ::= .equ identifier ',' expression
2365 /// ::= .equiv identifier ',' expression
2366 /// ::= .set identifier ',' expression
2367 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2370 if (parseIdentifier(Name))
2371 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2373 if (getLexer().isNot(AsmToken::Comma))
2374 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2377 return parseAssignment(Name, allow_redef, true);
2380 bool AsmParser::parseEscapedString(std::string &Data) {
2381 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2384 StringRef Str = getTok().getStringContents();
2385 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2386 if (Str[i] != '\\') {
2391 // Recognize escaped characters. Note that this escape semantics currently
2392 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2395 return TokError("unexpected backslash at end of string");
2397 // Recognize octal sequences.
2398 if ((unsigned)(Str[i] - '0') <= 7) {
2399 // Consume up to three octal characters.
2400 unsigned Value = Str[i] - '0';
2402 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2404 Value = Value * 8 + (Str[i] - '0');
2406 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2408 Value = Value * 8 + (Str[i] - '0');
2413 return TokError("invalid octal escape sequence (out of range)");
2415 Data += (unsigned char)Value;
2419 // Otherwise recognize individual escapes.
2422 // Just reject invalid escape sequences for now.
2423 return TokError("invalid escape sequence (unrecognized character)");
2425 case 'b': Data += '\b'; break;
2426 case 'f': Data += '\f'; break;
2427 case 'n': Data += '\n'; break;
2428 case 'r': Data += '\r'; break;
2429 case 't': Data += '\t'; break;
2430 case '"': Data += '"'; break;
2431 case '\\': Data += '\\'; break;
2438 /// parseDirectiveAscii:
2439 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2440 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2441 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2442 checkForValidSection();
2445 if (getLexer().isNot(AsmToken::String))
2446 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2449 if (parseEscapedString(Data))
2452 getStreamer().EmitBytes(Data);
2454 getStreamer().EmitBytes(StringRef("\0", 1));
2458 if (getLexer().is(AsmToken::EndOfStatement))
2461 if (getLexer().isNot(AsmToken::Comma))
2462 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2471 /// parseDirectiveReloc
2472 /// ::= .reloc expression , identifier [ , expression ]
2473 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2474 const MCExpr *Offset;
2475 const MCExpr *Expr = nullptr;
2477 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2478 if (parseExpression(Offset))
2481 // We can only deal with constant expressions at the moment.
2482 int64_t OffsetValue;
2483 if (!Offset->evaluateAsAbsolute(OffsetValue))
2484 return Error(OffsetLoc, "expression is not a constant value");
2486 if (Lexer.isNot(AsmToken::Comma))
2487 return TokError("expected comma");
2490 if (Lexer.isNot(AsmToken::Identifier))
2491 return TokError("expected relocation name");
2492 SMLoc NameLoc = Lexer.getTok().getLoc();
2493 StringRef Name = Lexer.getTok().getIdentifier();
2496 if (Lexer.is(AsmToken::Comma)) {
2498 SMLoc ExprLoc = Lexer.getLoc();
2499 if (parseExpression(Expr))
2503 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2504 return Error(ExprLoc, "expression must be relocatable");
2507 if (Lexer.isNot(AsmToken::EndOfStatement))
2508 return TokError("unexpected token in .reloc directive");
2510 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2511 return Error(NameLoc, "unknown relocation name");
2516 /// parseDirectiveValue
2517 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2518 bool AsmParser::parseDirectiveValue(unsigned Size) {
2519 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2520 checkForValidSection();
2523 const MCExpr *Value;
2524 SMLoc ExprLoc = getLexer().getLoc();
2525 if (parseExpression(Value))
2528 // Special case constant expressions to match code generator.
2529 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2530 assert(Size <= 8 && "Invalid size");
2531 uint64_t IntValue = MCE->getValue();
2532 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2533 return Error(ExprLoc, "literal value out of range for directive");
2534 getStreamer().EmitIntValue(IntValue, Size);
2536 getStreamer().EmitValue(Value, Size, ExprLoc);
2538 if (getLexer().is(AsmToken::EndOfStatement))
2541 // FIXME: Improve diagnostic.
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return TokError("unexpected token in directive");
2552 /// ParseDirectiveOctaValue
2553 /// ::= .octa [ hexconstant (, hexconstant)* ]
2554 bool AsmParser::parseDirectiveOctaValue() {
2555 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2556 checkForValidSection();
2559 if (Lexer.getKind() == AsmToken::Error)
2561 if (Lexer.getKind() != AsmToken::Integer &&
2562 Lexer.getKind() != AsmToken::BigNum)
2563 return TokError("unknown token in expression");
2565 SMLoc ExprLoc = getLexer().getLoc();
2566 APInt IntValue = getTok().getAPIntVal();
2570 if (IntValue.isIntN(64)) {
2572 lo = IntValue.getZExtValue();
2573 } else if (IntValue.isIntN(128)) {
2574 // It might actually have more than 128 bits, but the top ones are zero.
2575 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2576 lo = IntValue.getLoBits(64).getZExtValue();
2578 return Error(ExprLoc, "literal value out of range for directive");
2580 if (MAI.isLittleEndian()) {
2581 getStreamer().EmitIntValue(lo, 8);
2582 getStreamer().EmitIntValue(hi, 8);
2584 getStreamer().EmitIntValue(hi, 8);
2585 getStreamer().EmitIntValue(lo, 8);
2588 if (getLexer().is(AsmToken::EndOfStatement))
2591 // FIXME: Improve diagnostic.
2592 if (getLexer().isNot(AsmToken::Comma))
2593 return TokError("unexpected token in directive");
2602 /// parseDirectiveRealValue
2603 /// ::= (.single | .double) [ expression (, expression)* ]
2604 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2605 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2606 checkForValidSection();
2609 // We don't truly support arithmetic on floating point expressions, so we
2610 // have to manually parse unary prefixes.
2612 if (getLexer().is(AsmToken::Minus)) {
2615 } else if (getLexer().is(AsmToken::Plus))
2618 if (getLexer().isNot(AsmToken::Integer) &&
2619 getLexer().isNot(AsmToken::Real) &&
2620 getLexer().isNot(AsmToken::Identifier))
2621 return TokError("unexpected token in directive");
2623 // Convert to an APFloat.
2624 APFloat Value(Semantics);
2625 StringRef IDVal = getTok().getString();
2626 if (getLexer().is(AsmToken::Identifier)) {
2627 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2628 Value = APFloat::getInf(Semantics);
2629 else if (!IDVal.compare_lower("nan"))
2630 Value = APFloat::getNaN(Semantics, false, ~0);
2632 return TokError("invalid floating point literal");
2633 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2634 APFloat::opInvalidOp)
2635 return TokError("invalid floating point literal");
2639 // Consume the numeric token.
2642 // Emit the value as an integer.
2643 APInt AsInt = Value.bitcastToAPInt();
2644 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2645 AsInt.getBitWidth() / 8);
2647 if (getLexer().is(AsmToken::EndOfStatement))
2650 if (getLexer().isNot(AsmToken::Comma))
2651 return TokError("unexpected token in directive");
2660 /// parseDirectiveZero
2661 /// ::= .zero expression
2662 bool AsmParser::parseDirectiveZero() {
2663 checkForValidSection();
2666 if (parseAbsoluteExpression(NumBytes))
2670 if (getLexer().is(AsmToken::Comma)) {
2672 if (parseAbsoluteExpression(Val))
2676 if (getLexer().isNot(AsmToken::EndOfStatement))
2677 return TokError("unexpected token in '.zero' directive");
2681 getStreamer().EmitFill(NumBytes, Val);
2686 /// parseDirectiveFill
2687 /// ::= .fill expression [ , expression [ , expression ] ]
2688 bool AsmParser::parseDirectiveFill() {
2689 checkForValidSection();
2691 SMLoc RepeatLoc = getLexer().getLoc();
2693 if (parseAbsoluteExpression(NumValues))
2696 if (NumValues < 0) {
2698 "'.fill' directive with negative repeat count has no effect");
2702 int64_t FillSize = 1;
2703 int64_t FillExpr = 0;
2705 SMLoc SizeLoc, ExprLoc;
2706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2707 if (getLexer().isNot(AsmToken::Comma))
2708 return TokError("unexpected token in '.fill' directive");
2711 SizeLoc = getLexer().getLoc();
2712 if (parseAbsoluteExpression(FillSize))
2715 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2716 if (getLexer().isNot(AsmToken::Comma))
2717 return TokError("unexpected token in '.fill' directive");
2720 ExprLoc = getLexer().getLoc();
2721 if (parseAbsoluteExpression(FillExpr))
2724 if (getLexer().isNot(AsmToken::EndOfStatement))
2725 return TokError("unexpected token in '.fill' directive");
2732 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2736 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2740 if (!isUInt<32>(FillExpr) && FillSize > 4)
2741 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2743 if (NumValues > 0) {
2744 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2745 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2746 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2747 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2748 if (NonZeroFillSize < FillSize)
2749 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2756 /// parseDirectiveOrg
2757 /// ::= .org expression [ , expression ]
2758 bool AsmParser::parseDirectiveOrg() {
2759 checkForValidSection();
2761 const MCExpr *Offset;
2762 if (parseExpression(Offset))
2765 // Parse optional fill expression.
2766 int64_t FillExpr = 0;
2767 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2768 if (getLexer().isNot(AsmToken::Comma))
2769 return TokError("unexpected token in '.org' directive");
2772 if (parseAbsoluteExpression(FillExpr))
2775 if (getLexer().isNot(AsmToken::EndOfStatement))
2776 return TokError("unexpected token in '.org' directive");
2780 getStreamer().emitValueToOffset(Offset, FillExpr);
2784 /// parseDirectiveAlign
2785 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2786 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2787 checkForValidSection();
2789 SMLoc AlignmentLoc = getLexer().getLoc();
2791 if (parseAbsoluteExpression(Alignment))
2795 bool HasFillExpr = false;
2796 int64_t FillExpr = 0;
2797 int64_t MaxBytesToFill = 0;
2798 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2799 if (getLexer().isNot(AsmToken::Comma))
2800 return TokError("unexpected token in directive");
2803 // The fill expression can be omitted while specifying a maximum number of
2804 // alignment bytes, e.g:
2806 if (getLexer().isNot(AsmToken::Comma)) {
2808 if (parseAbsoluteExpression(FillExpr))
2812 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2813 if (getLexer().isNot(AsmToken::Comma))
2814 return TokError("unexpected token in directive");
2817 MaxBytesLoc = getLexer().getLoc();
2818 if (parseAbsoluteExpression(MaxBytesToFill))
2821 if (getLexer().isNot(AsmToken::EndOfStatement))
2822 return TokError("unexpected token in directive");
2831 // Compute alignment in bytes.
2833 // FIXME: Diagnose overflow.
2834 if (Alignment >= 32) {
2835 Error(AlignmentLoc, "invalid alignment value");
2839 Alignment = 1ULL << Alignment;
2841 // Reject alignments that aren't either a power of two or zero,
2842 // for gas compatibility. Alignment of zero is silently rounded
2846 if (!isPowerOf2_64(Alignment))
2847 Error(AlignmentLoc, "alignment must be a power of 2");
2850 // Diagnose non-sensical max bytes to align.
2851 if (MaxBytesLoc.isValid()) {
2852 if (MaxBytesToFill < 1) {
2853 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2854 "many bytes, ignoring maximum bytes expression");
2858 if (MaxBytesToFill >= Alignment) {
2859 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2865 // Check whether we should use optimal code alignment for this .align
2867 const MCSection *Section = getStreamer().getCurrentSection().first;
2868 assert(Section && "must have section to emit alignment");
2869 bool UseCodeAlign = Section->UseCodeAlign();
2870 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2871 ValueSize == 1 && UseCodeAlign) {
2872 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2874 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2875 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2882 /// parseDirectiveFile
2883 /// ::= .file [number] filename
2884 /// ::= .file number directory filename
2885 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2886 // FIXME: I'm not sure what this is.
2887 int64_t FileNumber = -1;
2888 SMLoc FileNumberLoc = getLexer().getLoc();
2889 if (getLexer().is(AsmToken::Integer)) {
2890 FileNumber = getTok().getIntVal();
2894 return TokError("file number less than one");
2897 if (getLexer().isNot(AsmToken::String))
2898 return TokError("unexpected token in '.file' directive");
2900 // Usually the directory and filename together, otherwise just the directory.
2901 // Allow the strings to have escaped octal character sequence.
2902 std::string Path = getTok().getString();
2903 if (parseEscapedString(Path))
2907 StringRef Directory;
2909 std::string FilenameData;
2910 if (getLexer().is(AsmToken::String)) {
2911 if (FileNumber == -1)
2912 return TokError("explicit path specified, but no file number");
2913 if (parseEscapedString(FilenameData))
2915 Filename = FilenameData;
2922 if (getLexer().isNot(AsmToken::EndOfStatement))
2923 return TokError("unexpected token in '.file' directive");
2925 if (FileNumber == -1)
2926 getStreamer().EmitFileDirective(Filename);
2928 if (getContext().getGenDwarfForAssembly())
2930 "input can't have .file dwarf directives when -g is "
2931 "used to generate dwarf debug info for assembly code");
2933 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2935 Error(FileNumberLoc, "file number already allocated");
2941 /// parseDirectiveLine
2942 /// ::= .line [number]
2943 bool AsmParser::parseDirectiveLine() {
2944 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2945 if (getLexer().isNot(AsmToken::Integer))
2946 return TokError("unexpected token in '.line' directive");
2948 int64_t LineNumber = getTok().getIntVal();
2952 // FIXME: Do something with the .line.
2955 if (getLexer().isNot(AsmToken::EndOfStatement))
2956 return TokError("unexpected token in '.line' directive");
2961 /// parseDirectiveLoc
2962 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2963 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2964 /// The first number is a file number, must have been previously assigned with
2965 /// a .file directive, the second number is the line number and optionally the
2966 /// third number is a column position (zero if not specified). The remaining
2967 /// optional items are .loc sub-directives.
2968 bool AsmParser::parseDirectiveLoc() {
2969 if (getLexer().isNot(AsmToken::Integer))
2970 return TokError("unexpected token in '.loc' directive");
2971 int64_t FileNumber = getTok().getIntVal();
2973 return TokError("file number less than one in '.loc' directive");
2974 if (!getContext().isValidDwarfFileNumber(FileNumber))
2975 return TokError("unassigned file number in '.loc' directive");
2978 int64_t LineNumber = 0;
2979 if (getLexer().is(AsmToken::Integer)) {
2980 LineNumber = getTok().getIntVal();
2982 return TokError("line number less than zero in '.loc' directive");
2986 int64_t ColumnPos = 0;
2987 if (getLexer().is(AsmToken::Integer)) {
2988 ColumnPos = getTok().getIntVal();
2990 return TokError("column position less than zero in '.loc' directive");
2994 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2996 int64_t Discriminator = 0;
2997 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2999 if (getLexer().is(AsmToken::EndOfStatement))
3003 SMLoc Loc = getTok().getLoc();
3004 if (parseIdentifier(Name))
3005 return TokError("unexpected token in '.loc' directive");
3007 if (Name == "basic_block")
3008 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3009 else if (Name == "prologue_end")
3010 Flags |= DWARF2_FLAG_PROLOGUE_END;
3011 else if (Name == "epilogue_begin")
3012 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3013 else if (Name == "is_stmt") {
3014 Loc = getTok().getLoc();
3015 const MCExpr *Value;
3016 if (parseExpression(Value))
3018 // The expression must be the constant 0 or 1.
3019 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3020 int Value = MCE->getValue();
3022 Flags &= ~DWARF2_FLAG_IS_STMT;
3023 else if (Value == 1)
3024 Flags |= DWARF2_FLAG_IS_STMT;
3026 return Error(Loc, "is_stmt value not 0 or 1");
3028 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3030 } else if (Name == "isa") {
3031 Loc = getTok().getLoc();
3032 const MCExpr *Value;
3033 if (parseExpression(Value))
3035 // The expression must be a constant greater or equal to 0.
3036 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3037 int Value = MCE->getValue();
3039 return Error(Loc, "isa number less than zero");
3042 return Error(Loc, "isa number not a constant value");
3044 } else if (Name == "discriminator") {
3045 if (parseAbsoluteExpression(Discriminator))
3048 return Error(Loc, "unknown sub-directive in '.loc' directive");
3051 if (getLexer().is(AsmToken::EndOfStatement))
3056 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3057 Isa, Discriminator, StringRef());
3062 /// parseDirectiveStabs
3063 /// ::= .stabs string, number, number, number
3064 bool AsmParser::parseDirectiveStabs() {
3065 return TokError("unsupported directive '.stabs'");
3068 /// parseDirectiveCFISections
3069 /// ::= .cfi_sections section [, section]
3070 bool AsmParser::parseDirectiveCFISections() {
3075 if (parseIdentifier(Name))
3076 return TokError("Expected an identifier");
3078 if (Name == ".eh_frame")
3080 else if (Name == ".debug_frame")
3083 if (getLexer().is(AsmToken::Comma)) {
3086 if (parseIdentifier(Name))
3087 return TokError("Expected an identifier");
3089 if (Name == ".eh_frame")
3091 else if (Name == ".debug_frame")
3095 getStreamer().EmitCFISections(EH, Debug);
3099 /// parseDirectiveCFIStartProc
3100 /// ::= .cfi_startproc [simple]
3101 bool AsmParser::parseDirectiveCFIStartProc() {
3103 if (getLexer().isNot(AsmToken::EndOfStatement))
3104 if (parseIdentifier(Simple) || Simple != "simple")
3105 return TokError("unexpected token in .cfi_startproc directive");
3107 getStreamer().EmitCFIStartProc(!Simple.empty());
3111 /// parseDirectiveCFIEndProc
3112 /// ::= .cfi_endproc
3113 bool AsmParser::parseDirectiveCFIEndProc() {
3114 getStreamer().EmitCFIEndProc();
3118 /// \brief parse register name or number.
3119 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3120 SMLoc DirectiveLoc) {
3123 if (getLexer().isNot(AsmToken::Integer)) {
3124 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3126 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3128 return parseAbsoluteExpression(Register);
3133 /// parseDirectiveCFIDefCfa
3134 /// ::= .cfi_def_cfa register, offset
3135 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3136 int64_t Register = 0;
3137 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3140 if (getLexer().isNot(AsmToken::Comma))
3141 return TokError("unexpected token in directive");
3145 if (parseAbsoluteExpression(Offset))
3148 getStreamer().EmitCFIDefCfa(Register, Offset);
3152 /// parseDirectiveCFIDefCfaOffset
3153 /// ::= .cfi_def_cfa_offset offset
3154 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3156 if (parseAbsoluteExpression(Offset))
3159 getStreamer().EmitCFIDefCfaOffset(Offset);
3163 /// parseDirectiveCFIRegister
3164 /// ::= .cfi_register register, register
3165 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3166 int64_t Register1 = 0;
3167 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3170 if (getLexer().isNot(AsmToken::Comma))
3171 return TokError("unexpected token in directive");
3174 int64_t Register2 = 0;
3175 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3178 getStreamer().EmitCFIRegister(Register1, Register2);
3182 /// parseDirectiveCFIWindowSave
3183 /// ::= .cfi_window_save
3184 bool AsmParser::parseDirectiveCFIWindowSave() {
3185 getStreamer().EmitCFIWindowSave();
3189 /// parseDirectiveCFIAdjustCfaOffset
3190 /// ::= .cfi_adjust_cfa_offset adjustment
3191 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3192 int64_t Adjustment = 0;
3193 if (parseAbsoluteExpression(Adjustment))
3196 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3200 /// parseDirectiveCFIDefCfaRegister
3201 /// ::= .cfi_def_cfa_register register
3202 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3203 int64_t Register = 0;
3204 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3207 getStreamer().EmitCFIDefCfaRegister(Register);
3211 /// parseDirectiveCFIOffset
3212 /// ::= .cfi_offset register, offset
3213 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3214 int64_t Register = 0;
3217 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3220 if (getLexer().isNot(AsmToken::Comma))
3221 return TokError("unexpected token in directive");
3224 if (parseAbsoluteExpression(Offset))
3227 getStreamer().EmitCFIOffset(Register, Offset);
3231 /// parseDirectiveCFIRelOffset
3232 /// ::= .cfi_rel_offset register, offset
3233 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3234 int64_t Register = 0;
3236 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3239 if (getLexer().isNot(AsmToken::Comma))
3240 return TokError("unexpected token in directive");
3244 if (parseAbsoluteExpression(Offset))
3247 getStreamer().EmitCFIRelOffset(Register, Offset);
3251 static bool isValidEncoding(int64_t Encoding) {
3252 if (Encoding & ~0xff)
3255 if (Encoding == dwarf::DW_EH_PE_omit)
3258 const unsigned Format = Encoding & 0xf;
3259 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3260 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3261 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3262 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3265 const unsigned Application = Encoding & 0x70;
3266 if (Application != dwarf::DW_EH_PE_absptr &&
3267 Application != dwarf::DW_EH_PE_pcrel)
3273 /// parseDirectiveCFIPersonalityOrLsda
3274 /// IsPersonality true for cfi_personality, false for cfi_lsda
3275 /// ::= .cfi_personality encoding, [symbol_name]
3276 /// ::= .cfi_lsda encoding, [symbol_name]
3277 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3278 int64_t Encoding = 0;
3279 if (parseAbsoluteExpression(Encoding))
3281 if (Encoding == dwarf::DW_EH_PE_omit)
3284 if (!isValidEncoding(Encoding))
3285 return TokError("unsupported encoding.");
3287 if (getLexer().isNot(AsmToken::Comma))
3288 return TokError("unexpected token in directive");
3292 if (parseIdentifier(Name))
3293 return TokError("expected identifier in directive");
3295 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3298 getStreamer().EmitCFIPersonality(Sym, Encoding);
3300 getStreamer().EmitCFILsda(Sym, Encoding);
3304 /// parseDirectiveCFIRememberState
3305 /// ::= .cfi_remember_state
3306 bool AsmParser::parseDirectiveCFIRememberState() {
3307 getStreamer().EmitCFIRememberState();
3311 /// parseDirectiveCFIRestoreState
3312 /// ::= .cfi_remember_state
3313 bool AsmParser::parseDirectiveCFIRestoreState() {
3314 getStreamer().EmitCFIRestoreState();
3318 /// parseDirectiveCFISameValue
3319 /// ::= .cfi_same_value register
3320 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3321 int64_t Register = 0;
3323 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3326 getStreamer().EmitCFISameValue(Register);
3330 /// parseDirectiveCFIRestore
3331 /// ::= .cfi_restore register
3332 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3333 int64_t Register = 0;
3334 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3337 getStreamer().EmitCFIRestore(Register);
3341 /// parseDirectiveCFIEscape
3342 /// ::= .cfi_escape expression[,...]
3343 bool AsmParser::parseDirectiveCFIEscape() {
3346 if (parseAbsoluteExpression(CurrValue))
3349 Values.push_back((uint8_t)CurrValue);
3351 while (getLexer().is(AsmToken::Comma)) {
3354 if (parseAbsoluteExpression(CurrValue))
3357 Values.push_back((uint8_t)CurrValue);
3360 getStreamer().EmitCFIEscape(Values);
3364 /// parseDirectiveCFISignalFrame
3365 /// ::= .cfi_signal_frame
3366 bool AsmParser::parseDirectiveCFISignalFrame() {
3367 if (getLexer().isNot(AsmToken::EndOfStatement))
3368 return Error(getLexer().getLoc(),
3369 "unexpected token in '.cfi_signal_frame'");
3371 getStreamer().EmitCFISignalFrame();
3375 /// parseDirectiveCFIUndefined
3376 /// ::= .cfi_undefined register
3377 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3378 int64_t Register = 0;
3380 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3383 getStreamer().EmitCFIUndefined(Register);
3387 /// parseDirectiveMacrosOnOff
3390 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3391 if (getLexer().isNot(AsmToken::EndOfStatement))
3392 return Error(getLexer().getLoc(),
3393 "unexpected token in '" + Directive + "' directive");
3395 setMacrosEnabled(Directive == ".macros_on");
3399 /// parseDirectiveMacro
3400 /// ::= .macro name[,] [parameters]
3401 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3403 if (parseIdentifier(Name))
3404 return TokError("expected identifier in '.macro' directive");
3406 if (getLexer().is(AsmToken::Comma))
3409 MCAsmMacroParameters Parameters;
3410 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3412 if (!Parameters.empty() && Parameters.back().Vararg)
3413 return Error(Lexer.getLoc(),
3414 "Vararg parameter '" + Parameters.back().Name +
3415 "' should be last one in the list of parameters.");
3417 MCAsmMacroParameter Parameter;
3418 if (parseIdentifier(Parameter.Name))
3419 return TokError("expected identifier in '.macro' directive");
3421 if (Lexer.is(AsmToken::Colon)) {
3422 Lex(); // consume ':'
3425 StringRef Qualifier;
3427 QualLoc = Lexer.getLoc();
3428 if (parseIdentifier(Qualifier))
3429 return Error(QualLoc, "missing parameter qualifier for "
3430 "'" + Parameter.Name + "' in macro '" + Name + "'");
3432 if (Qualifier == "req")
3433 Parameter.Required = true;
3434 else if (Qualifier == "vararg")
3435 Parameter.Vararg = true;
3437 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3438 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3441 if (getLexer().is(AsmToken::Equal)) {
3446 ParamLoc = Lexer.getLoc();
3447 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3450 if (Parameter.Required)
3451 Warning(ParamLoc, "pointless default value for required parameter "
3452 "'" + Parameter.Name + "' in macro '" + Name + "'");
3455 Parameters.push_back(std::move(Parameter));
3457 if (getLexer().is(AsmToken::Comma))
3461 // Eat the end of statement.
3464 AsmToken EndToken, StartToken = getTok();
3465 unsigned MacroDepth = 0;
3467 // Lex the macro definition.
3469 // Check whether we have reached the end of the file.
3470 if (getLexer().is(AsmToken::Eof))
3471 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3473 // Otherwise, check whether we have reach the .endmacro.
3474 if (getLexer().is(AsmToken::Identifier)) {
3475 if (getTok().getIdentifier() == ".endm" ||
3476 getTok().getIdentifier() == ".endmacro") {
3477 if (MacroDepth == 0) { // Outermost macro.
3478 EndToken = getTok();
3480 if (getLexer().isNot(AsmToken::EndOfStatement))
3481 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3485 // Otherwise we just found the end of an inner macro.
3488 } else if (getTok().getIdentifier() == ".macro") {
3489 // We allow nested macros. Those aren't instantiated until the outermost
3490 // macro is expanded so just ignore them for now.
3495 // Otherwise, scan til the end of the statement.
3496 eatToEndOfStatement();
3499 if (lookupMacro(Name)) {
3500 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3503 const char *BodyStart = StartToken.getLoc().getPointer();
3504 const char *BodyEnd = EndToken.getLoc().getPointer();
3505 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3506 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3507 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3511 /// checkForBadMacro
3513 /// With the support added for named parameters there may be code out there that
3514 /// is transitioning from positional parameters. In versions of gas that did
3515 /// not support named parameters they would be ignored on the macro definition.
3516 /// But to support both styles of parameters this is not possible so if a macro
3517 /// definition has named parameters but does not use them and has what appears
3518 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3519 /// warning that the positional parameter found in body which have no effect.
3520 /// Hoping the developer will either remove the named parameters from the macro
3521 /// definition so the positional parameters get used if that was what was
3522 /// intended or change the macro to use the named parameters. It is possible
3523 /// this warning will trigger when the none of the named parameters are used
3524 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3525 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3527 ArrayRef<MCAsmMacroParameter> Parameters) {
3528 // If this macro is not defined with named parameters the warning we are
3529 // checking for here doesn't apply.
3530 unsigned NParameters = Parameters.size();
3531 if (NParameters == 0)
3534 bool NamedParametersFound = false;
3535 bool PositionalParametersFound = false;
3537 // Look at the body of the macro for use of both the named parameters and what
3538 // are likely to be positional parameters. This is what expandMacro() is
3539 // doing when it finds the parameters in the body.
3540 while (!Body.empty()) {
3541 // Scan for the next possible parameter.
3542 std::size_t End = Body.size(), Pos = 0;
3543 for (; Pos != End; ++Pos) {
3544 // Check for a substitution or escape.
3545 // This macro is defined with parameters, look for \foo, \bar, etc.
3546 if (Body[Pos] == '\\' && Pos + 1 != End)
3549 // This macro should have parameters, but look for $0, $1, ..., $n too.
3550 if (Body[Pos] != '$' || Pos + 1 == End)
3552 char Next = Body[Pos + 1];
3553 if (Next == '$' || Next == 'n' ||
3554 isdigit(static_cast<unsigned char>(Next)))
3558 // Check if we reached the end.
3562 if (Body[Pos] == '$') {
3563 switch (Body[Pos + 1]) {
3568 // $n => number of arguments
3570 PositionalParametersFound = true;
3573 // $[0-9] => argument
3575 PositionalParametersFound = true;
3581 unsigned I = Pos + 1;
3582 while (isIdentifierChar(Body[I]) && I + 1 != End)
3585 const char *Begin = Body.data() + Pos + 1;
3586 StringRef Argument(Begin, I - (Pos + 1));
3588 for (; Index < NParameters; ++Index)
3589 if (Parameters[Index].Name == Argument)
3592 if (Index == NParameters) {
3593 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3599 NamedParametersFound = true;
3600 Pos += 1 + Argument.size();
3603 // Update the scan point.
3604 Body = Body.substr(Pos);
3607 if (!NamedParametersFound && PositionalParametersFound)
3608 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3609 "used in macro body, possible positional parameter "
3610 "found in body which will have no effect");
3613 /// parseDirectiveExitMacro
3615 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3616 if (getLexer().isNot(AsmToken::EndOfStatement))
3617 return TokError("unexpected token in '" + Directive + "' directive");
3619 if (!isInsideMacroInstantiation())
3620 return TokError("unexpected '" + Directive + "' in file, "
3621 "no current macro definition");
3623 // Exit all conditionals that are active in the current macro.
3624 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3625 TheCondState = TheCondStack.back();
3626 TheCondStack.pop_back();
3633 /// parseDirectiveEndMacro
3636 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3637 if (getLexer().isNot(AsmToken::EndOfStatement))
3638 return TokError("unexpected token in '" + Directive + "' directive");
3640 // If we are inside a macro instantiation, terminate the current
3642 if (isInsideMacroInstantiation()) {
3647 // Otherwise, this .endmacro is a stray entry in the file; well formed
3648 // .endmacro directives are handled during the macro definition parsing.
3649 return TokError("unexpected '" + Directive + "' in file, "
3650 "no current macro definition");
3653 /// parseDirectivePurgeMacro
3655 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3657 if (parseIdentifier(Name))
3658 return TokError("expected identifier in '.purgem' directive");
3660 if (getLexer().isNot(AsmToken::EndOfStatement))
3661 return TokError("unexpected token in '.purgem' directive");
3663 if (!lookupMacro(Name))
3664 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3666 undefineMacro(Name);
3670 /// parseDirectiveBundleAlignMode
3671 /// ::= {.bundle_align_mode} expression
3672 bool AsmParser::parseDirectiveBundleAlignMode() {
3673 checkForValidSection();
3675 // Expect a single argument: an expression that evaluates to a constant
3676 // in the inclusive range 0-30.
3677 SMLoc ExprLoc = getLexer().getLoc();
3678 int64_t AlignSizePow2;
3679 if (parseAbsoluteExpression(AlignSizePow2))
3681 else if (getLexer().isNot(AsmToken::EndOfStatement))
3682 return TokError("unexpected token after expression in"
3683 " '.bundle_align_mode' directive");
3684 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3685 return Error(ExprLoc,
3686 "invalid bundle alignment size (expected between 0 and 30)");
3690 // Because of AlignSizePow2's verified range we can safely truncate it to
3692 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3696 /// parseDirectiveBundleLock
3697 /// ::= {.bundle_lock} [align_to_end]
3698 bool AsmParser::parseDirectiveBundleLock() {
3699 checkForValidSection();
3700 bool AlignToEnd = false;
3702 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3704 SMLoc Loc = getTok().getLoc();
3705 const char *kInvalidOptionError =
3706 "invalid option for '.bundle_lock' directive";
3708 if (parseIdentifier(Option))
3709 return Error(Loc, kInvalidOptionError);
3711 if (Option != "align_to_end")
3712 return Error(Loc, kInvalidOptionError);
3713 else if (getLexer().isNot(AsmToken::EndOfStatement))
3715 "unexpected token after '.bundle_lock' directive option");
3721 getStreamer().EmitBundleLock(AlignToEnd);
3725 /// parseDirectiveBundleLock
3726 /// ::= {.bundle_lock}
3727 bool AsmParser::parseDirectiveBundleUnlock() {
3728 checkForValidSection();
3730 if (getLexer().isNot(AsmToken::EndOfStatement))
3731 return TokError("unexpected token in '.bundle_unlock' directive");
3734 getStreamer().EmitBundleUnlock();
3738 /// parseDirectiveSpace
3739 /// ::= (.skip | .space) expression [ , expression ]
3740 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3741 checkForValidSection();
3744 if (parseAbsoluteExpression(NumBytes))
3747 int64_t FillExpr = 0;
3748 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3749 if (getLexer().isNot(AsmToken::Comma))
3750 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3753 if (parseAbsoluteExpression(FillExpr))
3756 if (getLexer().isNot(AsmToken::EndOfStatement))
3757 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3763 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3766 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3767 getStreamer().EmitFill(NumBytes, FillExpr);
3772 /// parseDirectiveLEB128
3773 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3774 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3775 checkForValidSection();
3776 const MCExpr *Value;
3779 if (parseExpression(Value))
3783 getStreamer().EmitSLEB128Value(Value);
3785 getStreamer().EmitULEB128Value(Value);
3787 if (getLexer().is(AsmToken::EndOfStatement))
3790 if (getLexer().isNot(AsmToken::Comma))
3791 return TokError("unexpected token in directive");
3798 /// parseDirectiveSymbolAttribute
3799 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3800 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3801 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3804 SMLoc Loc = getTok().getLoc();
3806 if (parseIdentifier(Name))
3807 return Error(Loc, "expected identifier in directive");
3809 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3811 // Assembler local symbols don't make any sense here. Complain loudly.
3812 if (Sym->isTemporary())
3813 return Error(Loc, "non-local symbol required in directive");
3815 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3816 return Error(Loc, "unable to emit symbol attribute");
3818 if (getLexer().is(AsmToken::EndOfStatement))
3821 if (getLexer().isNot(AsmToken::Comma))
3822 return TokError("unexpected token in directive");
3831 /// parseDirectiveComm
3832 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3833 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3834 checkForValidSection();
3836 SMLoc IDLoc = getLexer().getLoc();
3838 if (parseIdentifier(Name))
3839 return TokError("expected identifier in directive");
3841 // Handle the identifier as the key symbol.
3842 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3844 if (getLexer().isNot(AsmToken::Comma))
3845 return TokError("unexpected token in directive");
3849 SMLoc SizeLoc = getLexer().getLoc();
3850 if (parseAbsoluteExpression(Size))
3853 int64_t Pow2Alignment = 0;
3854 SMLoc Pow2AlignmentLoc;
3855 if (getLexer().is(AsmToken::Comma)) {
3857 Pow2AlignmentLoc = getLexer().getLoc();
3858 if (parseAbsoluteExpression(Pow2Alignment))
3861 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3862 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3863 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3865 // If this target takes alignments in bytes (not log) validate and convert.
3866 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3867 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3868 if (!isPowerOf2_64(Pow2Alignment))
3869 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3870 Pow2Alignment = Log2_64(Pow2Alignment);
3874 if (getLexer().isNot(AsmToken::EndOfStatement))
3875 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3879 // NOTE: a size of zero for a .comm should create a undefined symbol
3880 // but a size of .lcomm creates a bss symbol of size zero.
3882 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3883 "be less than zero");
3885 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3886 // may internally end up wanting an alignment in bytes.
3887 // FIXME: Diagnose overflow.
3888 if (Pow2Alignment < 0)
3889 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3890 "alignment, can't be less than zero");
3892 if (!Sym->isUndefined())
3893 return Error(IDLoc, "invalid symbol redefinition");
3895 // Create the Symbol as a common or local common with Size and Pow2Alignment
3897 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3901 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3905 /// parseDirectiveAbort
3906 /// ::= .abort [... message ...]
3907 bool AsmParser::parseDirectiveAbort() {
3908 // FIXME: Use loc from directive.
3909 SMLoc Loc = getLexer().getLoc();
3911 StringRef Str = parseStringToEndOfStatement();
3912 if (getLexer().isNot(AsmToken::EndOfStatement))
3913 return TokError("unexpected token in '.abort' directive");
3918 Error(Loc, ".abort detected. Assembly stopping.");
3920 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3921 // FIXME: Actually abort assembly here.
3926 /// parseDirectiveInclude
3927 /// ::= .include "filename"
3928 bool AsmParser::parseDirectiveInclude() {
3929 if (getLexer().isNot(AsmToken::String))
3930 return TokError("expected string in '.include' directive");
3932 // Allow the strings to have escaped octal character sequence.
3933 std::string Filename;
3934 if (parseEscapedString(Filename))
3936 SMLoc IncludeLoc = getLexer().getLoc();
3939 if (getLexer().isNot(AsmToken::EndOfStatement))
3940 return TokError("unexpected token in '.include' directive");
3942 // Attempt to switch the lexer to the included file before consuming the end
3943 // of statement to avoid losing it when we switch.
3944 if (enterIncludeFile(Filename)) {
3945 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3952 /// parseDirectiveIncbin
3953 /// ::= .incbin "filename"
3954 bool AsmParser::parseDirectiveIncbin() {
3955 if (getLexer().isNot(AsmToken::String))
3956 return TokError("expected string in '.incbin' directive");
3958 // Allow the strings to have escaped octal character sequence.
3959 std::string Filename;
3960 if (parseEscapedString(Filename))
3962 SMLoc IncbinLoc = getLexer().getLoc();
3965 if (getLexer().isNot(AsmToken::EndOfStatement))
3966 return TokError("unexpected token in '.incbin' directive");
3968 // Attempt to process the included file.
3969 if (processIncbinFile(Filename)) {
3970 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3977 /// parseDirectiveIf
3978 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3979 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3980 TheCondStack.push_back(TheCondState);
3981 TheCondState.TheCond = AsmCond::IfCond;
3982 if (TheCondState.Ignore) {
3983 eatToEndOfStatement();
3986 if (parseAbsoluteExpression(ExprValue))
3989 if (getLexer().isNot(AsmToken::EndOfStatement))
3990 return TokError("unexpected token in '.if' directive");
3996 llvm_unreachable("unsupported directive");
4001 ExprValue = ExprValue == 0;
4004 ExprValue = ExprValue >= 0;
4007 ExprValue = ExprValue > 0;
4010 ExprValue = ExprValue <= 0;
4013 ExprValue = ExprValue < 0;
4017 TheCondState.CondMet = ExprValue;
4018 TheCondState.Ignore = !TheCondState.CondMet;
4024 /// parseDirectiveIfb
4026 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4027 TheCondStack.push_back(TheCondState);
4028 TheCondState.TheCond = AsmCond::IfCond;
4030 if (TheCondState.Ignore) {
4031 eatToEndOfStatement();
4033 StringRef Str = parseStringToEndOfStatement();
4035 if (getLexer().isNot(AsmToken::EndOfStatement))
4036 return TokError("unexpected token in '.ifb' directive");
4040 TheCondState.CondMet = ExpectBlank == Str.empty();
4041 TheCondState.Ignore = !TheCondState.CondMet;
4047 /// parseDirectiveIfc
4048 /// ::= .ifc string1, string2
4049 /// ::= .ifnc string1, string2
4050 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4051 TheCondStack.push_back(TheCondState);
4052 TheCondState.TheCond = AsmCond::IfCond;
4054 if (TheCondState.Ignore) {
4055 eatToEndOfStatement();
4057 StringRef Str1 = parseStringToComma();
4059 if (getLexer().isNot(AsmToken::Comma))
4060 return TokError("unexpected token in '.ifc' directive");
4064 StringRef Str2 = parseStringToEndOfStatement();
4066 if (getLexer().isNot(AsmToken::EndOfStatement))
4067 return TokError("unexpected token in '.ifc' directive");
4071 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4072 TheCondState.Ignore = !TheCondState.CondMet;
4078 /// parseDirectiveIfeqs
4079 /// ::= .ifeqs string1, string2
4080 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4081 if (Lexer.isNot(AsmToken::String)) {
4083 TokError("expected string parameter for '.ifeqs' directive");
4085 TokError("expected string parameter for '.ifnes' directive");
4086 eatToEndOfStatement();
4090 StringRef String1 = getTok().getStringContents();
4093 if (Lexer.isNot(AsmToken::Comma)) {
4095 TokError("expected comma after first string for '.ifeqs' directive");
4097 TokError("expected comma after first string for '.ifnes' directive");
4098 eatToEndOfStatement();
4104 if (Lexer.isNot(AsmToken::String)) {
4106 TokError("expected string parameter for '.ifeqs' directive");
4108 TokError("expected string parameter for '.ifnes' directive");
4109 eatToEndOfStatement();
4113 StringRef String2 = getTok().getStringContents();
4116 TheCondStack.push_back(TheCondState);
4117 TheCondState.TheCond = AsmCond::IfCond;
4118 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4119 TheCondState.Ignore = !TheCondState.CondMet;
4124 /// parseDirectiveIfdef
4125 /// ::= .ifdef symbol
4126 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4128 TheCondStack.push_back(TheCondState);
4129 TheCondState.TheCond = AsmCond::IfCond;
4131 if (TheCondState.Ignore) {
4132 eatToEndOfStatement();
4134 if (parseIdentifier(Name))
4135 return TokError("expected identifier after '.ifdef'");
4139 MCSymbol *Sym = getContext().lookupSymbol(Name);
4142 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4144 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4145 TheCondState.Ignore = !TheCondState.CondMet;
4151 /// parseDirectiveElseIf
4152 /// ::= .elseif expression
4153 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4154 if (TheCondState.TheCond != AsmCond::IfCond &&
4155 TheCondState.TheCond != AsmCond::ElseIfCond)
4156 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4158 TheCondState.TheCond = AsmCond::ElseIfCond;
4160 bool LastIgnoreState = false;
4161 if (!TheCondStack.empty())
4162 LastIgnoreState = TheCondStack.back().Ignore;
4163 if (LastIgnoreState || TheCondState.CondMet) {
4164 TheCondState.Ignore = true;
4165 eatToEndOfStatement();
4168 if (parseAbsoluteExpression(ExprValue))
4171 if (getLexer().isNot(AsmToken::EndOfStatement))
4172 return TokError("unexpected token in '.elseif' directive");
4175 TheCondState.CondMet = ExprValue;
4176 TheCondState.Ignore = !TheCondState.CondMet;
4182 /// parseDirectiveElse
4184 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4185 if (getLexer().isNot(AsmToken::EndOfStatement))
4186 return TokError("unexpected token in '.else' directive");
4190 if (TheCondState.TheCond != AsmCond::IfCond &&
4191 TheCondState.TheCond != AsmCond::ElseIfCond)
4192 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4194 TheCondState.TheCond = AsmCond::ElseCond;
4195 bool LastIgnoreState = false;
4196 if (!TheCondStack.empty())
4197 LastIgnoreState = TheCondStack.back().Ignore;
4198 if (LastIgnoreState || TheCondState.CondMet)
4199 TheCondState.Ignore = true;
4201 TheCondState.Ignore = false;
4206 /// parseDirectiveEnd
4208 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4209 if (getLexer().isNot(AsmToken::EndOfStatement))
4210 return TokError("unexpected token in '.end' directive");
4214 while (Lexer.isNot(AsmToken::Eof))
4220 /// parseDirectiveError
4222 /// ::= .error [string]
4223 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4224 if (!TheCondStack.empty()) {
4225 if (TheCondStack.back().Ignore) {
4226 eatToEndOfStatement();
4232 return Error(L, ".err encountered");
4234 StringRef Message = ".error directive invoked in source file";
4235 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4236 if (Lexer.isNot(AsmToken::String)) {
4237 TokError(".error argument must be a string");
4238 eatToEndOfStatement();
4242 Message = getTok().getStringContents();
4250 /// parseDirectiveWarning
4251 /// ::= .warning [string]
4252 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4253 if (!TheCondStack.empty()) {
4254 if (TheCondStack.back().Ignore) {
4255 eatToEndOfStatement();
4260 StringRef Message = ".warning directive invoked in source file";
4261 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4262 if (Lexer.isNot(AsmToken::String)) {
4263 TokError(".warning argument must be a string");
4264 eatToEndOfStatement();
4268 Message = getTok().getStringContents();
4272 Warning(L, Message);
4276 /// parseDirectiveEndIf
4278 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4279 if (getLexer().isNot(AsmToken::EndOfStatement))
4280 return TokError("unexpected token in '.endif' directive");
4284 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4285 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4287 if (!TheCondStack.empty()) {
4288 TheCondState = TheCondStack.back();
4289 TheCondStack.pop_back();
4295 void AsmParser::initializeDirectiveKindMap() {
4296 DirectiveKindMap[".set"] = DK_SET;
4297 DirectiveKindMap[".equ"] = DK_EQU;
4298 DirectiveKindMap[".equiv"] = DK_EQUIV;
4299 DirectiveKindMap[".ascii"] = DK_ASCII;
4300 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4301 DirectiveKindMap[".string"] = DK_STRING;
4302 DirectiveKindMap[".byte"] = DK_BYTE;
4303 DirectiveKindMap[".short"] = DK_SHORT;
4304 DirectiveKindMap[".value"] = DK_VALUE;
4305 DirectiveKindMap[".2byte"] = DK_2BYTE;
4306 DirectiveKindMap[".long"] = DK_LONG;
4307 DirectiveKindMap[".int"] = DK_INT;
4308 DirectiveKindMap[".4byte"] = DK_4BYTE;
4309 DirectiveKindMap[".quad"] = DK_QUAD;
4310 DirectiveKindMap[".8byte"] = DK_8BYTE;
4311 DirectiveKindMap[".octa"] = DK_OCTA;
4312 DirectiveKindMap[".single"] = DK_SINGLE;
4313 DirectiveKindMap[".float"] = DK_FLOAT;
4314 DirectiveKindMap[".double"] = DK_DOUBLE;
4315 DirectiveKindMap[".align"] = DK_ALIGN;
4316 DirectiveKindMap[".align32"] = DK_ALIGN32;
4317 DirectiveKindMap[".balign"] = DK_BALIGN;
4318 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4319 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4320 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4321 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4322 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4323 DirectiveKindMap[".org"] = DK_ORG;
4324 DirectiveKindMap[".fill"] = DK_FILL;
4325 DirectiveKindMap[".zero"] = DK_ZERO;
4326 DirectiveKindMap[".extern"] = DK_EXTERN;
4327 DirectiveKindMap[".globl"] = DK_GLOBL;
4328 DirectiveKindMap[".global"] = DK_GLOBAL;
4329 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4330 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4331 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4332 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4333 DirectiveKindMap[".reference"] = DK_REFERENCE;
4334 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4335 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4336 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4337 DirectiveKindMap[".comm"] = DK_COMM;
4338 DirectiveKindMap[".common"] = DK_COMMON;
4339 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4340 DirectiveKindMap[".abort"] = DK_ABORT;
4341 DirectiveKindMap[".include"] = DK_INCLUDE;
4342 DirectiveKindMap[".incbin"] = DK_INCBIN;
4343 DirectiveKindMap[".code16"] = DK_CODE16;
4344 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4345 DirectiveKindMap[".rept"] = DK_REPT;
4346 DirectiveKindMap[".rep"] = DK_REPT;
4347 DirectiveKindMap[".irp"] = DK_IRP;
4348 DirectiveKindMap[".irpc"] = DK_IRPC;
4349 DirectiveKindMap[".endr"] = DK_ENDR;
4350 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4351 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4352 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4353 DirectiveKindMap[".if"] = DK_IF;
4354 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4355 DirectiveKindMap[".ifge"] = DK_IFGE;
4356 DirectiveKindMap[".ifgt"] = DK_IFGT;
4357 DirectiveKindMap[".ifle"] = DK_IFLE;
4358 DirectiveKindMap[".iflt"] = DK_IFLT;
4359 DirectiveKindMap[".ifne"] = DK_IFNE;
4360 DirectiveKindMap[".ifb"] = DK_IFB;
4361 DirectiveKindMap[".ifnb"] = DK_IFNB;
4362 DirectiveKindMap[".ifc"] = DK_IFC;
4363 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4364 DirectiveKindMap[".ifnc"] = DK_IFNC;
4365 DirectiveKindMap[".ifnes"] = DK_IFNES;
4366 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4367 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4368 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4369 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4370 DirectiveKindMap[".else"] = DK_ELSE;
4371 DirectiveKindMap[".end"] = DK_END;
4372 DirectiveKindMap[".endif"] = DK_ENDIF;
4373 DirectiveKindMap[".skip"] = DK_SKIP;
4374 DirectiveKindMap[".space"] = DK_SPACE;
4375 DirectiveKindMap[".file"] = DK_FILE;
4376 DirectiveKindMap[".line"] = DK_LINE;
4377 DirectiveKindMap[".loc"] = DK_LOC;
4378 DirectiveKindMap[".stabs"] = DK_STABS;
4379 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4380 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4381 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4382 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4383 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4384 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4385 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4386 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4387 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4388 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4389 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4390 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4391 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4392 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4393 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4394 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4395 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4396 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4397 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4398 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4399 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4400 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4401 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4402 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4403 DirectiveKindMap[".macro"] = DK_MACRO;
4404 DirectiveKindMap[".exitm"] = DK_EXITM;
4405 DirectiveKindMap[".endm"] = DK_ENDM;
4406 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4407 DirectiveKindMap[".purgem"] = DK_PURGEM;
4408 DirectiveKindMap[".err"] = DK_ERR;
4409 DirectiveKindMap[".error"] = DK_ERROR;
4410 DirectiveKindMap[".warning"] = DK_WARNING;
4411 DirectiveKindMap[".reloc"] = DK_RELOC;
4414 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4415 AsmToken EndToken, StartToken = getTok();
4417 unsigned NestLevel = 0;
4419 // Check whether we have reached the end of the file.
4420 if (getLexer().is(AsmToken::Eof)) {
4421 Error(DirectiveLoc, "no matching '.endr' in definition");
4425 if (Lexer.is(AsmToken::Identifier) &&
4426 (getTok().getIdentifier() == ".rept")) {
4430 // Otherwise, check whether we have reached the .endr.
4431 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4432 if (NestLevel == 0) {
4433 EndToken = getTok();
4435 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4436 TokError("unexpected token in '.endr' directive");
4444 // Otherwise, scan till the end of the statement.
4445 eatToEndOfStatement();
4448 const char *BodyStart = StartToken.getLoc().getPointer();
4449 const char *BodyEnd = EndToken.getLoc().getPointer();
4450 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4452 // We Are Anonymous.
4453 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4454 return &MacroLikeBodies.back();
4457 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4458 raw_svector_ostream &OS) {
4461 std::unique_ptr<MemoryBuffer> Instantiation =
4462 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4464 // Create the macro instantiation object and add to the current macro
4465 // instantiation stack.
4466 MacroInstantiation *MI = new MacroInstantiation(
4467 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4468 ActiveMacros.push_back(MI);
4470 // Jump to the macro instantiation and prime the lexer.
4471 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4472 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4476 /// parseDirectiveRept
4477 /// ::= .rep | .rept count
4478 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4479 const MCExpr *CountExpr;
4480 SMLoc CountLoc = getTok().getLoc();
4481 if (parseExpression(CountExpr))
4485 if (!CountExpr->evaluateAsAbsolute(Count)) {
4486 eatToEndOfStatement();
4487 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4491 return Error(CountLoc, "Count is negative");
4493 if (Lexer.isNot(AsmToken::EndOfStatement))
4494 return TokError("unexpected token in '" + Dir + "' directive");
4496 // Eat the end of statement.
4499 // Lex the rept definition.
4500 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4504 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4505 // to hold the macro body with substitutions.
4506 SmallString<256> Buf;
4507 raw_svector_ostream OS(Buf);
4509 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4510 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4513 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4518 /// parseDirectiveIrp
4519 /// ::= .irp symbol,values
4520 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4521 MCAsmMacroParameter Parameter;
4523 if (parseIdentifier(Parameter.Name))
4524 return TokError("expected identifier in '.irp' directive");
4526 if (Lexer.isNot(AsmToken::Comma))
4527 return TokError("expected comma in '.irp' directive");
4531 MCAsmMacroArguments A;
4532 if (parseMacroArguments(nullptr, A))
4535 // Eat the end of statement.
4538 // Lex the irp definition.
4539 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4543 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4544 // to hold the macro body with substitutions.
4545 SmallString<256> Buf;
4546 raw_svector_ostream OS(Buf);
4548 for (const MCAsmMacroArgument &Arg : A) {
4549 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4550 // This is undocumented, but GAS seems to support it.
4551 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4555 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4560 /// parseDirectiveIrpc
4561 /// ::= .irpc symbol,values
4562 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4563 MCAsmMacroParameter Parameter;
4565 if (parseIdentifier(Parameter.Name))
4566 return TokError("expected identifier in '.irpc' directive");
4568 if (Lexer.isNot(AsmToken::Comma))
4569 return TokError("expected comma in '.irpc' directive");
4573 MCAsmMacroArguments A;
4574 if (parseMacroArguments(nullptr, A))
4577 if (A.size() != 1 || A.front().size() != 1)
4578 return TokError("unexpected token in '.irpc' directive");
4580 // Eat the end of statement.
4583 // Lex the irpc definition.
4584 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4588 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4589 // to hold the macro body with substitutions.
4590 SmallString<256> Buf;
4591 raw_svector_ostream OS(Buf);
4593 StringRef Values = A.front().front().getString();
4594 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4595 MCAsmMacroArgument Arg;
4596 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4598 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4599 // This is undocumented, but GAS seems to support it.
4600 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4604 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4609 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4610 if (ActiveMacros.empty())
4611 return TokError("unmatched '.endr' directive");
4613 // The only .repl that should get here are the ones created by
4614 // instantiateMacroLikeBody.
4615 assert(getLexer().is(AsmToken::EndOfStatement));
4621 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4623 const MCExpr *Value;
4624 SMLoc ExprLoc = getLexer().getLoc();
4625 if (parseExpression(Value))
4627 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4629 return Error(ExprLoc, "unexpected expression in _emit");
4630 uint64_t IntValue = MCE->getValue();
4631 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
4632 return Error(ExprLoc, "literal value out of range for directive");
4634 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
4638 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4639 const MCExpr *Value;
4640 SMLoc ExprLoc = getLexer().getLoc();
4641 if (parseExpression(Value))
4643 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4645 return Error(ExprLoc, "unexpected expression in align");
4646 uint64_t IntValue = MCE->getValue();
4647 if (!isPowerOf2_64(IntValue))
4648 return Error(ExprLoc, "literal value not a power of two greater then zero");
4650 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
4654 // We are comparing pointers, but the pointers are relative to a single string.
4655 // Thus, this should always be deterministic.
4656 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4657 const AsmRewrite *AsmRewriteB) {
4658 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4660 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4663 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4664 // rewrite to the same location. Make sure the SizeDirective rewrite is
4665 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4666 // ensures the sort algorithm is stable.
4667 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4668 AsmRewritePrecedence[AsmRewriteB->Kind])
4671 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4672 AsmRewritePrecedence[AsmRewriteB->Kind])
4674 llvm_unreachable("Unstable rewrite sort.");
4677 bool AsmParser::parseMSInlineAsm(
4678 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4679 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4680 SmallVectorImpl<std::string> &Constraints,
4681 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4682 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4683 SmallVector<void *, 4> InputDecls;
4684 SmallVector<void *, 4> OutputDecls;
4685 SmallVector<bool, 4> InputDeclsAddressOf;
4686 SmallVector<bool, 4> OutputDeclsAddressOf;
4687 SmallVector<std::string, 4> InputConstraints;
4688 SmallVector<std::string, 4> OutputConstraints;
4689 SmallVector<unsigned, 4> ClobberRegs;
4691 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4696 // While we have input, parse each statement.
4697 unsigned InputIdx = 0;
4698 unsigned OutputIdx = 0;
4699 while (getLexer().isNot(AsmToken::Eof)) {
4700 ParseStatementInfo Info(&AsmStrRewrites);
4701 if (parseStatement(Info, &SI))
4704 if (Info.ParseError)
4707 if (Info.Opcode == ~0U)
4710 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4712 // Build the list of clobbers, outputs and inputs.
4713 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4714 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4717 if (Operand.isImm())
4720 // Register operand.
4721 if (Operand.isReg() && !Operand.needAddressOf() &&
4722 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4723 unsigned NumDefs = Desc.getNumDefs();
4725 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4726 ClobberRegs.push_back(Operand.getReg());
4730 // Expr/Input or Output.
4731 StringRef SymName = Operand.getSymName();
4732 if (SymName.empty())
4735 void *OpDecl = Operand.getOpDecl();
4739 bool isOutput = (i == 1) && Desc.mayStore();
4740 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4743 OutputDecls.push_back(OpDecl);
4744 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4745 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4746 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
4748 InputDecls.push_back(OpDecl);
4749 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4750 InputConstraints.push_back(Operand.getConstraint().str());
4751 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
4755 // Consider implicit defs to be clobbers. Think of cpuid and push.
4756 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4757 Desc.getNumImplicitDefs());
4758 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4761 // Set the number of Outputs and Inputs.
4762 NumOutputs = OutputDecls.size();
4763 NumInputs = InputDecls.size();
4765 // Set the unique clobbers.
4766 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4767 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4769 Clobbers.assign(ClobberRegs.size(), std::string());
4770 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4771 raw_string_ostream OS(Clobbers[I]);
4772 IP->printRegName(OS, ClobberRegs[I]);
4775 // Merge the various outputs and inputs. Output are expected first.
4776 if (NumOutputs || NumInputs) {
4777 unsigned NumExprs = NumOutputs + NumInputs;
4778 OpDecls.resize(NumExprs);
4779 Constraints.resize(NumExprs);
4780 for (unsigned i = 0; i < NumOutputs; ++i) {
4781 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4782 Constraints[i] = OutputConstraints[i];
4784 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4785 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4786 Constraints[j] = InputConstraints[i];
4790 // Build the IR assembly string.
4791 std::string AsmStringIR;
4792 raw_string_ostream OS(AsmStringIR);
4793 StringRef ASMString =
4794 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4795 const char *AsmStart = ASMString.begin();
4796 const char *AsmEnd = ASMString.end();
4797 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4798 for (const AsmRewrite &AR : AsmStrRewrites) {
4799 AsmRewriteKind Kind = AR.Kind;
4800 if (Kind == AOK_Delete)
4803 const char *Loc = AR.Loc.getPointer();
4804 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4806 // Emit everything up to the immediate/expression.
4807 if (unsigned Len = Loc - AsmStart)
4808 OS << StringRef(AsmStart, Len);
4810 // Skip the original expression.
4811 if (Kind == AOK_Skip) {
4812 AsmStart = Loc + AR.Len;
4816 unsigned AdditionalSkip = 0;
4817 // Rewrite expressions in $N notation.
4822 OS << "$$" << AR.Val;
4828 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4831 OS << '$' << InputIdx++;
4834 OS << '$' << OutputIdx++;
4836 case AOK_SizeDirective:
4839 case 8: OS << "byte ptr "; break;
4840 case 16: OS << "word ptr "; break;
4841 case 32: OS << "dword ptr "; break;
4842 case 64: OS << "qword ptr "; break;
4843 case 80: OS << "xword ptr "; break;
4844 case 128: OS << "xmmword ptr "; break;
4845 case 256: OS << "ymmword ptr "; break;
4852 // MS alignment directives are measured in bytes. If the native assembler
4853 // measures alignment in bytes, we can pass it straight through.
4855 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
4858 // Alignment is in log2 form, so print that instead and skip the original
4860 unsigned Val = AR.Val;
4862 assert(Val < 10 && "Expected alignment less then 2^10.");
4863 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4866 case AOK_DotOperator:
4867 // Insert the dot if the user omitted it.
4869 if (AsmStringIR.back() != '.')
4875 // Skip the original expression.
4876 AsmStart = Loc + AR.Len + AdditionalSkip;
4879 // Emit the remainder of the asm string.
4880 if (AsmStart != AsmEnd)
4881 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4883 AsmString = OS.str();
4888 namespace MCParserUtils {
4890 /// Returns whether the given symbol is used anywhere in the given expression,
4891 /// or subexpressions.
4892 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4893 switch (Value->getKind()) {
4894 case MCExpr::Binary: {
4895 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4896 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4897 isSymbolUsedInExpression(Sym, BE->getRHS());
4899 case MCExpr::Target:
4900 case MCExpr::Constant:
4902 case MCExpr::SymbolRef: {
4904 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4906 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4910 return isSymbolUsedInExpression(
4911 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4914 llvm_unreachable("Unknown expr kind!");
4917 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4918 MCAsmParser &Parser, MCSymbol *&Sym,
4919 const MCExpr *&Value) {
4920 MCAsmLexer &Lexer = Parser.getLexer();
4922 // FIXME: Use better location, we should use proper tokens.
4923 SMLoc EqualLoc = Lexer.getLoc();
4925 if (Parser.parseExpression(Value)) {
4926 Parser.TokError("missing expression");
4927 Parser.eatToEndOfStatement();
4931 // Note: we don't count b as used in "a = b". This is to allow
4935 if (Lexer.isNot(AsmToken::EndOfStatement))
4936 return Parser.TokError("unexpected token in assignment");
4938 // Eat the end of statement marker.
4941 // Validate that the LHS is allowed to be a variable (either it has not been
4942 // used as a symbol, or it is an absolute symbol).
4943 Sym = Parser.getContext().lookupSymbol(Name);
4945 // Diagnose assignment to a label.
4947 // FIXME: Diagnostics. Note the location of the definition as a label.
4948 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4949 if (isSymbolUsedInExpression(Sym, Value))
4950 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4951 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
4953 ; // Allow redefinitions of undefined symbols only used in directives.
4954 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4955 ; // Allow redefinitions of variables that haven't yet been used.
4956 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4957 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4958 else if (!Sym->isVariable())
4959 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4960 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4961 return Parser.Error(EqualLoc,
4962 "invalid reassignment of non-absolute variable '" +
4964 } else if (Name == ".") {
4965 Parser.getStreamer().emitValueToOffset(Value, 0);
4968 Sym = Parser.getContext().getOrCreateSymbol(Name);
4970 Sym->setRedefinable(allow_redef);
4975 } // namespace MCParserUtils
4978 /// \brief Create an MCAsmParser instance.
4979 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4980 MCStreamer &Out, const MCAsmInfo &MAI) {
4981 return new AsmParser(SM, C, Out, MAI);