1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
115 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
158 /// When generating dwarf for assembly source files we need to calculate the
159 /// logical line number based on the last parsed cpp hash file line comment
160 /// and current line. Since this is slow and messes up the SourceMgr's
161 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
162 SMLoc LastQueryIDLoc;
163 unsigned LastQueryBuffer;
164 unsigned LastQueryLine;
166 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
167 unsigned AssemblerDialect;
169 /// \brief is Darwin compatibility enabled?
172 /// \brief Are we parsing ms-style inline assembly?
173 bool ParsingInlineAsm;
176 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
177 const MCAsmInfo &MAI);
178 virtual ~AsmParser();
180 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
182 void addDirectiveHandler(StringRef Directive,
183 ExtensionDirectiveHandler Handler) override {
184 ExtensionDirectiveMap[Directive] = Handler;
188 /// @name MCAsmParser Interface
191 SourceMgr &getSourceManager() override { return SrcMgr; }
192 MCAsmLexer &getLexer() override { return Lexer; }
193 MCContext &getContext() override { return Ctx; }
194 MCStreamer &getStreamer() override { return Out; }
195 unsigned getAssemblerDialect() override {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 void setAssemblerDialect(unsigned i) override {
202 AssemblerDialect = i;
205 void Note(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = None) override;
207 bool Warning(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = None) override;
209 bool Error(SMLoc L, const Twine &Msg,
210 ArrayRef<SMRange> Ranges = None) override;
212 const AsmToken &Lex() override;
214 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
215 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
217 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
218 unsigned &NumOutputs, unsigned &NumInputs,
219 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
220 SmallVectorImpl<std::string> &Constraints,
221 SmallVectorImpl<std::string> &Clobbers,
222 const MCInstrInfo *MII, const MCInstPrinter *IP,
223 MCAsmParserSemaCallback &SI) override;
225 bool parseExpression(const MCExpr *&Res);
226 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
227 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
228 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
229 bool parseAbsoluteExpression(int64_t &Res) override;
231 /// \brief Parse an identifier or string (as a quoted identifier)
232 /// and set \p Res to the identifier contents.
233 bool parseIdentifier(StringRef &Res) override;
234 void eatToEndOfStatement() override;
236 void checkForValidSection() override;
241 bool parseStatement(ParseStatementInfo &Info,
242 MCAsmParserSemaCallback *SI);
243 void eatToEndOfLine();
244 bool parseCppHashLineFilenameComment(const SMLoc &L);
246 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
247 ArrayRef<MCAsmMacroParameter> Parameters);
248 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
249 ArrayRef<MCAsmMacroParameter> Parameters,
250 ArrayRef<MCAsmMacroArgument> A,
253 /// \brief Are macros enabled in the parser?
254 bool areMacrosEnabled() {return MacrosEnabledFlag;}
256 /// \brief Control a flag in the parser that enables or disables macros.
257 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
259 /// \brief Lookup a previously defined macro.
260 /// \param Name Macro name.
261 /// \returns Pointer to macro. NULL if no such macro was defined.
262 const MCAsmMacro* lookupMacro(StringRef Name);
264 /// \brief Define a new macro with the given name and information.
265 void defineMacro(StringRef Name, MCAsmMacro Macro);
267 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
268 void undefineMacro(StringRef Name);
270 /// \brief Are we inside a macro instantiation?
271 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
273 /// \brief Handle entry to macro instantiation.
275 /// \param M The macro.
276 /// \param NameLoc Instantiation location.
277 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
279 /// \brief Handle exit from macro instantiation.
280 void handleMacroExit();
282 /// \brief Extract AsmTokens for a macro argument.
283 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
285 /// \brief Parse all macro arguments for a given macro.
286 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
288 void printMacroInstantiations();
289 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
290 ArrayRef<SMRange> Ranges = None) const {
291 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
293 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
295 /// \brief Enter the specified file. This returns true on failure.
296 bool enterIncludeFile(const std::string &Filename);
298 /// \brief Process the specified file for the .incbin directive.
299 /// This returns true on failure.
300 bool processIncbinFile(const std::string &Filename);
302 /// \brief Reset the current lexer position to that given by \p Loc. The
303 /// current token is not set; clients should ensure Lex() is called
306 /// \param InBuffer If not 0, should be the known buffer id that contains the
308 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
310 /// \brief Parse up to the end of statement and a return the contents from the
311 /// current token until the end of the statement; the current token on exit
312 /// will be either the EndOfStatement or EOF.
313 StringRef parseStringToEndOfStatement() override;
315 /// \brief Parse until the end of a statement or a comma is encountered,
316 /// return the contents from the current token up to the end or comma.
317 StringRef parseStringToComma();
319 bool parseAssignment(StringRef Name, bool allow_redef,
320 bool NoDeadStrip = false);
322 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
323 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
324 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
326 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
328 // Generic (target and platform independent) directive parsing.
330 DK_NO_DIRECTIVE, // Placeholder
331 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
332 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
333 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
334 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
335 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
336 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
337 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
338 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
339 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
340 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
341 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
342 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
343 DK_ELSEIF, DK_ELSE, DK_ENDIF,
344 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
345 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
346 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
347 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
348 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
349 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
350 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
351 DK_MACROS_ON, DK_MACROS_OFF,
352 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
353 DK_SLEB128, DK_ULEB128,
354 DK_ERR, DK_ERROR, DK_WARNING,
358 /// \brief Maps directive name --> DirectiveKind enum, for
359 /// directives parsed by this class.
360 StringMap<DirectiveKind> DirectiveKindMap;
362 // ".ascii", ".asciz", ".string"
363 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
364 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
365 bool parseDirectiveOctaValue(); // ".octa"
366 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
367 bool parseDirectiveFill(); // ".fill"
368 bool parseDirectiveZero(); // ".zero"
369 // ".set", ".equ", ".equiv"
370 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
371 bool parseDirectiveOrg(); // ".org"
372 // ".align{,32}", ".p2align{,w,l}"
373 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
375 // ".file", ".line", ".loc", ".stabs"
376 bool parseDirectiveFile(SMLoc DirectiveLoc);
377 bool parseDirectiveLine();
378 bool parseDirectiveLoc();
379 bool parseDirectiveStabs();
382 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
383 bool parseDirectiveCFIWindowSave();
384 bool parseDirectiveCFISections();
385 bool parseDirectiveCFIStartProc();
386 bool parseDirectiveCFIEndProc();
387 bool parseDirectiveCFIDefCfaOffset();
388 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
389 bool parseDirectiveCFIAdjustCfaOffset();
390 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
391 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
394 bool parseDirectiveCFIRememberState();
395 bool parseDirectiveCFIRestoreState();
396 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIEscape();
399 bool parseDirectiveCFISignalFrame();
400 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
403 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
404 bool parseDirectiveExitMacro(StringRef Directive);
405 bool parseDirectiveEndMacro(StringRef Directive);
406 bool parseDirectiveMacro(SMLoc DirectiveLoc);
407 bool parseDirectiveMacrosOnOff(StringRef Directive);
409 // ".bundle_align_mode"
410 bool parseDirectiveBundleAlignMode();
412 bool parseDirectiveBundleLock();
414 bool parseDirectiveBundleUnlock();
417 bool parseDirectiveSpace(StringRef IDVal);
419 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
420 bool parseDirectiveLEB128(bool Signed);
422 /// \brief Parse a directive like ".globl" which
423 /// accepts a single symbol (which should be a label or an external).
424 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
426 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
428 bool parseDirectiveAbort(); // ".abort"
429 bool parseDirectiveInclude(); // ".include"
430 bool parseDirectiveIncbin(); // ".incbin"
432 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
433 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
434 // ".ifb" or ".ifnb", depending on ExpectBlank.
435 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
436 // ".ifc" or ".ifnc", depending on ExpectEqual.
437 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
439 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
440 // ".ifdef" or ".ifndef", depending on expect_defined
441 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
442 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
443 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
444 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
445 bool parseEscapedString(std::string &Data) override;
447 const MCExpr *applyModifierToExpr(const MCExpr *E,
448 MCSymbolRefExpr::VariantKind Variant);
450 // Macro-like directives
451 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
452 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
453 raw_svector_ostream &OS);
454 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
455 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
456 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
457 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
459 // "_emit" or "__emit"
460 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
464 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
467 bool parseDirectiveEnd(SMLoc DirectiveLoc);
469 // ".err" or ".error"
470 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
473 bool parseDirectiveWarning(SMLoc DirectiveLoc);
475 void initializeDirectiveKindMap();
481 extern MCAsmParserExtension *createDarwinAsmParser();
482 extern MCAsmParserExtension *createELFAsmParser();
483 extern MCAsmParserExtension *createCOFFAsmParser();
487 enum { DEFAULT_ADDRSPACE = 0 };
489 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
490 const MCAsmInfo &_MAI)
491 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
492 PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
493 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
494 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
495 // Save the old handler.
496 SavedDiagHandler = SrcMgr.getDiagHandler();
497 SavedDiagContext = SrcMgr.getDiagContext();
498 // Set our own handler which calls the saved handler.
499 SrcMgr.setDiagHandler(DiagHandler, this);
500 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
502 // Initialize the platform / file format parser.
503 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
504 case MCObjectFileInfo::IsCOFF:
505 PlatformParser.reset(createCOFFAsmParser());
507 case MCObjectFileInfo::IsMachO:
508 PlatformParser.reset(createDarwinAsmParser());
511 case MCObjectFileInfo::IsELF:
512 PlatformParser.reset(createELFAsmParser());
516 PlatformParser->Initialize(*this);
517 initializeDirectiveKindMap();
520 AsmParser::~AsmParser() {
521 assert((HadError || ActiveMacros.empty()) &&
522 "Unexpected active macro instantiation!");
525 void AsmParser::printMacroInstantiations() {
526 // Print the active macro instantiation stack.
527 for (std::vector<MacroInstantiation *>::const_reverse_iterator
528 it = ActiveMacros.rbegin(),
529 ie = ActiveMacros.rend();
531 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
532 "while in macro instantiation");
535 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
536 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
537 printMacroInstantiations();
540 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
541 if (getTargetParser().getTargetOptions().MCFatalWarnings)
542 return Error(L, Msg, Ranges);
543 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
544 printMacroInstantiations();
548 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
550 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
551 printMacroInstantiations();
555 bool AsmParser::enterIncludeFile(const std::string &Filename) {
556 std::string IncludedFile;
558 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
563 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
567 /// Process the specified .incbin file by searching for it in the include paths
568 /// then just emitting the byte contents of the file to the streamer. This
569 /// returns true on failure.
570 bool AsmParser::processIncbinFile(const std::string &Filename) {
571 std::string IncludedFile;
573 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
577 // Pick up the bytes from the file and emit them.
578 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
582 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
583 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
584 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
588 const AsmToken &AsmParser::Lex() {
589 const AsmToken *tok = &Lexer.Lex();
591 if (tok->is(AsmToken::Eof)) {
592 // If this is the end of an included file, pop the parent file off the
594 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
595 if (ParentIncludeLoc != SMLoc()) {
596 jumpToLoc(ParentIncludeLoc);
601 if (tok->is(AsmToken::Error))
602 Error(Lexer.getErrLoc(), Lexer.getErr());
607 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
608 // Create the initial section, if requested.
609 if (!NoInitialTextSection)
610 Out.InitSections(false);
616 AsmCond StartingCondState = TheCondState;
618 // If we are generating dwarf for assembly source files save the initial text
619 // section and generate a .file directive.
620 if (getContext().getGenDwarfForAssembly()) {
621 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
622 getStreamer().EmitLabel(SectionStartSym);
623 auto InsertResult = getContext().addGenDwarfSection(
624 getStreamer().getCurrentSection().first);
625 assert(InsertResult.second && ".text section should not have debug info yet");
626 InsertResult.first->second.first = SectionStartSym;
627 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
628 0, StringRef(), getContext().getMainFileName()));
631 // While we have input, parse each statement.
632 while (Lexer.isNot(AsmToken::Eof)) {
633 ParseStatementInfo Info;
634 if (!parseStatement(Info, nullptr))
637 // We had an error, validate that one was emitted and recover by skipping to
639 assert(HadError && "Parse statement returned an error, but none emitted!");
640 eatToEndOfStatement();
643 if (TheCondState.TheCond != StartingCondState.TheCond ||
644 TheCondState.Ignore != StartingCondState.Ignore)
645 return TokError("unmatched .ifs or .elses");
647 // Check to see there are no empty DwarfFile slots.
648 const auto &LineTables = getContext().getMCDwarfLineTables();
649 if (!LineTables.empty()) {
651 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
652 if (File.Name.empty() && Index != 0)
653 TokError("unassigned file number: " + Twine(Index) +
654 " for .file directives");
659 // Check to see that all assembler local symbols were actually defined.
660 // Targets that don't do subsections via symbols may not want this, though,
661 // so conservatively exclude them. Only do this if we're finalizing, though,
662 // as otherwise we won't necessarilly have seen everything yet.
663 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
664 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
665 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
668 MCSymbol *Sym = i->getValue();
669 // Variable symbols may not be marked as defined, so check those
670 // explicitly. If we know it's a variable, we have a definition for
671 // the purposes of this check.
672 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
673 // FIXME: We would really like to refer back to where the symbol was
674 // first referenced for a source location. We need to add something
675 // to track that. Currently, we just point to the end of the file.
677 getLexer().getLoc(), SourceMgr::DK_Error,
678 "assembler local symbol '" + Sym->getName() + "' not defined");
682 // Finalize the output stream if there are no errors and if the client wants
684 if (!HadError && !NoFinalize)
690 void AsmParser::checkForValidSection() {
691 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
692 TokError("expected section directive before assembly directive");
693 Out.InitSections(false);
697 /// \brief Throw away the rest of the line for testing purposes.
698 void AsmParser::eatToEndOfStatement() {
699 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
703 if (Lexer.is(AsmToken::EndOfStatement))
707 StringRef AsmParser::parseStringToEndOfStatement() {
708 const char *Start = getTok().getLoc().getPointer();
710 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
713 const char *End = getTok().getLoc().getPointer();
714 return StringRef(Start, End - Start);
717 StringRef AsmParser::parseStringToComma() {
718 const char *Start = getTok().getLoc().getPointer();
720 while (Lexer.isNot(AsmToken::EndOfStatement) &&
721 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
724 const char *End = getTok().getLoc().getPointer();
725 return StringRef(Start, End - Start);
728 /// \brief Parse a paren expression and return it.
729 /// NOTE: This assumes the leading '(' has already been consumed.
731 /// parenexpr ::= expr)
733 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
734 if (parseExpression(Res))
736 if (Lexer.isNot(AsmToken::RParen))
737 return TokError("expected ')' in parentheses expression");
738 EndLoc = Lexer.getTok().getEndLoc();
743 /// \brief Parse a bracket expression and return it.
744 /// NOTE: This assumes the leading '[' has already been consumed.
746 /// bracketexpr ::= expr]
748 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
749 if (parseExpression(Res))
751 if (Lexer.isNot(AsmToken::RBrac))
752 return TokError("expected ']' in brackets expression");
753 EndLoc = Lexer.getTok().getEndLoc();
758 /// \brief Parse a primary expression and return it.
759 /// primaryexpr ::= (parenexpr
760 /// primaryexpr ::= symbol
761 /// primaryexpr ::= number
762 /// primaryexpr ::= '.'
763 /// primaryexpr ::= ~,+,- primaryexpr
764 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
765 SMLoc FirstTokenLoc = getLexer().getLoc();
766 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
767 switch (FirstTokenKind) {
769 return TokError("unknown token in expression");
770 // If we have an error assume that we've already handled it.
771 case AsmToken::Error:
773 case AsmToken::Exclaim:
774 Lex(); // Eat the operator.
775 if (parsePrimaryExpr(Res, EndLoc))
777 Res = MCUnaryExpr::CreateLNot(Res, getContext());
779 case AsmToken::Dollar:
781 case AsmToken::String:
782 case AsmToken::Identifier: {
783 StringRef Identifier;
784 if (parseIdentifier(Identifier)) {
785 if (FirstTokenKind == AsmToken::Dollar) {
786 if (Lexer.getMAI().getDollarIsPC()) {
787 // This is a '$' reference, which references the current PC. Emit a
788 // temporary label to the streamer and refer to it.
789 MCSymbol *Sym = Ctx.CreateTempSymbol();
791 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
793 EndLoc = FirstTokenLoc;
796 return Error(FirstTokenLoc, "invalid token in expression");
799 // Parse symbol variant
800 std::pair<StringRef, StringRef> Split;
801 if (!MAI.useParensForSymbolVariant()) {
802 if (FirstTokenKind == AsmToken::String) {
803 if (Lexer.is(AsmToken::At)) {
804 Lexer.Lex(); // eat @
805 SMLoc AtLoc = getLexer().getLoc();
807 if (parseIdentifier(VName))
808 return Error(AtLoc, "expected symbol variant after '@'");
810 Split = std::make_pair(Identifier, VName);
813 Split = Identifier.split('@');
815 } else if (Lexer.is(AsmToken::LParen)) {
816 Lexer.Lex(); // eat (
818 parseIdentifier(VName);
819 if (Lexer.isNot(AsmToken::RParen)) {
820 return Error(Lexer.getTok().getLoc(),
821 "unexpected token in variant, expected ')'");
823 Lexer.Lex(); // eat )
824 Split = std::make_pair(Identifier, VName);
827 EndLoc = SMLoc::getFromPointer(Identifier.end());
829 // This is a symbol reference.
830 StringRef SymbolName = Identifier;
831 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
833 // Lookup the symbol variant if used.
834 if (Split.second.size()) {
835 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
836 if (Variant != MCSymbolRefExpr::VK_Invalid) {
837 SymbolName = Split.first;
838 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
839 Variant = MCSymbolRefExpr::VK_None;
841 return Error(SMLoc::getFromPointer(Split.second.begin()),
842 "invalid variant '" + Split.second + "'");
846 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
848 // If this is an absolute variable reference, substitute it now to preserve
849 // semantics in the face of reassignment.
850 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
852 return Error(EndLoc, "unexpected modifier on variable reference");
854 Res = Sym->getVariableValue();
858 // Otherwise create a symbol ref.
859 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
862 case AsmToken::BigNum:
863 return TokError("literal value out of range for directive");
864 case AsmToken::Integer: {
865 SMLoc Loc = getTok().getLoc();
866 int64_t IntVal = getTok().getIntVal();
867 Res = MCConstantExpr::Create(IntVal, getContext());
868 EndLoc = Lexer.getTok().getEndLoc();
870 // Look for 'b' or 'f' following an Integer as a directional label
871 if (Lexer.getKind() == AsmToken::Identifier) {
872 StringRef IDVal = getTok().getString();
873 // Lookup the symbol variant if used.
874 std::pair<StringRef, StringRef> Split = IDVal.split('@');
875 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
876 if (Split.first.size() != IDVal.size()) {
877 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
878 if (Variant == MCSymbolRefExpr::VK_Invalid)
879 return TokError("invalid variant '" + Split.second + "'");
882 if (IDVal == "f" || IDVal == "b") {
884 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
885 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
886 if (IDVal == "b" && Sym->isUndefined())
887 return Error(Loc, "invalid reference to undefined symbol");
888 EndLoc = Lexer.getTok().getEndLoc();
889 Lex(); // Eat identifier.
894 case AsmToken::Real: {
895 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
896 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
897 Res = MCConstantExpr::Create(IntVal, getContext());
898 EndLoc = Lexer.getTok().getEndLoc();
902 case AsmToken::Dot: {
903 // This is a '.' reference, which references the current PC. Emit a
904 // temporary label to the streamer and refer to it.
905 MCSymbol *Sym = Ctx.CreateTempSymbol();
907 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
908 EndLoc = Lexer.getTok().getEndLoc();
909 Lex(); // Eat identifier.
912 case AsmToken::LParen:
913 Lex(); // Eat the '('.
914 return parseParenExpr(Res, EndLoc);
915 case AsmToken::LBrac:
916 if (!PlatformParser->HasBracketExpressions())
917 return TokError("brackets expression not supported on this target");
918 Lex(); // Eat the '['.
919 return parseBracketExpr(Res, EndLoc);
920 case AsmToken::Minus:
921 Lex(); // Eat the operator.
922 if (parsePrimaryExpr(Res, EndLoc))
924 Res = MCUnaryExpr::CreateMinus(Res, getContext());
927 Lex(); // Eat the operator.
928 if (parsePrimaryExpr(Res, EndLoc))
930 Res = MCUnaryExpr::CreatePlus(Res, getContext());
932 case AsmToken::Tilde:
933 Lex(); // Eat the operator.
934 if (parsePrimaryExpr(Res, EndLoc))
936 Res = MCUnaryExpr::CreateNot(Res, getContext());
941 bool AsmParser::parseExpression(const MCExpr *&Res) {
943 return parseExpression(Res, EndLoc);
947 AsmParser::applyModifierToExpr(const MCExpr *E,
948 MCSymbolRefExpr::VariantKind Variant) {
949 // Ask the target implementation about this expression first.
950 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
953 // Recurse over the given expression, rebuilding it to apply the given variant
954 // if there is exactly one symbol.
955 switch (E->getKind()) {
957 case MCExpr::Constant:
960 case MCExpr::SymbolRef: {
961 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
963 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
964 TokError("invalid variant on expression '" + getTok().getIdentifier() +
965 "' (already modified)");
969 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
972 case MCExpr::Unary: {
973 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
974 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
977 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
980 case MCExpr::Binary: {
981 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
982 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
983 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
993 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
997 llvm_unreachable("Invalid expression kind!");
1000 /// \brief Parse an expression and return it.
1002 /// expr ::= expr &&,|| expr -> lowest.
1003 /// expr ::= expr |,^,&,! expr
1004 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1005 /// expr ::= expr <<,>> expr
1006 /// expr ::= expr +,- expr
1007 /// expr ::= expr *,/,% expr -> highest.
1008 /// expr ::= primaryexpr
1010 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1011 // Parse the expression.
1013 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1016 // As a special case, we support 'a op b @ modifier' by rewriting the
1017 // expression to include the modifier. This is inefficient, but in general we
1018 // expect users to use 'a@modifier op b'.
1019 if (Lexer.getKind() == AsmToken::At) {
1022 if (Lexer.isNot(AsmToken::Identifier))
1023 return TokError("unexpected symbol modifier following '@'");
1025 MCSymbolRefExpr::VariantKind Variant =
1026 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1027 if (Variant == MCSymbolRefExpr::VK_Invalid)
1028 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1030 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1032 return TokError("invalid modifier '" + getTok().getIdentifier() +
1033 "' (no symbols present)");
1040 // Try to constant fold it up front, if possible.
1042 if (Res->EvaluateAsAbsolute(Value))
1043 Res = MCConstantExpr::Create(Value, getContext());
1048 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1050 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1053 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1056 SMLoc StartLoc = Lexer.getLoc();
1057 if (parseExpression(Expr))
1060 if (!Expr->EvaluateAsAbsolute(Res))
1061 return Error(StartLoc, "expected absolute expression");
1066 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1067 MCBinaryExpr::Opcode &Kind) {
1070 return 0; // not a binop.
1072 // Lowest Precedence: &&, ||
1073 case AsmToken::AmpAmp:
1074 Kind = MCBinaryExpr::LAnd;
1076 case AsmToken::PipePipe:
1077 Kind = MCBinaryExpr::LOr;
1080 // Low Precedence: |, &, ^
1082 // FIXME: gas seems to support '!' as an infix operator?
1083 case AsmToken::Pipe:
1084 Kind = MCBinaryExpr::Or;
1086 case AsmToken::Caret:
1087 Kind = MCBinaryExpr::Xor;
1090 Kind = MCBinaryExpr::And;
1093 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1094 case AsmToken::EqualEqual:
1095 Kind = MCBinaryExpr::EQ;
1097 case AsmToken::ExclaimEqual:
1098 case AsmToken::LessGreater:
1099 Kind = MCBinaryExpr::NE;
1101 case AsmToken::Less:
1102 Kind = MCBinaryExpr::LT;
1104 case AsmToken::LessEqual:
1105 Kind = MCBinaryExpr::LTE;
1107 case AsmToken::Greater:
1108 Kind = MCBinaryExpr::GT;
1110 case AsmToken::GreaterEqual:
1111 Kind = MCBinaryExpr::GTE;
1114 // Intermediate Precedence: <<, >>
1115 case AsmToken::LessLess:
1116 Kind = MCBinaryExpr::Shl;
1118 case AsmToken::GreaterGreater:
1119 Kind = MCBinaryExpr::Shr;
1122 // High Intermediate Precedence: +, -
1123 case AsmToken::Plus:
1124 Kind = MCBinaryExpr::Add;
1126 case AsmToken::Minus:
1127 Kind = MCBinaryExpr::Sub;
1130 // Highest Precedence: *, /, %
1131 case AsmToken::Star:
1132 Kind = MCBinaryExpr::Mul;
1134 case AsmToken::Slash:
1135 Kind = MCBinaryExpr::Div;
1137 case AsmToken::Percent:
1138 Kind = MCBinaryExpr::Mod;
1143 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1144 /// Res contains the LHS of the expression on input.
1145 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1148 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1149 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1151 // If the next token is lower precedence than we are allowed to eat, return
1152 // successfully with what we ate already.
1153 if (TokPrec < Precedence)
1158 // Eat the next primary expression.
1160 if (parsePrimaryExpr(RHS, EndLoc))
1163 // If BinOp binds less tightly with RHS than the operator after RHS, let
1164 // the pending operator take RHS as its LHS.
1165 MCBinaryExpr::Opcode Dummy;
1166 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1167 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1170 // Merge LHS and RHS according to operator.
1171 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1176 /// ::= EndOfStatement
1177 /// ::= Label* Directive ...Operands... EndOfStatement
1178 /// ::= Label* Identifier OperandList* EndOfStatement
1179 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1180 MCAsmParserSemaCallback *SI) {
1181 if (Lexer.is(AsmToken::EndOfStatement)) {
1187 // Statements always start with an identifier or are a full line comment.
1188 AsmToken ID = getTok();
1189 SMLoc IDLoc = ID.getLoc();
1191 int64_t LocalLabelVal = -1;
1192 // A full line comment is a '#' as the first token.
1193 if (Lexer.is(AsmToken::Hash))
1194 return parseCppHashLineFilenameComment(IDLoc);
1196 // Allow an integer followed by a ':' as a directional local label.
1197 if (Lexer.is(AsmToken::Integer)) {
1198 LocalLabelVal = getTok().getIntVal();
1199 if (LocalLabelVal < 0) {
1200 if (!TheCondState.Ignore)
1201 return TokError("unexpected token at start of statement");
1204 IDVal = getTok().getString();
1205 Lex(); // Consume the integer token to be used as an identifier token.
1206 if (Lexer.getKind() != AsmToken::Colon) {
1207 if (!TheCondState.Ignore)
1208 return TokError("unexpected token at start of statement");
1211 } else if (Lexer.is(AsmToken::Dot)) {
1212 // Treat '.' as a valid identifier in this context.
1215 } else if (parseIdentifier(IDVal)) {
1216 if (!TheCondState.Ignore)
1217 return TokError("unexpected token at start of statement");
1221 // Handle conditional assembly here before checking for skipping. We
1222 // have to do this so that .endif isn't skipped in a ".if 0" block for
1224 StringMap<DirectiveKind>::const_iterator DirKindIt =
1225 DirectiveKindMap.find(IDVal);
1226 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1228 : DirKindIt->getValue();
1239 return parseDirectiveIf(IDLoc, DirKind);
1241 return parseDirectiveIfb(IDLoc, true);
1243 return parseDirectiveIfb(IDLoc, false);
1245 return parseDirectiveIfc(IDLoc, true);
1247 return parseDirectiveIfeqs(IDLoc);
1249 return parseDirectiveIfc(IDLoc, false);
1251 return parseDirectiveIfdef(IDLoc, true);
1254 return parseDirectiveIfdef(IDLoc, false);
1256 return parseDirectiveElseIf(IDLoc);
1258 return parseDirectiveElse(IDLoc);
1260 return parseDirectiveEndIf(IDLoc);
1263 // Ignore the statement if in the middle of inactive conditional
1265 if (TheCondState.Ignore) {
1266 eatToEndOfStatement();
1270 // FIXME: Recurse on local labels?
1272 // See what kind of statement we have.
1273 switch (Lexer.getKind()) {
1274 case AsmToken::Colon: {
1275 checkForValidSection();
1277 // identifier ':' -> Label.
1280 // Diagnose attempt to use '.' as a label.
1282 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1284 // Diagnose attempt to use a variable as a label.
1286 // FIXME: Diagnostics. Note the location of the definition as a label.
1287 // FIXME: This doesn't diagnose assignment to a symbol which has been
1288 // implicitly marked as external.
1290 if (LocalLabelVal == -1) {
1291 if (ParsingInlineAsm && SI) {
1292 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1293 assert(RewrittenLabel.size() && "We should have an internal name here.");
1294 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1295 IDVal.size(), RewrittenLabel));
1296 IDVal = RewrittenLabel;
1298 Sym = getContext().GetOrCreateSymbol(IDVal);
1300 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1301 if (!Sym->isUndefined() || Sym->isVariable())
1302 return Error(IDLoc, "invalid symbol redefinition");
1305 if (!ParsingInlineAsm)
1308 // If we are generating dwarf for assembly source files then gather the
1309 // info to make a dwarf label entry for this label if needed.
1310 if (getContext().getGenDwarfForAssembly())
1311 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1314 getTargetParser().onLabelParsed(Sym);
1316 // Consume any end of statement token, if present, to avoid spurious
1317 // AddBlankLine calls().
1318 if (Lexer.is(AsmToken::EndOfStatement)) {
1320 if (Lexer.is(AsmToken::Eof))
1327 case AsmToken::Equal:
1328 // identifier '=' ... -> assignment statement
1331 return parseAssignment(IDVal, true);
1333 default: // Normal instruction or directive.
1337 // If macros are enabled, check to see if this is a macro instantiation.
1338 if (areMacrosEnabled())
1339 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1340 return handleMacroEntry(M, IDLoc);
1343 // Otherwise, we have a normal instruction or directive.
1345 // Directives start with "."
1346 if (IDVal[0] == '.' && IDVal != ".") {
1347 // There are several entities interested in parsing directives:
1349 // 1. The target-specific assembly parser. Some directives are target
1350 // specific or may potentially behave differently on certain targets.
1351 // 2. Asm parser extensions. For example, platform-specific parsers
1352 // (like the ELF parser) register themselves as extensions.
1353 // 3. The generic directive parser implemented by this class. These are
1354 // all the directives that behave in a target and platform independent
1355 // manner, or at least have a default behavior that's shared between
1356 // all targets and platforms.
1358 // First query the target-specific parser. It will return 'true' if it
1359 // isn't interested in this directive.
1360 if (!getTargetParser().ParseDirective(ID))
1363 // Next, check the extension directive map to see if any extension has
1364 // registered itself to parse this directive.
1365 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1366 ExtensionDirectiveMap.lookup(IDVal);
1368 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1370 // Finally, if no one else is interested in this directive, it must be
1371 // generic and familiar to this class.
1377 return parseDirectiveSet(IDVal, true);
1379 return parseDirectiveSet(IDVal, false);
1381 return parseDirectiveAscii(IDVal, false);
1384 return parseDirectiveAscii(IDVal, true);
1386 return parseDirectiveValue(1);
1390 return parseDirectiveValue(2);
1394 return parseDirectiveValue(4);
1397 return parseDirectiveValue(8);
1399 return parseDirectiveOctaValue();
1402 return parseDirectiveRealValue(APFloat::IEEEsingle);
1404 return parseDirectiveRealValue(APFloat::IEEEdouble);
1406 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1407 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1410 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1411 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1414 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1416 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1418 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1420 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1422 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1424 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1426 return parseDirectiveOrg();
1428 return parseDirectiveFill();
1430 return parseDirectiveZero();
1432 eatToEndOfStatement(); // .extern is the default, ignore it.
1436 return parseDirectiveSymbolAttribute(MCSA_Global);
1437 case DK_LAZY_REFERENCE:
1438 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1439 case DK_NO_DEAD_STRIP:
1440 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1441 case DK_SYMBOL_RESOLVER:
1442 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1443 case DK_PRIVATE_EXTERN:
1444 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1446 return parseDirectiveSymbolAttribute(MCSA_Reference);
1447 case DK_WEAK_DEFINITION:
1448 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1449 case DK_WEAK_REFERENCE:
1450 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1451 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1452 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1455 return parseDirectiveComm(/*IsLocal=*/false);
1457 return parseDirectiveComm(/*IsLocal=*/true);
1459 return parseDirectiveAbort();
1461 return parseDirectiveInclude();
1463 return parseDirectiveIncbin();
1466 return TokError(Twine(IDVal) + " not supported yet");
1468 return parseDirectiveRept(IDLoc, IDVal);
1470 return parseDirectiveIrp(IDLoc);
1472 return parseDirectiveIrpc(IDLoc);
1474 return parseDirectiveEndr(IDLoc);
1475 case DK_BUNDLE_ALIGN_MODE:
1476 return parseDirectiveBundleAlignMode();
1477 case DK_BUNDLE_LOCK:
1478 return parseDirectiveBundleLock();
1479 case DK_BUNDLE_UNLOCK:
1480 return parseDirectiveBundleUnlock();
1482 return parseDirectiveLEB128(true);
1484 return parseDirectiveLEB128(false);
1487 return parseDirectiveSpace(IDVal);
1489 return parseDirectiveFile(IDLoc);
1491 return parseDirectiveLine();
1493 return parseDirectiveLoc();
1495 return parseDirectiveStabs();
1496 case DK_CFI_SECTIONS:
1497 return parseDirectiveCFISections();
1498 case DK_CFI_STARTPROC:
1499 return parseDirectiveCFIStartProc();
1500 case DK_CFI_ENDPROC:
1501 return parseDirectiveCFIEndProc();
1502 case DK_CFI_DEF_CFA:
1503 return parseDirectiveCFIDefCfa(IDLoc);
1504 case DK_CFI_DEF_CFA_OFFSET:
1505 return parseDirectiveCFIDefCfaOffset();
1506 case DK_CFI_ADJUST_CFA_OFFSET:
1507 return parseDirectiveCFIAdjustCfaOffset();
1508 case DK_CFI_DEF_CFA_REGISTER:
1509 return parseDirectiveCFIDefCfaRegister(IDLoc);
1511 return parseDirectiveCFIOffset(IDLoc);
1512 case DK_CFI_REL_OFFSET:
1513 return parseDirectiveCFIRelOffset(IDLoc);
1514 case DK_CFI_PERSONALITY:
1515 return parseDirectiveCFIPersonalityOrLsda(true);
1517 return parseDirectiveCFIPersonalityOrLsda(false);
1518 case DK_CFI_REMEMBER_STATE:
1519 return parseDirectiveCFIRememberState();
1520 case DK_CFI_RESTORE_STATE:
1521 return parseDirectiveCFIRestoreState();
1522 case DK_CFI_SAME_VALUE:
1523 return parseDirectiveCFISameValue(IDLoc);
1524 case DK_CFI_RESTORE:
1525 return parseDirectiveCFIRestore(IDLoc);
1527 return parseDirectiveCFIEscape();
1528 case DK_CFI_SIGNAL_FRAME:
1529 return parseDirectiveCFISignalFrame();
1530 case DK_CFI_UNDEFINED:
1531 return parseDirectiveCFIUndefined(IDLoc);
1532 case DK_CFI_REGISTER:
1533 return parseDirectiveCFIRegister(IDLoc);
1534 case DK_CFI_WINDOW_SAVE:
1535 return parseDirectiveCFIWindowSave();
1538 return parseDirectiveMacrosOnOff(IDVal);
1540 return parseDirectiveMacro(IDLoc);
1542 return parseDirectiveExitMacro(IDVal);
1545 return parseDirectiveEndMacro(IDVal);
1547 return parseDirectivePurgeMacro(IDLoc);
1549 return parseDirectiveEnd(IDLoc);
1551 return parseDirectiveError(IDLoc, false);
1553 return parseDirectiveError(IDLoc, true);
1555 return parseDirectiveWarning(IDLoc);
1558 return Error(IDLoc, "unknown directive");
1561 // __asm _emit or __asm __emit
1562 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1563 IDVal == "_EMIT" || IDVal == "__EMIT"))
1564 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1567 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1568 return parseDirectiveMSAlign(IDLoc, Info);
1570 checkForValidSection();
1572 // Canonicalize the opcode to lower case.
1573 std::string OpcodeStr = IDVal.lower();
1574 ParseInstructionInfo IInfo(Info.AsmRewrites);
1575 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1576 Info.ParsedOperands);
1577 Info.ParseError = HadError;
1579 // Dump the parsed representation, if requested.
1580 if (getShowParsedOperands()) {
1581 SmallString<256> Str;
1582 raw_svector_ostream OS(Str);
1583 OS << "parsed instruction: [";
1584 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1587 Info.ParsedOperands[i]->print(OS);
1591 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1594 // If we are generating dwarf for the current section then generate a .loc
1595 // directive for the instruction.
1596 if (!HadError && getContext().getGenDwarfForAssembly() &&
1597 getContext().getGenDwarfSectionSyms().count(
1598 getStreamer().getCurrentSection().first)) {
1600 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1602 // If we previously parsed a cpp hash file line comment then make sure the
1603 // current Dwarf File is for the CppHashFilename if not then emit the
1604 // Dwarf File table for it and adjust the line number for the .loc.
1605 if (CppHashFilename.size() != 0) {
1606 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1607 0, StringRef(), CppHashFilename);
1608 getContext().setGenDwarfFileNumber(FileNumber);
1610 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1611 // cache with the different Loc from the call above we save the last
1612 // info we queried here with SrcMgr.FindLineNumber().
1613 unsigned CppHashLocLineNo;
1614 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1615 CppHashLocLineNo = LastQueryLine;
1617 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1618 LastQueryLine = CppHashLocLineNo;
1619 LastQueryIDLoc = CppHashLoc;
1620 LastQueryBuffer = CppHashBuf;
1622 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1625 getStreamer().EmitDwarfLocDirective(
1626 getContext().getGenDwarfFileNumber(), Line, 0,
1627 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1631 // If parsing succeeded, match the instruction.
1634 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1635 Info.ParsedOperands, Out,
1636 ErrorInfo, ParsingInlineAsm);
1639 // Don't skip the rest of the line, the instruction parser is responsible for
1644 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1645 /// since they may not be able to be tokenized to get to the end of line token.
1646 void AsmParser::eatToEndOfLine() {
1647 if (!Lexer.is(AsmToken::EndOfStatement))
1648 Lexer.LexUntilEndOfLine();
1653 /// parseCppHashLineFilenameComment as this:
1654 /// ::= # number "filename"
1655 /// or just as a full line comment if it doesn't have a number and a string.
1656 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1657 Lex(); // Eat the hash token.
1659 if (getLexer().isNot(AsmToken::Integer)) {
1660 // Consume the line since in cases it is not a well-formed line directive,
1661 // as if were simply a full line comment.
1666 int64_t LineNumber = getTok().getIntVal();
1669 if (getLexer().isNot(AsmToken::String)) {
1674 StringRef Filename = getTok().getString();
1675 // Get rid of the enclosing quotes.
1676 Filename = Filename.substr(1, Filename.size() - 2);
1678 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1680 CppHashFilename = Filename;
1681 CppHashLineNumber = LineNumber;
1682 CppHashBuf = CurBuffer;
1684 // Ignore any trailing characters, they're just comment.
1689 /// \brief will use the last parsed cpp hash line filename comment
1690 /// for the Filename and LineNo if any in the diagnostic.
1691 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1692 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1693 raw_ostream &OS = errs();
1695 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1696 const SMLoc &DiagLoc = Diag.getLoc();
1697 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1698 unsigned CppHashBuf =
1699 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1701 // Like SourceMgr::printMessage() we need to print the include stack if any
1702 // before printing the message.
1703 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1704 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1705 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1706 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1707 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1710 // If we have not parsed a cpp hash line filename comment or the source
1711 // manager changed or buffer changed (like in a nested include) then just
1712 // print the normal diagnostic using its Filename and LineNo.
1713 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1714 DiagBuf != CppHashBuf) {
1715 if (Parser->SavedDiagHandler)
1716 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1718 Diag.print(nullptr, OS);
1722 // Use the CppHashFilename and calculate a line number based on the
1723 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1725 const std::string &Filename = Parser->CppHashFilename;
1727 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1728 int CppHashLocLineNo =
1729 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1731 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1733 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1734 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1735 Diag.getLineContents(), Diag.getRanges());
1737 if (Parser->SavedDiagHandler)
1738 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1740 NewDiag.print(nullptr, OS);
1743 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1744 // difference being that that function accepts '@' as part of identifiers and
1745 // we can't do that. AsmLexer.cpp should probably be changed to handle
1746 // '@' as a special case when needed.
1747 static bool isIdentifierChar(char c) {
1748 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1752 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1753 ArrayRef<MCAsmMacroParameter> Parameters,
1754 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1755 unsigned NParameters = Parameters.size();
1756 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1757 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1758 return Error(L, "Wrong number of arguments");
1760 // A macro without parameters is handled differently on Darwin:
1761 // gas accepts no arguments and does no substitutions
1762 while (!Body.empty()) {
1763 // Scan for the next substitution.
1764 std::size_t End = Body.size(), Pos = 0;
1765 for (; Pos != End; ++Pos) {
1766 // Check for a substitution or escape.
1767 if (IsDarwin && !NParameters) {
1768 // This macro has no parameters, look for $0, $1, etc.
1769 if (Body[Pos] != '$' || Pos + 1 == End)
1772 char Next = Body[Pos + 1];
1773 if (Next == '$' || Next == 'n' ||
1774 isdigit(static_cast<unsigned char>(Next)))
1777 // This macro has parameters, look for \foo, \bar, etc.
1778 if (Body[Pos] == '\\' && Pos + 1 != End)
1784 OS << Body.slice(0, Pos);
1786 // Check if we reached the end.
1790 if (IsDarwin && !NParameters) {
1791 switch (Body[Pos + 1]) {
1797 // $n => number of arguments
1802 // $[0-9] => argument
1804 // Missing arguments are ignored.
1805 unsigned Index = Body[Pos + 1] - '0';
1806 if (Index >= A.size())
1809 // Otherwise substitute with the token values, with spaces eliminated.
1810 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1811 ie = A[Index].end();
1813 OS << it->getString();
1819 unsigned I = Pos + 1;
1820 while (isIdentifierChar(Body[I]) && I + 1 != End)
1823 const char *Begin = Body.data() + Pos + 1;
1824 StringRef Argument(Begin, I - (Pos + 1));
1826 for (; Index < NParameters; ++Index)
1827 if (Parameters[Index].Name == Argument)
1830 if (Index == NParameters) {
1831 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1834 OS << '\\' << Argument;
1838 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1839 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1840 ie = A[Index].end();
1842 // We expect no quotes around the string's contents when
1843 // parsing for varargs.
1844 if (it->getKind() != AsmToken::String || VarargParameter)
1845 OS << it->getString();
1847 OS << it->getStringContents();
1849 Pos += 1 + Argument.size();
1852 // Update the scan point.
1853 Body = Body.substr(Pos);
1859 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1860 size_t CondStackDepth)
1861 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1862 CondStackDepth(CondStackDepth) {}
1864 static bool isOperator(AsmToken::TokenKind kind) {
1868 case AsmToken::Plus:
1869 case AsmToken::Minus:
1870 case AsmToken::Tilde:
1871 case AsmToken::Slash:
1872 case AsmToken::Star:
1874 case AsmToken::Equal:
1875 case AsmToken::EqualEqual:
1876 case AsmToken::Pipe:
1877 case AsmToken::PipePipe:
1878 case AsmToken::Caret:
1880 case AsmToken::AmpAmp:
1881 case AsmToken::Exclaim:
1882 case AsmToken::ExclaimEqual:
1883 case AsmToken::Percent:
1884 case AsmToken::Less:
1885 case AsmToken::LessEqual:
1886 case AsmToken::LessLess:
1887 case AsmToken::LessGreater:
1888 case AsmToken::Greater:
1889 case AsmToken::GreaterEqual:
1890 case AsmToken::GreaterGreater:
1896 class AsmLexerSkipSpaceRAII {
1898 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1899 Lexer.setSkipSpace(SkipSpace);
1902 ~AsmLexerSkipSpaceRAII() {
1903 Lexer.setSkipSpace(true);
1911 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1914 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1915 StringRef Str = parseStringToEndOfStatement();
1916 MA.push_back(AsmToken(AsmToken::String, Str));
1921 unsigned ParenLevel = 0;
1922 unsigned AddTokens = 0;
1924 // Darwin doesn't use spaces to delmit arguments.
1925 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1928 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1929 return TokError("unexpected token in macro instantiation");
1931 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1934 if (Lexer.is(AsmToken::Space)) {
1935 Lex(); // Eat spaces
1937 // Spaces can delimit parameters, but could also be part an expression.
1938 // If the token after a space is an operator, add the token and the next
1939 // one into this argument
1941 if (isOperator(Lexer.getKind())) {
1942 // Check to see whether the token is used as an operator,
1943 // or part of an identifier
1944 const char *NextChar = getTok().getEndLoc().getPointer();
1945 if (*NextChar == ' ')
1949 if (!AddTokens && ParenLevel == 0) {
1955 // handleMacroEntry relies on not advancing the lexer here
1956 // to be able to fill in the remaining default parameter values
1957 if (Lexer.is(AsmToken::EndOfStatement))
1960 // Adjust the current parentheses level.
1961 if (Lexer.is(AsmToken::LParen))
1963 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1966 // Append the token to the current argument list.
1967 MA.push_back(getTok());
1973 if (ParenLevel != 0)
1974 return TokError("unbalanced parentheses in macro argument");
1978 // Parse the macro instantiation arguments.
1979 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1980 MCAsmMacroArguments &A) {
1981 const unsigned NParameters = M ? M->Parameters.size() : 0;
1982 bool NamedParametersFound = false;
1983 SmallVector<SMLoc, 4> FALocs;
1985 A.resize(NParameters);
1986 FALocs.resize(NParameters);
1988 // Parse two kinds of macro invocations:
1989 // - macros defined without any parameters accept an arbitrary number of them
1990 // - macros defined with parameters accept at most that many of them
1991 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1992 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1994 SMLoc IDLoc = Lexer.getLoc();
1995 MCAsmMacroParameter FA;
1997 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1998 if (parseIdentifier(FA.Name)) {
1999 Error(IDLoc, "invalid argument identifier for formal argument");
2000 eatToEndOfStatement();
2004 if (!Lexer.is(AsmToken::Equal)) {
2005 TokError("expected '=' after formal parameter identifier");
2006 eatToEndOfStatement();
2011 NamedParametersFound = true;
2014 if (NamedParametersFound && FA.Name.empty()) {
2015 Error(IDLoc, "cannot mix positional and keyword arguments");
2016 eatToEndOfStatement();
2020 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2021 if (parseMacroArgument(FA.Value, Vararg))
2024 unsigned PI = Parameter;
2025 if (!FA.Name.empty()) {
2027 for (FAI = 0; FAI < NParameters; ++FAI)
2028 if (M->Parameters[FAI].Name == FA.Name)
2031 if (FAI >= NParameters) {
2032 assert(M && "expected macro to be defined");
2034 "parameter named '" + FA.Name + "' does not exist for macro '" +
2041 if (!FA.Value.empty()) {
2046 if (FALocs.size() <= PI)
2047 FALocs.resize(PI + 1);
2049 FALocs[PI] = Lexer.getLoc();
2052 // At the end of the statement, fill in remaining arguments that have
2053 // default values. If there aren't any, then the next argument is
2054 // required but missing
2055 if (Lexer.is(AsmToken::EndOfStatement)) {
2056 bool Failure = false;
2057 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2058 if (A[FAI].empty()) {
2059 if (M->Parameters[FAI].Required) {
2060 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2061 "missing value for required parameter "
2062 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2066 if (!M->Parameters[FAI].Value.empty())
2067 A[FAI] = M->Parameters[FAI].Value;
2073 if (Lexer.is(AsmToken::Comma))
2077 return TokError("too many positional arguments");
2080 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2081 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2082 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2085 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2086 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2089 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2091 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2092 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2093 // this, although we should protect against infinite loops.
2094 if (ActiveMacros.size() == 20)
2095 return TokError("macros cannot be nested more than 20 levels deep");
2097 MCAsmMacroArguments A;
2098 if (parseMacroArguments(M, A))
2101 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2102 // to hold the macro body with substitutions.
2103 SmallString<256> Buf;
2104 StringRef Body = M->Body;
2105 raw_svector_ostream OS(Buf);
2107 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2110 // We include the .endmacro in the buffer as our cue to exit the macro
2112 OS << ".endmacro\n";
2114 std::unique_ptr<MemoryBuffer> Instantiation =
2115 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2117 // Create the macro instantiation object and add to the current macro
2118 // instantiation stack.
2119 MacroInstantiation *MI = new MacroInstantiation(
2120 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2121 ActiveMacros.push_back(MI);
2123 // Jump to the macro instantiation and prime the lexer.
2124 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2125 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2131 void AsmParser::handleMacroExit() {
2132 // Jump to the EndOfStatement we should return to, and consume it.
2133 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2136 // Pop the instantiation entry.
2137 delete ActiveMacros.back();
2138 ActiveMacros.pop_back();
2141 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2142 switch (Value->getKind()) {
2143 case MCExpr::Binary: {
2144 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2145 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2147 case MCExpr::Target:
2148 case MCExpr::Constant:
2150 case MCExpr::SymbolRef: {
2152 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2154 return isUsedIn(Sym, S.getVariableValue());
2158 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2161 llvm_unreachable("Unknown expr kind!");
2164 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2166 // FIXME: Use better location, we should use proper tokens.
2167 SMLoc EqualLoc = Lexer.getLoc();
2169 const MCExpr *Value;
2170 if (parseExpression(Value))
2173 // Note: we don't count b as used in "a = b". This is to allow
2177 if (Lexer.isNot(AsmToken::EndOfStatement))
2178 return TokError("unexpected token in assignment");
2180 // Eat the end of statement marker.
2183 // Validate that the LHS is allowed to be a variable (either it has not been
2184 // used as a symbol, or it is an absolute symbol).
2185 MCSymbol *Sym = getContext().LookupSymbol(Name);
2187 // Diagnose assignment to a label.
2189 // FIXME: Diagnostics. Note the location of the definition as a label.
2190 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2191 if (isUsedIn(Sym, Value))
2192 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2193 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2194 ; // Allow redefinitions of undefined symbols only used in directives.
2195 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2196 ; // Allow redefinitions of variables that haven't yet been used.
2197 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2198 return Error(EqualLoc, "redefinition of '" + Name + "'");
2199 else if (!Sym->isVariable())
2200 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2201 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2202 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2205 // Don't count these checks as uses.
2206 Sym->setUsed(false);
2207 } else if (Name == ".") {
2208 if (Out.EmitValueToOffset(Value, 0)) {
2209 Error(EqualLoc, "expected absolute expression");
2210 eatToEndOfStatement();
2214 Sym = getContext().GetOrCreateSymbol(Name);
2216 // Do the assignment.
2217 Out.EmitAssignment(Sym, Value);
2219 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2224 /// parseIdentifier:
2227 bool AsmParser::parseIdentifier(StringRef &Res) {
2228 // The assembler has relaxed rules for accepting identifiers, in particular we
2229 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2230 // separate tokens. At this level, we have already lexed so we cannot (currently)
2231 // handle this as a context dependent token, instead we detect adjacent tokens
2232 // and return the combined identifier.
2233 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2234 SMLoc PrefixLoc = getLexer().getLoc();
2236 // Consume the prefix character, and check for a following identifier.
2238 if (Lexer.isNot(AsmToken::Identifier))
2241 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2242 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2245 // Construct the joined identifier and consume the token.
2247 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2252 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2255 Res = getTok().getIdentifier();
2257 Lex(); // Consume the identifier token.
2262 /// parseDirectiveSet:
2263 /// ::= .equ identifier ',' expression
2264 /// ::= .equiv identifier ',' expression
2265 /// ::= .set identifier ',' expression
2266 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2269 if (parseIdentifier(Name))
2270 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2272 if (getLexer().isNot(AsmToken::Comma))
2273 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2276 return parseAssignment(Name, allow_redef, true);
2279 bool AsmParser::parseEscapedString(std::string &Data) {
2280 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2283 StringRef Str = getTok().getStringContents();
2284 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2285 if (Str[i] != '\\') {
2290 // Recognize escaped characters. Note that this escape semantics currently
2291 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2294 return TokError("unexpected backslash at end of string");
2296 // Recognize octal sequences.
2297 if ((unsigned)(Str[i] - '0') <= 7) {
2298 // Consume up to three octal characters.
2299 unsigned Value = Str[i] - '0';
2301 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2303 Value = Value * 8 + (Str[i] - '0');
2305 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2307 Value = Value * 8 + (Str[i] - '0');
2312 return TokError("invalid octal escape sequence (out of range)");
2314 Data += (unsigned char)Value;
2318 // Otherwise recognize individual escapes.
2321 // Just reject invalid escape sequences for now.
2322 return TokError("invalid escape sequence (unrecognized character)");
2324 case 'b': Data += '\b'; break;
2325 case 'f': Data += '\f'; break;
2326 case 'n': Data += '\n'; break;
2327 case 'r': Data += '\r'; break;
2328 case 't': Data += '\t'; break;
2329 case '"': Data += '"'; break;
2330 case '\\': Data += '\\'; break;
2337 /// parseDirectiveAscii:
2338 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2339 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2340 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2341 checkForValidSection();
2344 if (getLexer().isNot(AsmToken::String))
2345 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2348 if (parseEscapedString(Data))
2351 getStreamer().EmitBytes(Data);
2353 getStreamer().EmitBytes(StringRef("\0", 1));
2357 if (getLexer().is(AsmToken::EndOfStatement))
2360 if (getLexer().isNot(AsmToken::Comma))
2361 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2370 /// parseDirectiveValue
2371 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2372 bool AsmParser::parseDirectiveValue(unsigned Size) {
2373 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2374 checkForValidSection();
2377 const MCExpr *Value;
2378 SMLoc ExprLoc = getLexer().getLoc();
2379 if (parseExpression(Value))
2382 // Special case constant expressions to match code generator.
2383 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2384 assert(Size <= 8 && "Invalid size");
2385 uint64_t IntValue = MCE->getValue();
2386 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2387 return Error(ExprLoc, "literal value out of range for directive");
2388 getStreamer().EmitIntValue(IntValue, Size);
2390 getStreamer().EmitValue(Value, Size, ExprLoc);
2392 if (getLexer().is(AsmToken::EndOfStatement))
2395 // FIXME: Improve diagnostic.
2396 if (getLexer().isNot(AsmToken::Comma))
2397 return TokError("unexpected token in directive");
2406 /// ParseDirectiveOctaValue
2407 /// ::= .octa [ hexconstant (, hexconstant)* ]
2408 bool AsmParser::parseDirectiveOctaValue() {
2409 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2410 checkForValidSection();
2413 if (Lexer.getKind() == AsmToken::Error)
2415 if (Lexer.getKind() != AsmToken::Integer &&
2416 Lexer.getKind() != AsmToken::BigNum)
2417 return TokError("unknown token in expression");
2419 SMLoc ExprLoc = getLexer().getLoc();
2420 APInt IntValue = getTok().getAPIntVal();
2424 if (IntValue.isIntN(64)) {
2426 lo = IntValue.getZExtValue();
2427 } else if (IntValue.isIntN(128)) {
2428 // It might actually have more than 128 bits, but the top ones are zero.
2429 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2430 lo = IntValue.getLoBits(64).getZExtValue();
2432 return Error(ExprLoc, "literal value out of range for directive");
2434 if (MAI.isLittleEndian()) {
2435 getStreamer().EmitIntValue(lo, 8);
2436 getStreamer().EmitIntValue(hi, 8);
2438 getStreamer().EmitIntValue(hi, 8);
2439 getStreamer().EmitIntValue(lo, 8);
2442 if (getLexer().is(AsmToken::EndOfStatement))
2445 // FIXME: Improve diagnostic.
2446 if (getLexer().isNot(AsmToken::Comma))
2447 return TokError("unexpected token in directive");
2456 /// parseDirectiveRealValue
2457 /// ::= (.single | .double) [ expression (, expression)* ]
2458 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2459 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2460 checkForValidSection();
2463 // We don't truly support arithmetic on floating point expressions, so we
2464 // have to manually parse unary prefixes.
2466 if (getLexer().is(AsmToken::Minus)) {
2469 } else if (getLexer().is(AsmToken::Plus))
2472 if (getLexer().isNot(AsmToken::Integer) &&
2473 getLexer().isNot(AsmToken::Real) &&
2474 getLexer().isNot(AsmToken::Identifier))
2475 return TokError("unexpected token in directive");
2477 // Convert to an APFloat.
2478 APFloat Value(Semantics);
2479 StringRef IDVal = getTok().getString();
2480 if (getLexer().is(AsmToken::Identifier)) {
2481 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2482 Value = APFloat::getInf(Semantics);
2483 else if (!IDVal.compare_lower("nan"))
2484 Value = APFloat::getNaN(Semantics, false, ~0);
2486 return TokError("invalid floating point literal");
2487 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2488 APFloat::opInvalidOp)
2489 return TokError("invalid floating point literal");
2493 // Consume the numeric token.
2496 // Emit the value as an integer.
2497 APInt AsInt = Value.bitcastToAPInt();
2498 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2499 AsInt.getBitWidth() / 8);
2501 if (getLexer().is(AsmToken::EndOfStatement))
2504 if (getLexer().isNot(AsmToken::Comma))
2505 return TokError("unexpected token in directive");
2514 /// parseDirectiveZero
2515 /// ::= .zero expression
2516 bool AsmParser::parseDirectiveZero() {
2517 checkForValidSection();
2520 if (parseAbsoluteExpression(NumBytes))
2524 if (getLexer().is(AsmToken::Comma)) {
2526 if (parseAbsoluteExpression(Val))
2530 if (getLexer().isNot(AsmToken::EndOfStatement))
2531 return TokError("unexpected token in '.zero' directive");
2535 getStreamer().EmitFill(NumBytes, Val);
2540 /// parseDirectiveFill
2541 /// ::= .fill expression [ , expression [ , expression ] ]
2542 bool AsmParser::parseDirectiveFill() {
2543 checkForValidSection();
2545 SMLoc RepeatLoc = getLexer().getLoc();
2547 if (parseAbsoluteExpression(NumValues))
2550 if (NumValues < 0) {
2552 "'.fill' directive with negative repeat count has no effect");
2556 int64_t FillSize = 1;
2557 int64_t FillExpr = 0;
2559 SMLoc SizeLoc, ExprLoc;
2560 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2561 if (getLexer().isNot(AsmToken::Comma))
2562 return TokError("unexpected token in '.fill' directive");
2565 SizeLoc = getLexer().getLoc();
2566 if (parseAbsoluteExpression(FillSize))
2569 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2570 if (getLexer().isNot(AsmToken::Comma))
2571 return TokError("unexpected token in '.fill' directive");
2574 ExprLoc = getLexer().getLoc();
2575 if (parseAbsoluteExpression(FillExpr))
2578 if (getLexer().isNot(AsmToken::EndOfStatement))
2579 return TokError("unexpected token in '.fill' directive");
2586 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2590 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2594 if (!isUInt<32>(FillExpr) && FillSize > 4)
2595 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2597 if (NumValues > 0) {
2598 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2599 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2600 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2601 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2602 if (NonZeroFillSize < FillSize)
2603 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2610 /// parseDirectiveOrg
2611 /// ::= .org expression [ , expression ]
2612 bool AsmParser::parseDirectiveOrg() {
2613 checkForValidSection();
2615 const MCExpr *Offset;
2616 SMLoc Loc = getTok().getLoc();
2617 if (parseExpression(Offset))
2620 // Parse optional fill expression.
2621 int64_t FillExpr = 0;
2622 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2623 if (getLexer().isNot(AsmToken::Comma))
2624 return TokError("unexpected token in '.org' directive");
2627 if (parseAbsoluteExpression(FillExpr))
2630 if (getLexer().isNot(AsmToken::EndOfStatement))
2631 return TokError("unexpected token in '.org' directive");
2636 // Only limited forms of relocatable expressions are accepted here, it
2637 // has to be relative to the current section. The streamer will return
2638 // 'true' if the expression wasn't evaluatable.
2639 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2640 return Error(Loc, "expected assembly-time absolute expression");
2645 /// parseDirectiveAlign
2646 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2647 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2648 checkForValidSection();
2650 SMLoc AlignmentLoc = getLexer().getLoc();
2652 if (parseAbsoluteExpression(Alignment))
2656 bool HasFillExpr = false;
2657 int64_t FillExpr = 0;
2658 int64_t MaxBytesToFill = 0;
2659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2660 if (getLexer().isNot(AsmToken::Comma))
2661 return TokError("unexpected token in directive");
2664 // The fill expression can be omitted while specifying a maximum number of
2665 // alignment bytes, e.g:
2667 if (getLexer().isNot(AsmToken::Comma)) {
2669 if (parseAbsoluteExpression(FillExpr))
2673 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2674 if (getLexer().isNot(AsmToken::Comma))
2675 return TokError("unexpected token in directive");
2678 MaxBytesLoc = getLexer().getLoc();
2679 if (parseAbsoluteExpression(MaxBytesToFill))
2682 if (getLexer().isNot(AsmToken::EndOfStatement))
2683 return TokError("unexpected token in directive");
2692 // Compute alignment in bytes.
2694 // FIXME: Diagnose overflow.
2695 if (Alignment >= 32) {
2696 Error(AlignmentLoc, "invalid alignment value");
2700 Alignment = 1ULL << Alignment;
2702 // Reject alignments that aren't a power of two, for gas compatibility.
2703 if (!isPowerOf2_64(Alignment))
2704 Error(AlignmentLoc, "alignment must be a power of 2");
2707 // Diagnose non-sensical max bytes to align.
2708 if (MaxBytesLoc.isValid()) {
2709 if (MaxBytesToFill < 1) {
2710 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2711 "many bytes, ignoring maximum bytes expression");
2715 if (MaxBytesToFill >= Alignment) {
2716 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2722 // Check whether we should use optimal code alignment for this .align
2724 const MCSection *Section = getStreamer().getCurrentSection().first;
2725 assert(Section && "must have section to emit alignment");
2726 bool UseCodeAlign = Section->UseCodeAlign();
2727 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2728 ValueSize == 1 && UseCodeAlign) {
2729 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2731 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2732 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2739 /// parseDirectiveFile
2740 /// ::= .file [number] filename
2741 /// ::= .file number directory filename
2742 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2743 // FIXME: I'm not sure what this is.
2744 int64_t FileNumber = -1;
2745 SMLoc FileNumberLoc = getLexer().getLoc();
2746 if (getLexer().is(AsmToken::Integer)) {
2747 FileNumber = getTok().getIntVal();
2751 return TokError("file number less than one");
2754 if (getLexer().isNot(AsmToken::String))
2755 return TokError("unexpected token in '.file' directive");
2757 // Usually the directory and filename together, otherwise just the directory.
2758 // Allow the strings to have escaped octal character sequence.
2759 std::string Path = getTok().getString();
2760 if (parseEscapedString(Path))
2764 StringRef Directory;
2766 std::string FilenameData;
2767 if (getLexer().is(AsmToken::String)) {
2768 if (FileNumber == -1)
2769 return TokError("explicit path specified, but no file number");
2770 if (parseEscapedString(FilenameData))
2772 Filename = FilenameData;
2779 if (getLexer().isNot(AsmToken::EndOfStatement))
2780 return TokError("unexpected token in '.file' directive");
2782 if (FileNumber == -1)
2783 getStreamer().EmitFileDirective(Filename);
2785 if (getContext().getGenDwarfForAssembly() == true)
2787 "input can't have .file dwarf directives when -g is "
2788 "used to generate dwarf debug info for assembly code");
2790 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2792 Error(FileNumberLoc, "file number already allocated");
2798 /// parseDirectiveLine
2799 /// ::= .line [number]
2800 bool AsmParser::parseDirectiveLine() {
2801 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2802 if (getLexer().isNot(AsmToken::Integer))
2803 return TokError("unexpected token in '.line' directive");
2805 int64_t LineNumber = getTok().getIntVal();
2809 // FIXME: Do something with the .line.
2812 if (getLexer().isNot(AsmToken::EndOfStatement))
2813 return TokError("unexpected token in '.line' directive");
2818 /// parseDirectiveLoc
2819 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2820 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2821 /// The first number is a file number, must have been previously assigned with
2822 /// a .file directive, the second number is the line number and optionally the
2823 /// third number is a column position (zero if not specified). The remaining
2824 /// optional items are .loc sub-directives.
2825 bool AsmParser::parseDirectiveLoc() {
2826 if (getLexer().isNot(AsmToken::Integer))
2827 return TokError("unexpected token in '.loc' directive");
2828 int64_t FileNumber = getTok().getIntVal();
2830 return TokError("file number less than one in '.loc' directive");
2831 if (!getContext().isValidDwarfFileNumber(FileNumber))
2832 return TokError("unassigned file number in '.loc' directive");
2835 int64_t LineNumber = 0;
2836 if (getLexer().is(AsmToken::Integer)) {
2837 LineNumber = getTok().getIntVal();
2839 return TokError("line number less than zero in '.loc' directive");
2843 int64_t ColumnPos = 0;
2844 if (getLexer().is(AsmToken::Integer)) {
2845 ColumnPos = getTok().getIntVal();
2847 return TokError("column position less than zero in '.loc' directive");
2851 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2853 int64_t Discriminator = 0;
2854 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2856 if (getLexer().is(AsmToken::EndOfStatement))
2860 SMLoc Loc = getTok().getLoc();
2861 if (parseIdentifier(Name))
2862 return TokError("unexpected token in '.loc' directive");
2864 if (Name == "basic_block")
2865 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2866 else if (Name == "prologue_end")
2867 Flags |= DWARF2_FLAG_PROLOGUE_END;
2868 else if (Name == "epilogue_begin")
2869 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2870 else if (Name == "is_stmt") {
2871 Loc = getTok().getLoc();
2872 const MCExpr *Value;
2873 if (parseExpression(Value))
2875 // The expression must be the constant 0 or 1.
2876 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2877 int Value = MCE->getValue();
2879 Flags &= ~DWARF2_FLAG_IS_STMT;
2880 else if (Value == 1)
2881 Flags |= DWARF2_FLAG_IS_STMT;
2883 return Error(Loc, "is_stmt value not 0 or 1");
2885 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2887 } else if (Name == "isa") {
2888 Loc = getTok().getLoc();
2889 const MCExpr *Value;
2890 if (parseExpression(Value))
2892 // The expression must be a constant greater or equal to 0.
2893 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2894 int Value = MCE->getValue();
2896 return Error(Loc, "isa number less than zero");
2899 return Error(Loc, "isa number not a constant value");
2901 } else if (Name == "discriminator") {
2902 if (parseAbsoluteExpression(Discriminator))
2905 return Error(Loc, "unknown sub-directive in '.loc' directive");
2908 if (getLexer().is(AsmToken::EndOfStatement))
2913 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2914 Isa, Discriminator, StringRef());
2919 /// parseDirectiveStabs
2920 /// ::= .stabs string, number, number, number
2921 bool AsmParser::parseDirectiveStabs() {
2922 return TokError("unsupported directive '.stabs'");
2925 /// parseDirectiveCFISections
2926 /// ::= .cfi_sections section [, section]
2927 bool AsmParser::parseDirectiveCFISections() {
2932 if (parseIdentifier(Name))
2933 return TokError("Expected an identifier");
2935 if (Name == ".eh_frame")
2937 else if (Name == ".debug_frame")
2940 if (getLexer().is(AsmToken::Comma)) {
2943 if (parseIdentifier(Name))
2944 return TokError("Expected an identifier");
2946 if (Name == ".eh_frame")
2948 else if (Name == ".debug_frame")
2952 getStreamer().EmitCFISections(EH, Debug);
2956 /// parseDirectiveCFIStartProc
2957 /// ::= .cfi_startproc [simple]
2958 bool AsmParser::parseDirectiveCFIStartProc() {
2960 if (getLexer().isNot(AsmToken::EndOfStatement))
2961 if (parseIdentifier(Simple) || Simple != "simple")
2962 return TokError("unexpected token in .cfi_startproc directive");
2964 getStreamer().EmitCFIStartProc(!Simple.empty());
2968 /// parseDirectiveCFIEndProc
2969 /// ::= .cfi_endproc
2970 bool AsmParser::parseDirectiveCFIEndProc() {
2971 getStreamer().EmitCFIEndProc();
2975 /// \brief parse register name or number.
2976 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2977 SMLoc DirectiveLoc) {
2980 if (getLexer().isNot(AsmToken::Integer)) {
2981 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2983 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2985 return parseAbsoluteExpression(Register);
2990 /// parseDirectiveCFIDefCfa
2991 /// ::= .cfi_def_cfa register, offset
2992 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2993 int64_t Register = 0;
2994 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2997 if (getLexer().isNot(AsmToken::Comma))
2998 return TokError("unexpected token in directive");
3002 if (parseAbsoluteExpression(Offset))
3005 getStreamer().EmitCFIDefCfa(Register, Offset);
3009 /// parseDirectiveCFIDefCfaOffset
3010 /// ::= .cfi_def_cfa_offset offset
3011 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3013 if (parseAbsoluteExpression(Offset))
3016 getStreamer().EmitCFIDefCfaOffset(Offset);
3020 /// parseDirectiveCFIRegister
3021 /// ::= .cfi_register register, register
3022 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3023 int64_t Register1 = 0;
3024 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3027 if (getLexer().isNot(AsmToken::Comma))
3028 return TokError("unexpected token in directive");
3031 int64_t Register2 = 0;
3032 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3035 getStreamer().EmitCFIRegister(Register1, Register2);
3039 /// parseDirectiveCFIWindowSave
3040 /// ::= .cfi_window_save
3041 bool AsmParser::parseDirectiveCFIWindowSave() {
3042 getStreamer().EmitCFIWindowSave();
3046 /// parseDirectiveCFIAdjustCfaOffset
3047 /// ::= .cfi_adjust_cfa_offset adjustment
3048 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3049 int64_t Adjustment = 0;
3050 if (parseAbsoluteExpression(Adjustment))
3053 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3057 /// parseDirectiveCFIDefCfaRegister
3058 /// ::= .cfi_def_cfa_register register
3059 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3060 int64_t Register = 0;
3061 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3064 getStreamer().EmitCFIDefCfaRegister(Register);
3068 /// parseDirectiveCFIOffset
3069 /// ::= .cfi_offset register, offset
3070 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3071 int64_t Register = 0;
3074 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3077 if (getLexer().isNot(AsmToken::Comma))
3078 return TokError("unexpected token in directive");
3081 if (parseAbsoluteExpression(Offset))
3084 getStreamer().EmitCFIOffset(Register, Offset);
3088 /// parseDirectiveCFIRelOffset
3089 /// ::= .cfi_rel_offset register, offset
3090 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3091 int64_t Register = 0;
3093 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3096 if (getLexer().isNot(AsmToken::Comma))
3097 return TokError("unexpected token in directive");
3101 if (parseAbsoluteExpression(Offset))
3104 getStreamer().EmitCFIRelOffset(Register, Offset);
3108 static bool isValidEncoding(int64_t Encoding) {
3109 if (Encoding & ~0xff)
3112 if (Encoding == dwarf::DW_EH_PE_omit)
3115 const unsigned Format = Encoding & 0xf;
3116 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3117 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3118 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3119 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3122 const unsigned Application = Encoding & 0x70;
3123 if (Application != dwarf::DW_EH_PE_absptr &&
3124 Application != dwarf::DW_EH_PE_pcrel)
3130 /// parseDirectiveCFIPersonalityOrLsda
3131 /// IsPersonality true for cfi_personality, false for cfi_lsda
3132 /// ::= .cfi_personality encoding, [symbol_name]
3133 /// ::= .cfi_lsda encoding, [symbol_name]
3134 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3135 int64_t Encoding = 0;
3136 if (parseAbsoluteExpression(Encoding))
3138 if (Encoding == dwarf::DW_EH_PE_omit)
3141 if (!isValidEncoding(Encoding))
3142 return TokError("unsupported encoding.");
3144 if (getLexer().isNot(AsmToken::Comma))
3145 return TokError("unexpected token in directive");
3149 if (parseIdentifier(Name))
3150 return TokError("expected identifier in directive");
3152 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3155 getStreamer().EmitCFIPersonality(Sym, Encoding);
3157 getStreamer().EmitCFILsda(Sym, Encoding);
3161 /// parseDirectiveCFIRememberState
3162 /// ::= .cfi_remember_state
3163 bool AsmParser::parseDirectiveCFIRememberState() {
3164 getStreamer().EmitCFIRememberState();
3168 /// parseDirectiveCFIRestoreState
3169 /// ::= .cfi_remember_state
3170 bool AsmParser::parseDirectiveCFIRestoreState() {
3171 getStreamer().EmitCFIRestoreState();
3175 /// parseDirectiveCFISameValue
3176 /// ::= .cfi_same_value register
3177 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3178 int64_t Register = 0;
3180 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3183 getStreamer().EmitCFISameValue(Register);
3187 /// parseDirectiveCFIRestore
3188 /// ::= .cfi_restore register
3189 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3190 int64_t Register = 0;
3191 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3194 getStreamer().EmitCFIRestore(Register);
3198 /// parseDirectiveCFIEscape
3199 /// ::= .cfi_escape expression[,...]
3200 bool AsmParser::parseDirectiveCFIEscape() {
3203 if (parseAbsoluteExpression(CurrValue))
3206 Values.push_back((uint8_t)CurrValue);
3208 while (getLexer().is(AsmToken::Comma)) {
3211 if (parseAbsoluteExpression(CurrValue))
3214 Values.push_back((uint8_t)CurrValue);
3217 getStreamer().EmitCFIEscape(Values);
3221 /// parseDirectiveCFISignalFrame
3222 /// ::= .cfi_signal_frame
3223 bool AsmParser::parseDirectiveCFISignalFrame() {
3224 if (getLexer().isNot(AsmToken::EndOfStatement))
3225 return Error(getLexer().getLoc(),
3226 "unexpected token in '.cfi_signal_frame'");
3228 getStreamer().EmitCFISignalFrame();
3232 /// parseDirectiveCFIUndefined
3233 /// ::= .cfi_undefined register
3234 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3235 int64_t Register = 0;
3237 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3240 getStreamer().EmitCFIUndefined(Register);
3244 /// parseDirectiveMacrosOnOff
3247 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3248 if (getLexer().isNot(AsmToken::EndOfStatement))
3249 return Error(getLexer().getLoc(),
3250 "unexpected token in '" + Directive + "' directive");
3252 setMacrosEnabled(Directive == ".macros_on");
3256 /// parseDirectiveMacro
3257 /// ::= .macro name[,] [parameters]
3258 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3260 if (parseIdentifier(Name))
3261 return TokError("expected identifier in '.macro' directive");
3263 if (getLexer().is(AsmToken::Comma))
3266 MCAsmMacroParameters Parameters;
3267 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3269 if (Parameters.size() && Parameters.back().Vararg)
3270 return Error(Lexer.getLoc(),
3271 "Vararg parameter '" + Parameters.back().Name +
3272 "' should be last one in the list of parameters.");
3274 MCAsmMacroParameter Parameter;
3275 if (parseIdentifier(Parameter.Name))
3276 return TokError("expected identifier in '.macro' directive");
3278 if (Lexer.is(AsmToken::Colon)) {
3279 Lex(); // consume ':'
3282 StringRef Qualifier;
3284 QualLoc = Lexer.getLoc();
3285 if (parseIdentifier(Qualifier))
3286 return Error(QualLoc, "missing parameter qualifier for "
3287 "'" + Parameter.Name + "' in macro '" + Name + "'");
3289 if (Qualifier == "req")
3290 Parameter.Required = true;
3291 else if (Qualifier == "vararg")
3292 Parameter.Vararg = true;
3294 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3295 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3298 if (getLexer().is(AsmToken::Equal)) {
3303 ParamLoc = Lexer.getLoc();
3304 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3307 if (Parameter.Required)
3308 Warning(ParamLoc, "pointless default value for required parameter "
3309 "'" + Parameter.Name + "' in macro '" + Name + "'");
3312 Parameters.push_back(std::move(Parameter));
3314 if (getLexer().is(AsmToken::Comma))
3318 // Eat the end of statement.
3321 AsmToken EndToken, StartToken = getTok();
3322 unsigned MacroDepth = 0;
3324 // Lex the macro definition.
3326 // Check whether we have reached the end of the file.
3327 if (getLexer().is(AsmToken::Eof))
3328 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3330 // Otherwise, check whether we have reach the .endmacro.
3331 if (getLexer().is(AsmToken::Identifier)) {
3332 if (getTok().getIdentifier() == ".endm" ||
3333 getTok().getIdentifier() == ".endmacro") {
3334 if (MacroDepth == 0) { // Outermost macro.
3335 EndToken = getTok();
3337 if (getLexer().isNot(AsmToken::EndOfStatement))
3338 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3342 // Otherwise we just found the end of an inner macro.
3345 } else if (getTok().getIdentifier() == ".macro") {
3346 // We allow nested macros. Those aren't instantiated until the outermost
3347 // macro is expanded so just ignore them for now.
3352 // Otherwise, scan til the end of the statement.
3353 eatToEndOfStatement();
3356 if (lookupMacro(Name)) {
3357 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3360 const char *BodyStart = StartToken.getLoc().getPointer();
3361 const char *BodyEnd = EndToken.getLoc().getPointer();
3362 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3363 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3364 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3368 /// checkForBadMacro
3370 /// With the support added for named parameters there may be code out there that
3371 /// is transitioning from positional parameters. In versions of gas that did
3372 /// not support named parameters they would be ignored on the macro definition.
3373 /// But to support both styles of parameters this is not possible so if a macro
3374 /// definition has named parameters but does not use them and has what appears
3375 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3376 /// warning that the positional parameter found in body which have no effect.
3377 /// Hoping the developer will either remove the named parameters from the macro
3378 /// definition so the positional parameters get used if that was what was
3379 /// intended or change the macro to use the named parameters. It is possible
3380 /// this warning will trigger when the none of the named parameters are used
3381 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3382 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3384 ArrayRef<MCAsmMacroParameter> Parameters) {
3385 // If this macro is not defined with named parameters the warning we are
3386 // checking for here doesn't apply.
3387 unsigned NParameters = Parameters.size();
3388 if (NParameters == 0)
3391 bool NamedParametersFound = false;
3392 bool PositionalParametersFound = false;
3394 // Look at the body of the macro for use of both the named parameters and what
3395 // are likely to be positional parameters. This is what expandMacro() is
3396 // doing when it finds the parameters in the body.
3397 while (!Body.empty()) {
3398 // Scan for the next possible parameter.
3399 std::size_t End = Body.size(), Pos = 0;
3400 for (; Pos != End; ++Pos) {
3401 // Check for a substitution or escape.
3402 // This macro is defined with parameters, look for \foo, \bar, etc.
3403 if (Body[Pos] == '\\' && Pos + 1 != End)
3406 // This macro should have parameters, but look for $0, $1, ..., $n too.
3407 if (Body[Pos] != '$' || Pos + 1 == End)
3409 char Next = Body[Pos + 1];
3410 if (Next == '$' || Next == 'n' ||
3411 isdigit(static_cast<unsigned char>(Next)))
3415 // Check if we reached the end.
3419 if (Body[Pos] == '$') {
3420 switch (Body[Pos + 1]) {
3425 // $n => number of arguments
3427 PositionalParametersFound = true;
3430 // $[0-9] => argument
3432 PositionalParametersFound = true;
3438 unsigned I = Pos + 1;
3439 while (isIdentifierChar(Body[I]) && I + 1 != End)
3442 const char *Begin = Body.data() + Pos + 1;
3443 StringRef Argument(Begin, I - (Pos + 1));
3445 for (; Index < NParameters; ++Index)
3446 if (Parameters[Index].Name == Argument)
3449 if (Index == NParameters) {
3450 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3456 NamedParametersFound = true;
3457 Pos += 1 + Argument.size();
3460 // Update the scan point.
3461 Body = Body.substr(Pos);
3464 if (!NamedParametersFound && PositionalParametersFound)
3465 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3466 "used in macro body, possible positional parameter "
3467 "found in body which will have no effect");
3470 /// parseDirectiveExitMacro
3472 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3473 if (getLexer().isNot(AsmToken::EndOfStatement))
3474 return TokError("unexpected token in '" + Directive + "' directive");
3476 if (!isInsideMacroInstantiation())
3477 return TokError("unexpected '" + Directive + "' in file, "
3478 "no current macro definition");
3480 // Exit all conditionals that are active in the current macro.
3481 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3482 TheCondState = TheCondStack.back();
3483 TheCondStack.pop_back();
3490 /// parseDirectiveEndMacro
3493 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3494 if (getLexer().isNot(AsmToken::EndOfStatement))
3495 return TokError("unexpected token in '" + Directive + "' directive");
3497 // If we are inside a macro instantiation, terminate the current
3499 if (isInsideMacroInstantiation()) {
3504 // Otherwise, this .endmacro is a stray entry in the file; well formed
3505 // .endmacro directives are handled during the macro definition parsing.
3506 return TokError("unexpected '" + Directive + "' in file, "
3507 "no current macro definition");
3510 /// parseDirectivePurgeMacro
3512 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3514 if (parseIdentifier(Name))
3515 return TokError("expected identifier in '.purgem' directive");
3517 if (getLexer().isNot(AsmToken::EndOfStatement))
3518 return TokError("unexpected token in '.purgem' directive");
3520 if (!lookupMacro(Name))
3521 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3523 undefineMacro(Name);
3527 /// parseDirectiveBundleAlignMode
3528 /// ::= {.bundle_align_mode} expression
3529 bool AsmParser::parseDirectiveBundleAlignMode() {
3530 checkForValidSection();
3532 // Expect a single argument: an expression that evaluates to a constant
3533 // in the inclusive range 0-30.
3534 SMLoc ExprLoc = getLexer().getLoc();
3535 int64_t AlignSizePow2;
3536 if (parseAbsoluteExpression(AlignSizePow2))
3538 else if (getLexer().isNot(AsmToken::EndOfStatement))
3539 return TokError("unexpected token after expression in"
3540 " '.bundle_align_mode' directive");
3541 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3542 return Error(ExprLoc,
3543 "invalid bundle alignment size (expected between 0 and 30)");
3547 // Because of AlignSizePow2's verified range we can safely truncate it to
3549 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3553 /// parseDirectiveBundleLock
3554 /// ::= {.bundle_lock} [align_to_end]
3555 bool AsmParser::parseDirectiveBundleLock() {
3556 checkForValidSection();
3557 bool AlignToEnd = false;
3559 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3561 SMLoc Loc = getTok().getLoc();
3562 const char *kInvalidOptionError =
3563 "invalid option for '.bundle_lock' directive";
3565 if (parseIdentifier(Option))
3566 return Error(Loc, kInvalidOptionError);
3568 if (Option != "align_to_end")
3569 return Error(Loc, kInvalidOptionError);
3570 else if (getLexer().isNot(AsmToken::EndOfStatement))
3572 "unexpected token after '.bundle_lock' directive option");
3578 getStreamer().EmitBundleLock(AlignToEnd);
3582 /// parseDirectiveBundleLock
3583 /// ::= {.bundle_lock}
3584 bool AsmParser::parseDirectiveBundleUnlock() {
3585 checkForValidSection();
3587 if (getLexer().isNot(AsmToken::EndOfStatement))
3588 return TokError("unexpected token in '.bundle_unlock' directive");
3591 getStreamer().EmitBundleUnlock();
3595 /// parseDirectiveSpace
3596 /// ::= (.skip | .space) expression [ , expression ]
3597 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3598 checkForValidSection();
3601 if (parseAbsoluteExpression(NumBytes))
3604 int64_t FillExpr = 0;
3605 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3606 if (getLexer().isNot(AsmToken::Comma))
3607 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3610 if (parseAbsoluteExpression(FillExpr))
3613 if (getLexer().isNot(AsmToken::EndOfStatement))
3614 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3620 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3623 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3624 getStreamer().EmitFill(NumBytes, FillExpr);
3629 /// parseDirectiveLEB128
3630 /// ::= (.sleb128 | .uleb128) expression
3631 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3632 checkForValidSection();
3633 const MCExpr *Value;
3635 if (parseExpression(Value))
3638 if (getLexer().isNot(AsmToken::EndOfStatement))
3639 return TokError("unexpected token in directive");
3642 getStreamer().EmitSLEB128Value(Value);
3644 getStreamer().EmitULEB128Value(Value);
3649 /// parseDirectiveSymbolAttribute
3650 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3651 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3652 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3655 SMLoc Loc = getTok().getLoc();
3657 if (parseIdentifier(Name))
3658 return Error(Loc, "expected identifier in directive");
3660 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3662 // Assembler local symbols don't make any sense here. Complain loudly.
3663 if (Sym->isTemporary())
3664 return Error(Loc, "non-local symbol required in directive");
3666 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3667 return Error(Loc, "unable to emit symbol attribute");
3669 if (getLexer().is(AsmToken::EndOfStatement))
3672 if (getLexer().isNot(AsmToken::Comma))
3673 return TokError("unexpected token in directive");
3682 /// parseDirectiveComm
3683 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3684 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3685 checkForValidSection();
3687 SMLoc IDLoc = getLexer().getLoc();
3689 if (parseIdentifier(Name))
3690 return TokError("expected identifier in directive");
3692 // Handle the identifier as the key symbol.
3693 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3695 if (getLexer().isNot(AsmToken::Comma))
3696 return TokError("unexpected token in directive");
3700 SMLoc SizeLoc = getLexer().getLoc();
3701 if (parseAbsoluteExpression(Size))
3704 int64_t Pow2Alignment = 0;
3705 SMLoc Pow2AlignmentLoc;
3706 if (getLexer().is(AsmToken::Comma)) {
3708 Pow2AlignmentLoc = getLexer().getLoc();
3709 if (parseAbsoluteExpression(Pow2Alignment))
3712 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3713 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3714 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3716 // If this target takes alignments in bytes (not log) validate and convert.
3717 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3718 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3719 if (!isPowerOf2_64(Pow2Alignment))
3720 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3721 Pow2Alignment = Log2_64(Pow2Alignment);
3725 if (getLexer().isNot(AsmToken::EndOfStatement))
3726 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3730 // NOTE: a size of zero for a .comm should create a undefined symbol
3731 // but a size of .lcomm creates a bss symbol of size zero.
3733 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3734 "be less than zero");
3736 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3737 // may internally end up wanting an alignment in bytes.
3738 // FIXME: Diagnose overflow.
3739 if (Pow2Alignment < 0)
3740 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3741 "alignment, can't be less than zero");
3743 if (!Sym->isUndefined())
3744 return Error(IDLoc, "invalid symbol redefinition");
3746 // Create the Symbol as a common or local common with Size and Pow2Alignment
3748 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3752 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3756 /// parseDirectiveAbort
3757 /// ::= .abort [... message ...]
3758 bool AsmParser::parseDirectiveAbort() {
3759 // FIXME: Use loc from directive.
3760 SMLoc Loc = getLexer().getLoc();
3762 StringRef Str = parseStringToEndOfStatement();
3763 if (getLexer().isNot(AsmToken::EndOfStatement))
3764 return TokError("unexpected token in '.abort' directive");
3769 Error(Loc, ".abort detected. Assembly stopping.");
3771 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3772 // FIXME: Actually abort assembly here.
3777 /// parseDirectiveInclude
3778 /// ::= .include "filename"
3779 bool AsmParser::parseDirectiveInclude() {
3780 if (getLexer().isNot(AsmToken::String))
3781 return TokError("expected string in '.include' directive");
3783 // Allow the strings to have escaped octal character sequence.
3784 std::string Filename;
3785 if (parseEscapedString(Filename))
3787 SMLoc IncludeLoc = getLexer().getLoc();
3790 if (getLexer().isNot(AsmToken::EndOfStatement))
3791 return TokError("unexpected token in '.include' directive");
3793 // Attempt to switch the lexer to the included file before consuming the end
3794 // of statement to avoid losing it when we switch.
3795 if (enterIncludeFile(Filename)) {
3796 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3803 /// parseDirectiveIncbin
3804 /// ::= .incbin "filename"
3805 bool AsmParser::parseDirectiveIncbin() {
3806 if (getLexer().isNot(AsmToken::String))
3807 return TokError("expected string in '.incbin' directive");
3809 // Allow the strings to have escaped octal character sequence.
3810 std::string Filename;
3811 if (parseEscapedString(Filename))
3813 SMLoc IncbinLoc = getLexer().getLoc();
3816 if (getLexer().isNot(AsmToken::EndOfStatement))
3817 return TokError("unexpected token in '.incbin' directive");
3819 // Attempt to process the included file.
3820 if (processIncbinFile(Filename)) {
3821 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3828 /// parseDirectiveIf
3829 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3830 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3831 TheCondStack.push_back(TheCondState);
3832 TheCondState.TheCond = AsmCond::IfCond;
3833 if (TheCondState.Ignore) {
3834 eatToEndOfStatement();
3837 if (parseAbsoluteExpression(ExprValue))
3840 if (getLexer().isNot(AsmToken::EndOfStatement))
3841 return TokError("unexpected token in '.if' directive");
3847 llvm_unreachable("unsupported directive");
3852 ExprValue = ExprValue == 0;
3855 ExprValue = ExprValue >= 0;
3858 ExprValue = ExprValue > 0;
3861 ExprValue = ExprValue <= 0;
3864 ExprValue = ExprValue < 0;
3868 TheCondState.CondMet = ExprValue;
3869 TheCondState.Ignore = !TheCondState.CondMet;
3875 /// parseDirectiveIfb
3877 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3878 TheCondStack.push_back(TheCondState);
3879 TheCondState.TheCond = AsmCond::IfCond;
3881 if (TheCondState.Ignore) {
3882 eatToEndOfStatement();
3884 StringRef Str = parseStringToEndOfStatement();
3886 if (getLexer().isNot(AsmToken::EndOfStatement))
3887 return TokError("unexpected token in '.ifb' directive");
3891 TheCondState.CondMet = ExpectBlank == Str.empty();
3892 TheCondState.Ignore = !TheCondState.CondMet;
3898 /// parseDirectiveIfc
3899 /// ::= .ifc string1, string2
3900 /// ::= .ifnc string1, string2
3901 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3902 TheCondStack.push_back(TheCondState);
3903 TheCondState.TheCond = AsmCond::IfCond;
3905 if (TheCondState.Ignore) {
3906 eatToEndOfStatement();
3908 StringRef Str1 = parseStringToComma();
3910 if (getLexer().isNot(AsmToken::Comma))
3911 return TokError("unexpected token in '.ifc' directive");
3915 StringRef Str2 = parseStringToEndOfStatement();
3917 if (getLexer().isNot(AsmToken::EndOfStatement))
3918 return TokError("unexpected token in '.ifc' directive");
3922 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3923 TheCondState.Ignore = !TheCondState.CondMet;
3929 /// parseDirectiveIfeqs
3930 /// ::= .ifeqs string1, string2
3931 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3932 if (Lexer.isNot(AsmToken::String)) {
3933 TokError("expected string parameter for '.ifeqs' directive");
3934 eatToEndOfStatement();
3938 StringRef String1 = getTok().getStringContents();
3941 if (Lexer.isNot(AsmToken::Comma)) {
3942 TokError("expected comma after first string for '.ifeqs' directive");
3943 eatToEndOfStatement();
3949 if (Lexer.isNot(AsmToken::String)) {
3950 TokError("expected string parameter for '.ifeqs' directive");
3951 eatToEndOfStatement();
3955 StringRef String2 = getTok().getStringContents();
3958 TheCondStack.push_back(TheCondState);
3959 TheCondState.TheCond = AsmCond::IfCond;
3960 TheCondState.CondMet = String1 == String2;
3961 TheCondState.Ignore = !TheCondState.CondMet;
3966 /// parseDirectiveIfdef
3967 /// ::= .ifdef symbol
3968 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3970 TheCondStack.push_back(TheCondState);
3971 TheCondState.TheCond = AsmCond::IfCond;
3973 if (TheCondState.Ignore) {
3974 eatToEndOfStatement();
3976 if (parseIdentifier(Name))
3977 return TokError("expected identifier after '.ifdef'");
3981 MCSymbol *Sym = getContext().LookupSymbol(Name);
3984 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3986 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3987 TheCondState.Ignore = !TheCondState.CondMet;
3993 /// parseDirectiveElseIf
3994 /// ::= .elseif expression
3995 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3996 if (TheCondState.TheCond != AsmCond::IfCond &&
3997 TheCondState.TheCond != AsmCond::ElseIfCond)
3998 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4000 TheCondState.TheCond = AsmCond::ElseIfCond;
4002 bool LastIgnoreState = false;
4003 if (!TheCondStack.empty())
4004 LastIgnoreState = TheCondStack.back().Ignore;
4005 if (LastIgnoreState || TheCondState.CondMet) {
4006 TheCondState.Ignore = true;
4007 eatToEndOfStatement();
4010 if (parseAbsoluteExpression(ExprValue))
4013 if (getLexer().isNot(AsmToken::EndOfStatement))
4014 return TokError("unexpected token in '.elseif' directive");
4017 TheCondState.CondMet = ExprValue;
4018 TheCondState.Ignore = !TheCondState.CondMet;
4024 /// parseDirectiveElse
4026 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4027 if (getLexer().isNot(AsmToken::EndOfStatement))
4028 return TokError("unexpected token in '.else' directive");
4032 if (TheCondState.TheCond != AsmCond::IfCond &&
4033 TheCondState.TheCond != AsmCond::ElseIfCond)
4034 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4036 TheCondState.TheCond = AsmCond::ElseCond;
4037 bool LastIgnoreState = false;
4038 if (!TheCondStack.empty())
4039 LastIgnoreState = TheCondStack.back().Ignore;
4040 if (LastIgnoreState || TheCondState.CondMet)
4041 TheCondState.Ignore = true;
4043 TheCondState.Ignore = false;
4048 /// parseDirectiveEnd
4050 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4051 if (getLexer().isNot(AsmToken::EndOfStatement))
4052 return TokError("unexpected token in '.end' directive");
4056 while (Lexer.isNot(AsmToken::Eof))
4062 /// parseDirectiveError
4064 /// ::= .error [string]
4065 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4066 if (!TheCondStack.empty()) {
4067 if (TheCondStack.back().Ignore) {
4068 eatToEndOfStatement();
4074 return Error(L, ".err encountered");
4076 StringRef Message = ".error directive invoked in source file";
4077 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4078 if (Lexer.isNot(AsmToken::String)) {
4079 TokError(".error argument must be a string");
4080 eatToEndOfStatement();
4084 Message = getTok().getStringContents();
4092 /// parseDirectiveWarning
4093 /// ::= .warning [string]
4094 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4095 if (!TheCondStack.empty()) {
4096 if (TheCondStack.back().Ignore) {
4097 eatToEndOfStatement();
4102 StringRef Message = ".warning directive invoked in source file";
4103 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4104 if (Lexer.isNot(AsmToken::String)) {
4105 TokError(".warning argument must be a string");
4106 eatToEndOfStatement();
4110 Message = getTok().getStringContents();
4114 Warning(L, Message);
4118 /// parseDirectiveEndIf
4120 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4121 if (getLexer().isNot(AsmToken::EndOfStatement))
4122 return TokError("unexpected token in '.endif' directive");
4126 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4127 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4129 if (!TheCondStack.empty()) {
4130 TheCondState = TheCondStack.back();
4131 TheCondStack.pop_back();
4137 void AsmParser::initializeDirectiveKindMap() {
4138 DirectiveKindMap[".set"] = DK_SET;
4139 DirectiveKindMap[".equ"] = DK_EQU;
4140 DirectiveKindMap[".equiv"] = DK_EQUIV;
4141 DirectiveKindMap[".ascii"] = DK_ASCII;
4142 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4143 DirectiveKindMap[".string"] = DK_STRING;
4144 DirectiveKindMap[".byte"] = DK_BYTE;
4145 DirectiveKindMap[".short"] = DK_SHORT;
4146 DirectiveKindMap[".value"] = DK_VALUE;
4147 DirectiveKindMap[".2byte"] = DK_2BYTE;
4148 DirectiveKindMap[".long"] = DK_LONG;
4149 DirectiveKindMap[".int"] = DK_INT;
4150 DirectiveKindMap[".4byte"] = DK_4BYTE;
4151 DirectiveKindMap[".quad"] = DK_QUAD;
4152 DirectiveKindMap[".8byte"] = DK_8BYTE;
4153 DirectiveKindMap[".octa"] = DK_OCTA;
4154 DirectiveKindMap[".single"] = DK_SINGLE;
4155 DirectiveKindMap[".float"] = DK_FLOAT;
4156 DirectiveKindMap[".double"] = DK_DOUBLE;
4157 DirectiveKindMap[".align"] = DK_ALIGN;
4158 DirectiveKindMap[".align32"] = DK_ALIGN32;
4159 DirectiveKindMap[".balign"] = DK_BALIGN;
4160 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4161 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4162 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4163 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4164 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4165 DirectiveKindMap[".org"] = DK_ORG;
4166 DirectiveKindMap[".fill"] = DK_FILL;
4167 DirectiveKindMap[".zero"] = DK_ZERO;
4168 DirectiveKindMap[".extern"] = DK_EXTERN;
4169 DirectiveKindMap[".globl"] = DK_GLOBL;
4170 DirectiveKindMap[".global"] = DK_GLOBAL;
4171 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4172 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4173 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4174 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4175 DirectiveKindMap[".reference"] = DK_REFERENCE;
4176 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4177 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4178 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4179 DirectiveKindMap[".comm"] = DK_COMM;
4180 DirectiveKindMap[".common"] = DK_COMMON;
4181 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4182 DirectiveKindMap[".abort"] = DK_ABORT;
4183 DirectiveKindMap[".include"] = DK_INCLUDE;
4184 DirectiveKindMap[".incbin"] = DK_INCBIN;
4185 DirectiveKindMap[".code16"] = DK_CODE16;
4186 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4187 DirectiveKindMap[".rept"] = DK_REPT;
4188 DirectiveKindMap[".rep"] = DK_REPT;
4189 DirectiveKindMap[".irp"] = DK_IRP;
4190 DirectiveKindMap[".irpc"] = DK_IRPC;
4191 DirectiveKindMap[".endr"] = DK_ENDR;
4192 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4193 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4194 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4195 DirectiveKindMap[".if"] = DK_IF;
4196 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4197 DirectiveKindMap[".ifge"] = DK_IFGE;
4198 DirectiveKindMap[".ifgt"] = DK_IFGT;
4199 DirectiveKindMap[".ifle"] = DK_IFLE;
4200 DirectiveKindMap[".iflt"] = DK_IFLT;
4201 DirectiveKindMap[".ifne"] = DK_IFNE;
4202 DirectiveKindMap[".ifb"] = DK_IFB;
4203 DirectiveKindMap[".ifnb"] = DK_IFNB;
4204 DirectiveKindMap[".ifc"] = DK_IFC;
4205 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4206 DirectiveKindMap[".ifnc"] = DK_IFNC;
4207 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4208 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4209 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4210 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4211 DirectiveKindMap[".else"] = DK_ELSE;
4212 DirectiveKindMap[".end"] = DK_END;
4213 DirectiveKindMap[".endif"] = DK_ENDIF;
4214 DirectiveKindMap[".skip"] = DK_SKIP;
4215 DirectiveKindMap[".space"] = DK_SPACE;
4216 DirectiveKindMap[".file"] = DK_FILE;
4217 DirectiveKindMap[".line"] = DK_LINE;
4218 DirectiveKindMap[".loc"] = DK_LOC;
4219 DirectiveKindMap[".stabs"] = DK_STABS;
4220 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4221 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4222 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4223 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4224 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4225 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4226 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4227 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4228 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4229 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4230 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4231 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4232 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4233 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4234 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4235 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4236 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4237 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4238 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4239 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4240 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4241 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4242 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4243 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4244 DirectiveKindMap[".macro"] = DK_MACRO;
4245 DirectiveKindMap[".exitm"] = DK_EXITM;
4246 DirectiveKindMap[".endm"] = DK_ENDM;
4247 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4248 DirectiveKindMap[".purgem"] = DK_PURGEM;
4249 DirectiveKindMap[".err"] = DK_ERR;
4250 DirectiveKindMap[".error"] = DK_ERROR;
4251 DirectiveKindMap[".warning"] = DK_WARNING;
4254 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4255 AsmToken EndToken, StartToken = getTok();
4257 unsigned NestLevel = 0;
4259 // Check whether we have reached the end of the file.
4260 if (getLexer().is(AsmToken::Eof)) {
4261 Error(DirectiveLoc, "no matching '.endr' in definition");
4265 if (Lexer.is(AsmToken::Identifier) &&
4266 (getTok().getIdentifier() == ".rept")) {
4270 // Otherwise, check whether we have reached the .endr.
4271 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4272 if (NestLevel == 0) {
4273 EndToken = getTok();
4275 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4276 TokError("unexpected token in '.endr' directive");
4284 // Otherwise, scan till the end of the statement.
4285 eatToEndOfStatement();
4288 const char *BodyStart = StartToken.getLoc().getPointer();
4289 const char *BodyEnd = EndToken.getLoc().getPointer();
4290 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4292 // We Are Anonymous.
4293 MacroLikeBodies.push_back(
4294 MCAsmMacro(StringRef(), Body, MCAsmMacroParameters()));
4295 return &MacroLikeBodies.back();
4298 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4299 raw_svector_ostream &OS) {
4302 std::unique_ptr<MemoryBuffer> Instantiation =
4303 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4305 // Create the macro instantiation object and add to the current macro
4306 // instantiation stack.
4307 MacroInstantiation *MI = new MacroInstantiation(
4308 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4309 ActiveMacros.push_back(MI);
4311 // Jump to the macro instantiation and prime the lexer.
4312 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4313 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4317 /// parseDirectiveRept
4318 /// ::= .rep | .rept count
4319 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4320 const MCExpr *CountExpr;
4321 SMLoc CountLoc = getTok().getLoc();
4322 if (parseExpression(CountExpr))
4326 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4327 eatToEndOfStatement();
4328 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4332 return Error(CountLoc, "Count is negative");
4334 if (Lexer.isNot(AsmToken::EndOfStatement))
4335 return TokError("unexpected token in '" + Dir + "' directive");
4337 // Eat the end of statement.
4340 // Lex the rept definition.
4341 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4345 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4346 // to hold the macro body with substitutions.
4347 SmallString<256> Buf;
4348 raw_svector_ostream OS(Buf);
4350 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4353 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4358 /// parseDirectiveIrp
4359 /// ::= .irp symbol,values
4360 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4361 MCAsmMacroParameter Parameter;
4363 if (parseIdentifier(Parameter.Name))
4364 return TokError("expected identifier in '.irp' directive");
4366 if (Lexer.isNot(AsmToken::Comma))
4367 return TokError("expected comma in '.irp' directive");
4371 MCAsmMacroArguments A;
4372 if (parseMacroArguments(nullptr, A))
4375 // Eat the end of statement.
4378 // Lex the irp definition.
4379 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4383 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4384 // to hold the macro body with substitutions.
4385 SmallString<256> Buf;
4386 raw_svector_ostream OS(Buf);
4388 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4389 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4393 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4398 /// parseDirectiveIrpc
4399 /// ::= .irpc symbol,values
4400 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4401 MCAsmMacroParameter Parameter;
4403 if (parseIdentifier(Parameter.Name))
4404 return TokError("expected identifier in '.irpc' directive");
4406 if (Lexer.isNot(AsmToken::Comma))
4407 return TokError("expected comma in '.irpc' directive");
4411 MCAsmMacroArguments A;
4412 if (parseMacroArguments(nullptr, A))
4415 if (A.size() != 1 || A.front().size() != 1)
4416 return TokError("unexpected token in '.irpc' directive");
4418 // Eat the end of statement.
4421 // Lex the irpc definition.
4422 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4426 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4427 // to hold the macro body with substitutions.
4428 SmallString<256> Buf;
4429 raw_svector_ostream OS(Buf);
4431 StringRef Values = A.front().front().getString();
4432 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4433 MCAsmMacroArgument Arg;
4434 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4436 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4440 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4445 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4446 if (ActiveMacros.empty())
4447 return TokError("unmatched '.endr' directive");
4449 // The only .repl that should get here are the ones created by
4450 // instantiateMacroLikeBody.
4451 assert(getLexer().is(AsmToken::EndOfStatement));
4457 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4459 const MCExpr *Value;
4460 SMLoc ExprLoc = getLexer().getLoc();
4461 if (parseExpression(Value))
4463 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4465 return Error(ExprLoc, "unexpected expression in _emit");
4466 uint64_t IntValue = MCE->getValue();
4467 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4468 return Error(ExprLoc, "literal value out of range for directive");
4470 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4474 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4475 const MCExpr *Value;
4476 SMLoc ExprLoc = getLexer().getLoc();
4477 if (parseExpression(Value))
4479 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4481 return Error(ExprLoc, "unexpected expression in align");
4482 uint64_t IntValue = MCE->getValue();
4483 if (!isPowerOf2_64(IntValue))
4484 return Error(ExprLoc, "literal value not a power of two greater then zero");
4486 Info.AsmRewrites->push_back(
4487 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4491 // We are comparing pointers, but the pointers are relative to a single string.
4492 // Thus, this should always be deterministic.
4493 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4494 const AsmRewrite *AsmRewriteB) {
4495 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4497 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4500 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4501 // rewrite to the same location. Make sure the SizeDirective rewrite is
4502 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4503 // ensures the sort algorithm is stable.
4504 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4505 AsmRewritePrecedence[AsmRewriteB->Kind])
4508 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4509 AsmRewritePrecedence[AsmRewriteB->Kind])
4511 llvm_unreachable("Unstable rewrite sort.");
4514 bool AsmParser::parseMSInlineAsm(
4515 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4516 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4517 SmallVectorImpl<std::string> &Constraints,
4518 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4519 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4520 SmallVector<void *, 4> InputDecls;
4521 SmallVector<void *, 4> OutputDecls;
4522 SmallVector<bool, 4> InputDeclsAddressOf;
4523 SmallVector<bool, 4> OutputDeclsAddressOf;
4524 SmallVector<std::string, 4> InputConstraints;
4525 SmallVector<std::string, 4> OutputConstraints;
4526 SmallVector<unsigned, 4> ClobberRegs;
4528 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4533 // While we have input, parse each statement.
4534 unsigned InputIdx = 0;
4535 unsigned OutputIdx = 0;
4536 while (getLexer().isNot(AsmToken::Eof)) {
4537 ParseStatementInfo Info(&AsmStrRewrites);
4538 if (parseStatement(Info, &SI))
4541 if (Info.ParseError)
4544 if (Info.Opcode == ~0U)
4547 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4549 // Build the list of clobbers, outputs and inputs.
4550 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4551 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4554 if (Operand.isImm())
4557 // Register operand.
4558 if (Operand.isReg() && !Operand.needAddressOf() &&
4559 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4560 unsigned NumDefs = Desc.getNumDefs();
4562 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4563 ClobberRegs.push_back(Operand.getReg());
4567 // Expr/Input or Output.
4568 StringRef SymName = Operand.getSymName();
4569 if (SymName.empty())
4572 void *OpDecl = Operand.getOpDecl();
4576 bool isOutput = (i == 1) && Desc.mayStore();
4577 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4580 OutputDecls.push_back(OpDecl);
4581 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4582 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4583 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4585 InputDecls.push_back(OpDecl);
4586 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4587 InputConstraints.push_back(Operand.getConstraint().str());
4588 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4592 // Consider implicit defs to be clobbers. Think of cpuid and push.
4593 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4594 Desc.getNumImplicitDefs());
4595 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4598 // Set the number of Outputs and Inputs.
4599 NumOutputs = OutputDecls.size();
4600 NumInputs = InputDecls.size();
4602 // Set the unique clobbers.
4603 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4604 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4606 Clobbers.assign(ClobberRegs.size(), std::string());
4607 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4608 raw_string_ostream OS(Clobbers[I]);
4609 IP->printRegName(OS, ClobberRegs[I]);
4612 // Merge the various outputs and inputs. Output are expected first.
4613 if (NumOutputs || NumInputs) {
4614 unsigned NumExprs = NumOutputs + NumInputs;
4615 OpDecls.resize(NumExprs);
4616 Constraints.resize(NumExprs);
4617 for (unsigned i = 0; i < NumOutputs; ++i) {
4618 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4619 Constraints[i] = OutputConstraints[i];
4621 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4622 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4623 Constraints[j] = InputConstraints[i];
4627 // Build the IR assembly string.
4628 std::string AsmStringIR;
4629 raw_string_ostream OS(AsmStringIR);
4630 StringRef ASMString =
4631 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4632 const char *AsmStart = ASMString.begin();
4633 const char *AsmEnd = ASMString.end();
4634 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4635 for (const AsmRewrite &AR : AsmStrRewrites) {
4636 AsmRewriteKind Kind = AR.Kind;
4637 if (Kind == AOK_Delete)
4640 const char *Loc = AR.Loc.getPointer();
4641 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4643 // Emit everything up to the immediate/expression.
4644 if (unsigned Len = Loc - AsmStart)
4645 OS << StringRef(AsmStart, Len);
4647 // Skip the original expression.
4648 if (Kind == AOK_Skip) {
4649 AsmStart = Loc + AR.Len;
4653 unsigned AdditionalSkip = 0;
4654 // Rewrite expressions in $N notation.
4659 OS << "$$" << AR.Val;
4665 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4668 OS << '$' << InputIdx++;
4671 OS << '$' << OutputIdx++;
4673 case AOK_SizeDirective:
4676 case 8: OS << "byte ptr "; break;
4677 case 16: OS << "word ptr "; break;
4678 case 32: OS << "dword ptr "; break;
4679 case 64: OS << "qword ptr "; break;
4680 case 80: OS << "xword ptr "; break;
4681 case 128: OS << "xmmword ptr "; break;
4682 case 256: OS << "ymmword ptr "; break;
4689 unsigned Val = AR.Val;
4690 OS << ".align " << Val;
4692 // Skip the original immediate.
4693 assert(Val < 10 && "Expected alignment less then 2^10.");
4694 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4697 case AOK_DotOperator:
4698 // Insert the dot if the user omitted it.
4700 if (AsmStringIR.back() != '.')
4706 // Skip the original expression.
4707 AsmStart = Loc + AR.Len + AdditionalSkip;
4710 // Emit the remainder of the asm string.
4711 if (AsmStart != AsmEnd)
4712 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4714 AsmString = OS.str();
4718 /// \brief Create an MCAsmParser instance.
4719 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4720 MCStreamer &Out, const MCAsmInfo &MAI) {
4721 return new AsmParser(SM, C, Out, MAI);