1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCTargetAsmParser.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/raw_ostream.h"
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
52 /// \brief Helper types for tracking macro definitions.
53 typedef std::vector<AsmToken> MCAsmMacroArgument;
54 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56 struct MCAsmMacroParameter {
58 MCAsmMacroArgument Value;
62 MCAsmMacroParameter() : Required(false), Vararg(false) {}
65 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
70 MCAsmMacroParameters Parameters;
73 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
74 : Name(N), Body(B), Parameters(std::move(P)) {}
77 /// \brief Helper class for storing information about an active macro
79 struct MacroInstantiation {
80 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
83 /// The buffer where parsing should resume upon instantiation completion.
86 /// The location where parsing should resume upon instantiation completion.
89 /// The depth of TheCondStack at the start of the instantiation.
90 size_t CondStackDepth;
93 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
96 struct ParseStatementInfo {
97 /// \brief The parsed operands from the last parsed statement.
98 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
100 /// \brief The opcode from the last parsed instruction.
103 /// \brief Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 /// \brief The concrete assembly parser instance.
114 class AsmParser : public MCAsmParser {
115 AsmParser(const AsmParser &) = delete;
116 void operator=(const AsmParser &) = delete;
121 const MCAsmInfo &MAI;
123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
125 std::unique_ptr<MCAsmParserExtension> PlatformParser;
127 /// This is the current buffer index we're lexing from as managed by the
128 /// SourceMgr object.
131 AsmCond TheCondState;
132 std::vector<AsmCond> TheCondStack;
134 /// \brief maps directive names to handler methods in parser
135 /// extensions. Extensions register themselves in this map by calling
136 /// addDirectiveHandler.
137 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
139 /// \brief Map of currently defined macros.
140 StringMap<MCAsmMacro> MacroMap;
142 /// \brief Stack of active macro instantiations.
143 std::vector<MacroInstantiation*> ActiveMacros;
145 /// \brief List of bodies of anonymous macros.
146 std::deque<MCAsmMacro> MacroLikeBodies;
148 /// Boolean tracking whether macro substitution is enabled.
149 unsigned MacrosEnabledFlag : 1;
151 /// \brief Keeps track of how many .macro's have been instantiated.
152 unsigned NumOfMacroInstantiations;
154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
162 /// When generating dwarf for assembly source files we need to calculate the
163 /// logical line number based on the last parsed cpp hash file line comment
164 /// and current line. Since this is slow and messes up the SourceMgr's
165 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
166 SMLoc LastQueryIDLoc;
167 unsigned LastQueryBuffer;
168 unsigned LastQueryLine;
170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
171 unsigned AssemblerDialect;
173 /// \brief is Darwin compatibility enabled?
176 /// \brief Are we parsing ms-style inline assembly?
177 bool ParsingInlineAsm;
180 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
181 const MCAsmInfo &MAI);
182 ~AsmParser() override;
184 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
186 void addDirectiveHandler(StringRef Directive,
187 ExtensionDirectiveHandler Handler) override {
188 ExtensionDirectiveMap[Directive] = Handler;
191 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
192 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
196 /// @name MCAsmParser Interface
199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 void setAssemblerDialect(unsigned i) override {
210 AssemblerDialect = i;
213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
220 const AsmToken &Lex() override;
222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
233 bool parseExpression(const MCExpr *&Res);
234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseAbsoluteExpression(int64_t &Res) override;
239 /// \brief Parse an identifier or string (as a quoted identifier)
240 /// and set \p Res to the identifier contents.
241 bool parseIdentifier(StringRef &Res) override;
242 void eatToEndOfStatement() override;
244 void checkForValidSection() override;
249 bool parseStatement(ParseStatementInfo &Info,
250 MCAsmParserSemaCallback *SI);
251 void eatToEndOfLine();
252 bool parseCppHashLineFilenameComment(const SMLoc &L);
254 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
255 ArrayRef<MCAsmMacroParameter> Parameters);
256 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
257 ArrayRef<MCAsmMacroParameter> Parameters,
258 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
261 /// \brief Are macros enabled in the parser?
262 bool areMacrosEnabled() {return MacrosEnabledFlag;}
264 /// \brief Control a flag in the parser that enables or disables macros.
265 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
267 /// \brief Lookup a previously defined macro.
268 /// \param Name Macro name.
269 /// \returns Pointer to macro. NULL if no such macro was defined.
270 const MCAsmMacro* lookupMacro(StringRef Name);
272 /// \brief Define a new macro with the given name and information.
273 void defineMacro(StringRef Name, MCAsmMacro Macro);
275 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
276 void undefineMacro(StringRef Name);
278 /// \brief Are we inside a macro instantiation?
279 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
281 /// \brief Handle entry to macro instantiation.
283 /// \param M The macro.
284 /// \param NameLoc Instantiation location.
285 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
287 /// \brief Handle exit from macro instantiation.
288 void handleMacroExit();
290 /// \brief Extract AsmTokens for a macro argument.
291 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
293 /// \brief Parse all macro arguments for a given macro.
294 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
296 void printMacroInstantiations();
297 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
298 ArrayRef<SMRange> Ranges = None) const {
299 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
301 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
303 /// \brief Enter the specified file. This returns true on failure.
304 bool enterIncludeFile(const std::string &Filename);
306 /// \brief Process the specified file for the .incbin directive.
307 /// This returns true on failure.
308 bool processIncbinFile(const std::string &Filename);
310 /// \brief Reset the current lexer position to that given by \p Loc. The
311 /// current token is not set; clients should ensure Lex() is called
314 /// \param InBuffer If not 0, should be the known buffer id that contains the
316 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
318 /// \brief Parse up to the end of statement and a return the contents from the
319 /// current token until the end of the statement; the current token on exit
320 /// will be either the EndOfStatement or EOF.
321 StringRef parseStringToEndOfStatement() override;
323 /// \brief Parse until the end of a statement or a comma is encountered,
324 /// return the contents from the current token up to the end or comma.
325 StringRef parseStringToComma();
327 bool parseAssignment(StringRef Name, bool allow_redef,
328 bool NoDeadStrip = false);
330 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
331 MCBinaryExpr::Opcode &Kind);
333 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
339 // Generic (target and platform independent) directive parsing.
341 DK_NO_DIRECTIVE, // Placeholder
342 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
343 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
344 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
345 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
346 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
347 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
348 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
349 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
350 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
351 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
352 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
353 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
354 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
355 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
356 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
357 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
358 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
359 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
360 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
361 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
362 DK_MACROS_ON, DK_MACROS_OFF,
363 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
364 DK_SLEB128, DK_ULEB128,
365 DK_ERR, DK_ERROR, DK_WARNING,
369 /// \brief Maps directive name --> DirectiveKind enum, for
370 /// directives parsed by this class.
371 StringMap<DirectiveKind> DirectiveKindMap;
373 // ".ascii", ".asciz", ".string"
374 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
375 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
376 bool parseDirectiveOctaValue(); // ".octa"
377 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
378 bool parseDirectiveFill(); // ".fill"
379 bool parseDirectiveZero(); // ".zero"
380 // ".set", ".equ", ".equiv"
381 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
382 bool parseDirectiveOrg(); // ".org"
383 // ".align{,32}", ".p2align{,w,l}"
384 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
386 // ".file", ".line", ".loc", ".stabs"
387 bool parseDirectiveFile(SMLoc DirectiveLoc);
388 bool parseDirectiveLine();
389 bool parseDirectiveLoc();
390 bool parseDirectiveStabs();
393 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIWindowSave();
395 bool parseDirectiveCFISections();
396 bool parseDirectiveCFIStartProc();
397 bool parseDirectiveCFIEndProc();
398 bool parseDirectiveCFIDefCfaOffset();
399 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIAdjustCfaOffset();
401 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
405 bool parseDirectiveCFIRememberState();
406 bool parseDirectiveCFIRestoreState();
407 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIEscape();
410 bool parseDirectiveCFISignalFrame();
411 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
414 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
415 bool parseDirectiveExitMacro(StringRef Directive);
416 bool parseDirectiveEndMacro(StringRef Directive);
417 bool parseDirectiveMacro(SMLoc DirectiveLoc);
418 bool parseDirectiveMacrosOnOff(StringRef Directive);
420 // ".bundle_align_mode"
421 bool parseDirectiveBundleAlignMode();
423 bool parseDirectiveBundleLock();
425 bool parseDirectiveBundleUnlock();
428 bool parseDirectiveSpace(StringRef IDVal);
430 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
431 bool parseDirectiveLEB128(bool Signed);
433 /// \brief Parse a directive like ".globl" which
434 /// accepts a single symbol (which should be a label or an external).
435 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
437 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
439 bool parseDirectiveAbort(); // ".abort"
440 bool parseDirectiveInclude(); // ".include"
441 bool parseDirectiveIncbin(); // ".incbin"
443 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
444 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
445 // ".ifb" or ".ifnb", depending on ExpectBlank.
446 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
447 // ".ifc" or ".ifnc", depending on ExpectEqual.
448 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
449 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
450 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
451 // ".ifdef" or ".ifndef", depending on expect_defined
452 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
453 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
454 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
455 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
456 bool parseEscapedString(std::string &Data) override;
458 const MCExpr *applyModifierToExpr(const MCExpr *E,
459 MCSymbolRefExpr::VariantKind Variant);
461 // Macro-like directives
462 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
463 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
464 raw_svector_ostream &OS);
465 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
466 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
467 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
468 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
470 // "_emit" or "__emit"
471 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
475 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
478 bool parseDirectiveEnd(SMLoc DirectiveLoc);
480 // ".err" or ".error"
481 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
484 bool parseDirectiveWarning(SMLoc DirectiveLoc);
486 void initializeDirectiveKindMap();
492 extern MCAsmParserExtension *createDarwinAsmParser();
493 extern MCAsmParserExtension *createELFAsmParser();
494 extern MCAsmParserExtension *createCOFFAsmParser();
498 enum { DEFAULT_ADDRSPACE = 0 };
500 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
501 const MCAsmInfo &MAI)
502 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
503 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
504 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
505 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
506 // Save the old handler.
507 SavedDiagHandler = SrcMgr.getDiagHandler();
508 SavedDiagContext = SrcMgr.getDiagContext();
509 // Set our own handler which calls the saved handler.
510 SrcMgr.setDiagHandler(DiagHandler, this);
511 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
513 // Initialize the platform / file format parser.
514 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
515 case MCObjectFileInfo::IsCOFF:
516 PlatformParser.reset(createCOFFAsmParser());
518 case MCObjectFileInfo::IsMachO:
519 PlatformParser.reset(createDarwinAsmParser());
522 case MCObjectFileInfo::IsELF:
523 PlatformParser.reset(createELFAsmParser());
527 PlatformParser->Initialize(*this);
528 initializeDirectiveKindMap();
530 NumOfMacroInstantiations = 0;
533 AsmParser::~AsmParser() {
534 assert((HadError || ActiveMacros.empty()) &&
535 "Unexpected active macro instantiation!");
538 void AsmParser::printMacroInstantiations() {
539 // Print the active macro instantiation stack.
540 for (std::vector<MacroInstantiation *>::const_reverse_iterator
541 it = ActiveMacros.rbegin(),
542 ie = ActiveMacros.rend();
544 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
545 "while in macro instantiation");
548 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
549 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
550 printMacroInstantiations();
553 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554 if (getTargetParser().getTargetOptions().MCFatalWarnings)
555 return Error(L, Msg, Ranges);
556 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
557 printMacroInstantiations();
561 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
563 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
564 printMacroInstantiations();
568 bool AsmParser::enterIncludeFile(const std::string &Filename) {
569 std::string IncludedFile;
571 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
576 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
580 /// Process the specified .incbin file by searching for it in the include paths
581 /// then just emitting the byte contents of the file to the streamer. This
582 /// returns true on failure.
583 bool AsmParser::processIncbinFile(const std::string &Filename) {
584 std::string IncludedFile;
586 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
590 // Pick up the bytes from the file and emit them.
591 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
595 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
596 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
597 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
601 const AsmToken &AsmParser::Lex() {
602 const AsmToken *tok = &Lexer.Lex();
604 if (tok->is(AsmToken::Eof)) {
605 // If this is the end of an included file, pop the parent file off the
607 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
608 if (ParentIncludeLoc != SMLoc()) {
609 jumpToLoc(ParentIncludeLoc);
614 if (tok->is(AsmToken::Error))
615 Error(Lexer.getErrLoc(), Lexer.getErr());
620 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
621 // Create the initial section, if requested.
622 if (!NoInitialTextSection)
623 Out.InitSections(false);
629 AsmCond StartingCondState = TheCondState;
631 // If we are generating dwarf for assembly source files save the initial text
632 // section and generate a .file directive.
633 if (getContext().getGenDwarfForAssembly()) {
634 MCSection *Sec = getStreamer().getCurrentSection().first;
635 if (!Sec->getBeginSymbol()) {
636 MCSymbol *SectionStartSym = getContext().createTempSymbol();
637 getStreamer().EmitLabel(SectionStartSym);
638 Sec->setBeginSymbol(SectionStartSym);
640 bool InsertResult = getContext().addGenDwarfSection(Sec);
641 assert(InsertResult && ".text section should not have debug info yet");
643 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
644 0, StringRef(), getContext().getMainFileName()));
647 // While we have input, parse each statement.
648 while (Lexer.isNot(AsmToken::Eof)) {
649 ParseStatementInfo Info;
650 if (!parseStatement(Info, nullptr))
653 // We had an error, validate that one was emitted and recover by skipping to
655 assert(HadError && "Parse statement returned an error, but none emitted!");
656 eatToEndOfStatement();
659 if (TheCondState.TheCond != StartingCondState.TheCond ||
660 TheCondState.Ignore != StartingCondState.Ignore)
661 return TokError("unmatched .ifs or .elses");
663 // Check to see there are no empty DwarfFile slots.
664 const auto &LineTables = getContext().getMCDwarfLineTables();
665 if (!LineTables.empty()) {
667 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
668 if (File.Name.empty() && Index != 0)
669 TokError("unassigned file number: " + Twine(Index) +
670 " for .file directives");
675 // Check to see that all assembler local symbols were actually defined.
676 // Targets that don't do subsections via symbols may not want this, though,
677 // so conservatively exclude them. Only do this if we're finalizing, though,
678 // as otherwise we won't necessarilly have seen everything yet.
679 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
680 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
681 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
684 MCSymbol *Sym = i->getValue();
685 // Variable symbols may not be marked as defined, so check those
686 // explicitly. If we know it's a variable, we have a definition for
687 // the purposes of this check.
688 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
689 // FIXME: We would really like to refer back to where the symbol was
690 // first referenced for a source location. We need to add something
691 // to track that. Currently, we just point to the end of the file.
693 getLexer().getLoc(), SourceMgr::DK_Error,
694 "assembler local symbol '" + Sym->getName() + "' not defined");
698 // Finalize the output stream if there are no errors and if the client wants
700 if (!HadError && !NoFinalize)
706 void AsmParser::checkForValidSection() {
707 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
708 TokError("expected section directive before assembly directive");
709 Out.InitSections(false);
713 /// \brief Throw away the rest of the line for testing purposes.
714 void AsmParser::eatToEndOfStatement() {
715 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
719 if (Lexer.is(AsmToken::EndOfStatement))
723 StringRef AsmParser::parseStringToEndOfStatement() {
724 const char *Start = getTok().getLoc().getPointer();
726 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
729 const char *End = getTok().getLoc().getPointer();
730 return StringRef(Start, End - Start);
733 StringRef AsmParser::parseStringToComma() {
734 const char *Start = getTok().getLoc().getPointer();
736 while (Lexer.isNot(AsmToken::EndOfStatement) &&
737 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
740 const char *End = getTok().getLoc().getPointer();
741 return StringRef(Start, End - Start);
744 /// \brief Parse a paren expression and return it.
745 /// NOTE: This assumes the leading '(' has already been consumed.
747 /// parenexpr ::= expr)
749 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
750 if (parseExpression(Res))
752 if (Lexer.isNot(AsmToken::RParen))
753 return TokError("expected ')' in parentheses expression");
754 EndLoc = Lexer.getTok().getEndLoc();
759 /// \brief Parse a bracket expression and return it.
760 /// NOTE: This assumes the leading '[' has already been consumed.
762 /// bracketexpr ::= expr]
764 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
765 if (parseExpression(Res))
767 if (Lexer.isNot(AsmToken::RBrac))
768 return TokError("expected ']' in brackets expression");
769 EndLoc = Lexer.getTok().getEndLoc();
774 /// \brief Parse a primary expression and return it.
775 /// primaryexpr ::= (parenexpr
776 /// primaryexpr ::= symbol
777 /// primaryexpr ::= number
778 /// primaryexpr ::= '.'
779 /// primaryexpr ::= ~,+,- primaryexpr
780 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
781 SMLoc FirstTokenLoc = getLexer().getLoc();
782 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
783 switch (FirstTokenKind) {
785 return TokError("unknown token in expression");
786 // If we have an error assume that we've already handled it.
787 case AsmToken::Error:
789 case AsmToken::Exclaim:
790 Lex(); // Eat the operator.
791 if (parsePrimaryExpr(Res, EndLoc))
793 Res = MCUnaryExpr::createLNot(Res, getContext());
795 case AsmToken::Dollar:
797 case AsmToken::String:
798 case AsmToken::Identifier: {
799 StringRef Identifier;
800 if (parseIdentifier(Identifier)) {
801 if (FirstTokenKind == AsmToken::Dollar) {
802 if (Lexer.getMAI().getDollarIsPC()) {
803 // This is a '$' reference, which references the current PC. Emit a
804 // temporary label to the streamer and refer to it.
805 MCSymbol *Sym = Ctx.createTempSymbol();
807 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
809 EndLoc = FirstTokenLoc;
812 return Error(FirstTokenLoc, "invalid token in expression");
815 // Parse symbol variant
816 std::pair<StringRef, StringRef> Split;
817 if (!MAI.useParensForSymbolVariant()) {
818 if (FirstTokenKind == AsmToken::String) {
819 if (Lexer.is(AsmToken::At)) {
820 Lexer.Lex(); // eat @
821 SMLoc AtLoc = getLexer().getLoc();
823 if (parseIdentifier(VName))
824 return Error(AtLoc, "expected symbol variant after '@'");
826 Split = std::make_pair(Identifier, VName);
829 Split = Identifier.split('@');
831 } else if (Lexer.is(AsmToken::LParen)) {
832 Lexer.Lex(); // eat (
834 parseIdentifier(VName);
835 if (Lexer.isNot(AsmToken::RParen)) {
836 return Error(Lexer.getTok().getLoc(),
837 "unexpected token in variant, expected ')'");
839 Lexer.Lex(); // eat )
840 Split = std::make_pair(Identifier, VName);
843 EndLoc = SMLoc::getFromPointer(Identifier.end());
845 // This is a symbol reference.
846 StringRef SymbolName = Identifier;
847 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
849 // Lookup the symbol variant if used.
850 if (Split.second.size()) {
851 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
852 if (Variant != MCSymbolRefExpr::VK_Invalid) {
853 SymbolName = Split.first;
854 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
855 Variant = MCSymbolRefExpr::VK_None;
857 return Error(SMLoc::getFromPointer(Split.second.begin()),
858 "invalid variant '" + Split.second + "'");
862 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
864 // If this is an absolute variable reference, substitute it now to preserve
865 // semantics in the face of reassignment.
866 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
868 return Error(EndLoc, "unexpected modifier on variable reference");
870 Res = Sym->getVariableValue();
874 // Otherwise create a symbol ref.
875 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
878 case AsmToken::BigNum:
879 return TokError("literal value out of range for directive");
880 case AsmToken::Integer: {
881 SMLoc Loc = getTok().getLoc();
882 int64_t IntVal = getTok().getIntVal();
883 Res = MCConstantExpr::create(IntVal, getContext());
884 EndLoc = Lexer.getTok().getEndLoc();
886 // Look for 'b' or 'f' following an Integer as a directional label
887 if (Lexer.getKind() == AsmToken::Identifier) {
888 StringRef IDVal = getTok().getString();
889 // Lookup the symbol variant if used.
890 std::pair<StringRef, StringRef> Split = IDVal.split('@');
891 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
892 if (Split.first.size() != IDVal.size()) {
893 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
894 if (Variant == MCSymbolRefExpr::VK_Invalid)
895 return TokError("invalid variant '" + Split.second + "'");
898 if (IDVal == "f" || IDVal == "b") {
900 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
901 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
902 if (IDVal == "b" && Sym->isUndefined())
903 return Error(Loc, "invalid reference to undefined symbol");
904 EndLoc = Lexer.getTok().getEndLoc();
905 Lex(); // Eat identifier.
910 case AsmToken::Real: {
911 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
912 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
913 Res = MCConstantExpr::create(IntVal, getContext());
914 EndLoc = Lexer.getTok().getEndLoc();
918 case AsmToken::Dot: {
919 // This is a '.' reference, which references the current PC. Emit a
920 // temporary label to the streamer and refer to it.
921 MCSymbol *Sym = Ctx.createTempSymbol();
923 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
924 EndLoc = Lexer.getTok().getEndLoc();
925 Lex(); // Eat identifier.
928 case AsmToken::LParen:
929 Lex(); // Eat the '('.
930 return parseParenExpr(Res, EndLoc);
931 case AsmToken::LBrac:
932 if (!PlatformParser->HasBracketExpressions())
933 return TokError("brackets expression not supported on this target");
934 Lex(); // Eat the '['.
935 return parseBracketExpr(Res, EndLoc);
936 case AsmToken::Minus:
937 Lex(); // Eat the operator.
938 if (parsePrimaryExpr(Res, EndLoc))
940 Res = MCUnaryExpr::createMinus(Res, getContext());
943 Lex(); // Eat the operator.
944 if (parsePrimaryExpr(Res, EndLoc))
946 Res = MCUnaryExpr::createPlus(Res, getContext());
948 case AsmToken::Tilde:
949 Lex(); // Eat the operator.
950 if (parsePrimaryExpr(Res, EndLoc))
952 Res = MCUnaryExpr::createNot(Res, getContext());
957 bool AsmParser::parseExpression(const MCExpr *&Res) {
959 return parseExpression(Res, EndLoc);
963 AsmParser::applyModifierToExpr(const MCExpr *E,
964 MCSymbolRefExpr::VariantKind Variant) {
965 // Ask the target implementation about this expression first.
966 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
969 // Recurse over the given expression, rebuilding it to apply the given variant
970 // if there is exactly one symbol.
971 switch (E->getKind()) {
973 case MCExpr::Constant:
976 case MCExpr::SymbolRef: {
977 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
979 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
980 TokError("invalid variant on expression '" + getTok().getIdentifier() +
981 "' (already modified)");
985 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
988 case MCExpr::Unary: {
989 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
990 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
993 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
996 case MCExpr::Binary: {
997 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
998 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
999 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1009 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1013 llvm_unreachable("Invalid expression kind!");
1016 /// \brief Parse an expression and return it.
1018 /// expr ::= expr &&,|| expr -> lowest.
1019 /// expr ::= expr |,^,&,! expr
1020 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1021 /// expr ::= expr <<,>> expr
1022 /// expr ::= expr +,- expr
1023 /// expr ::= expr *,/,% expr -> highest.
1024 /// expr ::= primaryexpr
1026 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1027 // Parse the expression.
1029 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1032 // As a special case, we support 'a op b @ modifier' by rewriting the
1033 // expression to include the modifier. This is inefficient, but in general we
1034 // expect users to use 'a@modifier op b'.
1035 if (Lexer.getKind() == AsmToken::At) {
1038 if (Lexer.isNot(AsmToken::Identifier))
1039 return TokError("unexpected symbol modifier following '@'");
1041 MCSymbolRefExpr::VariantKind Variant =
1042 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1043 if (Variant == MCSymbolRefExpr::VK_Invalid)
1044 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1046 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1048 return TokError("invalid modifier '" + getTok().getIdentifier() +
1049 "' (no symbols present)");
1056 // Try to constant fold it up front, if possible.
1058 if (Res->evaluateAsAbsolute(Value))
1059 Res = MCConstantExpr::create(Value, getContext());
1064 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1066 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1069 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1072 SMLoc StartLoc = Lexer.getLoc();
1073 if (parseExpression(Expr))
1076 if (!Expr->evaluateAsAbsolute(Res))
1077 return Error(StartLoc, "expected absolute expression");
1082 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1083 MCBinaryExpr::Opcode &Kind) {
1086 return 0; // not a binop.
1088 // Lowest Precedence: &&, ||
1089 case AsmToken::AmpAmp:
1090 Kind = MCBinaryExpr::LAnd;
1092 case AsmToken::PipePipe:
1093 Kind = MCBinaryExpr::LOr;
1096 // Low Precedence: |, &, ^
1098 // FIXME: gas seems to support '!' as an infix operator?
1099 case AsmToken::Pipe:
1100 Kind = MCBinaryExpr::Or;
1102 case AsmToken::Caret:
1103 Kind = MCBinaryExpr::Xor;
1106 Kind = MCBinaryExpr::And;
1109 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1110 case AsmToken::EqualEqual:
1111 Kind = MCBinaryExpr::EQ;
1113 case AsmToken::ExclaimEqual:
1114 case AsmToken::LessGreater:
1115 Kind = MCBinaryExpr::NE;
1117 case AsmToken::Less:
1118 Kind = MCBinaryExpr::LT;
1120 case AsmToken::LessEqual:
1121 Kind = MCBinaryExpr::LTE;
1123 case AsmToken::Greater:
1124 Kind = MCBinaryExpr::GT;
1126 case AsmToken::GreaterEqual:
1127 Kind = MCBinaryExpr::GTE;
1130 // Intermediate Precedence: <<, >>
1131 case AsmToken::LessLess:
1132 Kind = MCBinaryExpr::Shl;
1134 case AsmToken::GreaterGreater:
1135 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1138 // High Intermediate Precedence: +, -
1139 case AsmToken::Plus:
1140 Kind = MCBinaryExpr::Add;
1142 case AsmToken::Minus:
1143 Kind = MCBinaryExpr::Sub;
1146 // Highest Precedence: *, /, %
1147 case AsmToken::Star:
1148 Kind = MCBinaryExpr::Mul;
1150 case AsmToken::Slash:
1151 Kind = MCBinaryExpr::Div;
1153 case AsmToken::Percent:
1154 Kind = MCBinaryExpr::Mod;
1159 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1160 /// Res contains the LHS of the expression on input.
1161 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1164 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1165 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1167 // If the next token is lower precedence than we are allowed to eat, return
1168 // successfully with what we ate already.
1169 if (TokPrec < Precedence)
1174 // Eat the next primary expression.
1176 if (parsePrimaryExpr(RHS, EndLoc))
1179 // If BinOp binds less tightly with RHS than the operator after RHS, let
1180 // the pending operator take RHS as its LHS.
1181 MCBinaryExpr::Opcode Dummy;
1182 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1183 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1186 // Merge LHS and RHS according to operator.
1187 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1192 /// ::= EndOfStatement
1193 /// ::= Label* Directive ...Operands... EndOfStatement
1194 /// ::= Label* Identifier OperandList* EndOfStatement
1195 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1196 MCAsmParserSemaCallback *SI) {
1197 if (Lexer.is(AsmToken::EndOfStatement)) {
1203 // Statements always start with an identifier or are a full line comment.
1204 AsmToken ID = getTok();
1205 SMLoc IDLoc = ID.getLoc();
1207 int64_t LocalLabelVal = -1;
1208 // A full line comment is a '#' as the first token.
1209 if (Lexer.is(AsmToken::Hash))
1210 return parseCppHashLineFilenameComment(IDLoc);
1212 // Allow an integer followed by a ':' as a directional local label.
1213 if (Lexer.is(AsmToken::Integer)) {
1214 LocalLabelVal = getTok().getIntVal();
1215 if (LocalLabelVal < 0) {
1216 if (!TheCondState.Ignore)
1217 return TokError("unexpected token at start of statement");
1220 IDVal = getTok().getString();
1221 Lex(); // Consume the integer token to be used as an identifier token.
1222 if (Lexer.getKind() != AsmToken::Colon) {
1223 if (!TheCondState.Ignore)
1224 return TokError("unexpected token at start of statement");
1227 } else if (Lexer.is(AsmToken::Dot)) {
1228 // Treat '.' as a valid identifier in this context.
1231 } else if (parseIdentifier(IDVal)) {
1232 if (!TheCondState.Ignore)
1233 return TokError("unexpected token at start of statement");
1237 // Handle conditional assembly here before checking for skipping. We
1238 // have to do this so that .endif isn't skipped in a ".if 0" block for
1240 StringMap<DirectiveKind>::const_iterator DirKindIt =
1241 DirectiveKindMap.find(IDVal);
1242 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1244 : DirKindIt->getValue();
1255 return parseDirectiveIf(IDLoc, DirKind);
1257 return parseDirectiveIfb(IDLoc, true);
1259 return parseDirectiveIfb(IDLoc, false);
1261 return parseDirectiveIfc(IDLoc, true);
1263 return parseDirectiveIfeqs(IDLoc, true);
1265 return parseDirectiveIfc(IDLoc, false);
1267 return parseDirectiveIfeqs(IDLoc, false);
1269 return parseDirectiveIfdef(IDLoc, true);
1272 return parseDirectiveIfdef(IDLoc, false);
1274 return parseDirectiveElseIf(IDLoc);
1276 return parseDirectiveElse(IDLoc);
1278 return parseDirectiveEndIf(IDLoc);
1281 // Ignore the statement if in the middle of inactive conditional
1283 if (TheCondState.Ignore) {
1284 eatToEndOfStatement();
1288 // FIXME: Recurse on local labels?
1290 // See what kind of statement we have.
1291 switch (Lexer.getKind()) {
1292 case AsmToken::Colon: {
1293 checkForValidSection();
1295 // identifier ':' -> Label.
1298 // Diagnose attempt to use '.' as a label.
1300 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1302 // Diagnose attempt to use a variable as a label.
1304 // FIXME: Diagnostics. Note the location of the definition as a label.
1305 // FIXME: This doesn't diagnose assignment to a symbol which has been
1306 // implicitly marked as external.
1308 if (LocalLabelVal == -1) {
1309 if (ParsingInlineAsm && SI) {
1310 StringRef RewrittenLabel =
1311 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1312 assert(RewrittenLabel.size() &&
1313 "We should have an internal name here.");
1314 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1315 IDVal.size(), RewrittenLabel));
1316 IDVal = RewrittenLabel;
1318 Sym = getContext().getOrCreateSymbol(IDVal);
1320 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1322 Sym->redefineIfPossible();
1324 if (!Sym->isUndefined() || Sym->isVariable())
1325 return Error(IDLoc, "invalid symbol redefinition");
1328 if (!ParsingInlineAsm)
1331 // If we are generating dwarf for assembly source files then gather the
1332 // info to make a dwarf label entry for this label if needed.
1333 if (getContext().getGenDwarfForAssembly())
1334 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1337 getTargetParser().onLabelParsed(Sym);
1339 // Consume any end of statement token, if present, to avoid spurious
1340 // AddBlankLine calls().
1341 if (Lexer.is(AsmToken::EndOfStatement)) {
1343 if (Lexer.is(AsmToken::Eof))
1350 case AsmToken::Equal:
1351 // identifier '=' ... -> assignment statement
1354 return parseAssignment(IDVal, true);
1356 default: // Normal instruction or directive.
1360 // If macros are enabled, check to see if this is a macro instantiation.
1361 if (areMacrosEnabled())
1362 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1363 return handleMacroEntry(M, IDLoc);
1366 // Otherwise, we have a normal instruction or directive.
1368 // Directives start with "."
1369 if (IDVal[0] == '.' && IDVal != ".") {
1370 // There are several entities interested in parsing directives:
1372 // 1. The target-specific assembly parser. Some directives are target
1373 // specific or may potentially behave differently on certain targets.
1374 // 2. Asm parser extensions. For example, platform-specific parsers
1375 // (like the ELF parser) register themselves as extensions.
1376 // 3. The generic directive parser implemented by this class. These are
1377 // all the directives that behave in a target and platform independent
1378 // manner, or at least have a default behavior that's shared between
1379 // all targets and platforms.
1381 // First query the target-specific parser. It will return 'true' if it
1382 // isn't interested in this directive.
1383 if (!getTargetParser().ParseDirective(ID))
1386 // Next, check the extension directive map to see if any extension has
1387 // registered itself to parse this directive.
1388 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1389 ExtensionDirectiveMap.lookup(IDVal);
1391 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1393 // Finally, if no one else is interested in this directive, it must be
1394 // generic and familiar to this class.
1400 return parseDirectiveSet(IDVal, true);
1402 return parseDirectiveSet(IDVal, false);
1404 return parseDirectiveAscii(IDVal, false);
1407 return parseDirectiveAscii(IDVal, true);
1409 return parseDirectiveValue(1);
1413 return parseDirectiveValue(2);
1417 return parseDirectiveValue(4);
1420 return parseDirectiveValue(8);
1422 return parseDirectiveOctaValue();
1425 return parseDirectiveRealValue(APFloat::IEEEsingle);
1427 return parseDirectiveRealValue(APFloat::IEEEdouble);
1429 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1430 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1433 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1434 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1437 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1439 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1441 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1443 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1445 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1447 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1449 return parseDirectiveOrg();
1451 return parseDirectiveFill();
1453 return parseDirectiveZero();
1455 eatToEndOfStatement(); // .extern is the default, ignore it.
1459 return parseDirectiveSymbolAttribute(MCSA_Global);
1460 case DK_LAZY_REFERENCE:
1461 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1462 case DK_NO_DEAD_STRIP:
1463 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1464 case DK_SYMBOL_RESOLVER:
1465 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1466 case DK_PRIVATE_EXTERN:
1467 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1469 return parseDirectiveSymbolAttribute(MCSA_Reference);
1470 case DK_WEAK_DEFINITION:
1471 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1472 case DK_WEAK_REFERENCE:
1473 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1474 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1475 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1478 return parseDirectiveComm(/*IsLocal=*/false);
1480 return parseDirectiveComm(/*IsLocal=*/true);
1482 return parseDirectiveAbort();
1484 return parseDirectiveInclude();
1486 return parseDirectiveIncbin();
1489 return TokError(Twine(IDVal) + " not supported yet");
1491 return parseDirectiveRept(IDLoc, IDVal);
1493 return parseDirectiveIrp(IDLoc);
1495 return parseDirectiveIrpc(IDLoc);
1497 return parseDirectiveEndr(IDLoc);
1498 case DK_BUNDLE_ALIGN_MODE:
1499 return parseDirectiveBundleAlignMode();
1500 case DK_BUNDLE_LOCK:
1501 return parseDirectiveBundleLock();
1502 case DK_BUNDLE_UNLOCK:
1503 return parseDirectiveBundleUnlock();
1505 return parseDirectiveLEB128(true);
1507 return parseDirectiveLEB128(false);
1510 return parseDirectiveSpace(IDVal);
1512 return parseDirectiveFile(IDLoc);
1514 return parseDirectiveLine();
1516 return parseDirectiveLoc();
1518 return parseDirectiveStabs();
1519 case DK_CFI_SECTIONS:
1520 return parseDirectiveCFISections();
1521 case DK_CFI_STARTPROC:
1522 return parseDirectiveCFIStartProc();
1523 case DK_CFI_ENDPROC:
1524 return parseDirectiveCFIEndProc();
1525 case DK_CFI_DEF_CFA:
1526 return parseDirectiveCFIDefCfa(IDLoc);
1527 case DK_CFI_DEF_CFA_OFFSET:
1528 return parseDirectiveCFIDefCfaOffset();
1529 case DK_CFI_ADJUST_CFA_OFFSET:
1530 return parseDirectiveCFIAdjustCfaOffset();
1531 case DK_CFI_DEF_CFA_REGISTER:
1532 return parseDirectiveCFIDefCfaRegister(IDLoc);
1534 return parseDirectiveCFIOffset(IDLoc);
1535 case DK_CFI_REL_OFFSET:
1536 return parseDirectiveCFIRelOffset(IDLoc);
1537 case DK_CFI_PERSONALITY:
1538 return parseDirectiveCFIPersonalityOrLsda(true);
1540 return parseDirectiveCFIPersonalityOrLsda(false);
1541 case DK_CFI_REMEMBER_STATE:
1542 return parseDirectiveCFIRememberState();
1543 case DK_CFI_RESTORE_STATE:
1544 return parseDirectiveCFIRestoreState();
1545 case DK_CFI_SAME_VALUE:
1546 return parseDirectiveCFISameValue(IDLoc);
1547 case DK_CFI_RESTORE:
1548 return parseDirectiveCFIRestore(IDLoc);
1550 return parseDirectiveCFIEscape();
1551 case DK_CFI_SIGNAL_FRAME:
1552 return parseDirectiveCFISignalFrame();
1553 case DK_CFI_UNDEFINED:
1554 return parseDirectiveCFIUndefined(IDLoc);
1555 case DK_CFI_REGISTER:
1556 return parseDirectiveCFIRegister(IDLoc);
1557 case DK_CFI_WINDOW_SAVE:
1558 return parseDirectiveCFIWindowSave();
1561 return parseDirectiveMacrosOnOff(IDVal);
1563 return parseDirectiveMacro(IDLoc);
1565 return parseDirectiveExitMacro(IDVal);
1568 return parseDirectiveEndMacro(IDVal);
1570 return parseDirectivePurgeMacro(IDLoc);
1572 return parseDirectiveEnd(IDLoc);
1574 return parseDirectiveError(IDLoc, false);
1576 return parseDirectiveError(IDLoc, true);
1578 return parseDirectiveWarning(IDLoc);
1581 return Error(IDLoc, "unknown directive");
1584 // __asm _emit or __asm __emit
1585 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1586 IDVal == "_EMIT" || IDVal == "__EMIT"))
1587 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1590 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1591 return parseDirectiveMSAlign(IDLoc, Info);
1593 checkForValidSection();
1595 // Canonicalize the opcode to lower case.
1596 std::string OpcodeStr = IDVal.lower();
1597 ParseInstructionInfo IInfo(Info.AsmRewrites);
1598 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1599 Info.ParsedOperands);
1600 Info.ParseError = HadError;
1602 // Dump the parsed representation, if requested.
1603 if (getShowParsedOperands()) {
1604 SmallString<256> Str;
1605 raw_svector_ostream OS(Str);
1606 OS << "parsed instruction: [";
1607 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1610 Info.ParsedOperands[i]->print(OS);
1614 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1617 // If we are generating dwarf for the current section then generate a .loc
1618 // directive for the instruction.
1619 if (!HadError && getContext().getGenDwarfForAssembly() &&
1620 getContext().getGenDwarfSectionSyms().count(
1621 getStreamer().getCurrentSection().first)) {
1623 if (ActiveMacros.empty())
1624 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1626 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1627 ActiveMacros.back()->ExitBuffer);
1629 // If we previously parsed a cpp hash file line comment then make sure the
1630 // current Dwarf File is for the CppHashFilename if not then emit the
1631 // Dwarf File table for it and adjust the line number for the .loc.
1632 if (CppHashFilename.size()) {
1633 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1634 0, StringRef(), CppHashFilename);
1635 getContext().setGenDwarfFileNumber(FileNumber);
1637 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1638 // cache with the different Loc from the call above we save the last
1639 // info we queried here with SrcMgr.FindLineNumber().
1640 unsigned CppHashLocLineNo;
1641 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1642 CppHashLocLineNo = LastQueryLine;
1644 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1645 LastQueryLine = CppHashLocLineNo;
1646 LastQueryIDLoc = CppHashLoc;
1647 LastQueryBuffer = CppHashBuf;
1649 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1652 getStreamer().EmitDwarfLocDirective(
1653 getContext().getGenDwarfFileNumber(), Line, 0,
1654 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1658 // If parsing succeeded, match the instruction.
1661 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1662 Info.ParsedOperands, Out,
1663 ErrorInfo, ParsingInlineAsm);
1666 // Don't skip the rest of the line, the instruction parser is responsible for
1671 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1672 /// since they may not be able to be tokenized to get to the end of line token.
1673 void AsmParser::eatToEndOfLine() {
1674 if (!Lexer.is(AsmToken::EndOfStatement))
1675 Lexer.LexUntilEndOfLine();
1680 /// parseCppHashLineFilenameComment as this:
1681 /// ::= # number "filename"
1682 /// or just as a full line comment if it doesn't have a number and a string.
1683 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1684 Lex(); // Eat the hash token.
1686 if (getLexer().isNot(AsmToken::Integer)) {
1687 // Consume the line since in cases it is not a well-formed line directive,
1688 // as if were simply a full line comment.
1693 int64_t LineNumber = getTok().getIntVal();
1696 if (getLexer().isNot(AsmToken::String)) {
1701 StringRef Filename = getTok().getString();
1702 // Get rid of the enclosing quotes.
1703 Filename = Filename.substr(1, Filename.size() - 2);
1705 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1707 CppHashFilename = Filename;
1708 CppHashLineNumber = LineNumber;
1709 CppHashBuf = CurBuffer;
1711 // Ignore any trailing characters, they're just comment.
1716 /// \brief will use the last parsed cpp hash line filename comment
1717 /// for the Filename and LineNo if any in the diagnostic.
1718 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1719 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1720 raw_ostream &OS = errs();
1722 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1723 const SMLoc &DiagLoc = Diag.getLoc();
1724 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1725 unsigned CppHashBuf =
1726 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1728 // Like SourceMgr::printMessage() we need to print the include stack if any
1729 // before printing the message.
1730 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1731 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1732 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1733 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1734 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1737 // If we have not parsed a cpp hash line filename comment or the source
1738 // manager changed or buffer changed (like in a nested include) then just
1739 // print the normal diagnostic using its Filename and LineNo.
1740 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1741 DiagBuf != CppHashBuf) {
1742 if (Parser->SavedDiagHandler)
1743 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1745 Diag.print(nullptr, OS);
1749 // Use the CppHashFilename and calculate a line number based on the
1750 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1752 const std::string &Filename = Parser->CppHashFilename;
1754 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1755 int CppHashLocLineNo =
1756 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1758 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1760 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1761 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1762 Diag.getLineContents(), Diag.getRanges());
1764 if (Parser->SavedDiagHandler)
1765 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1767 NewDiag.print(nullptr, OS);
1770 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1771 // difference being that that function accepts '@' as part of identifiers and
1772 // we can't do that. AsmLexer.cpp should probably be changed to handle
1773 // '@' as a special case when needed.
1774 static bool isIdentifierChar(char c) {
1775 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1779 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1780 ArrayRef<MCAsmMacroParameter> Parameters,
1781 ArrayRef<MCAsmMacroArgument> A,
1782 bool EnableAtPseudoVariable, const SMLoc &L) {
1783 unsigned NParameters = Parameters.size();
1784 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1785 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1786 return Error(L, "Wrong number of arguments");
1788 // A macro without parameters is handled differently on Darwin:
1789 // gas accepts no arguments and does no substitutions
1790 while (!Body.empty()) {
1791 // Scan for the next substitution.
1792 std::size_t End = Body.size(), Pos = 0;
1793 for (; Pos != End; ++Pos) {
1794 // Check for a substitution or escape.
1795 if (IsDarwin && !NParameters) {
1796 // This macro has no parameters, look for $0, $1, etc.
1797 if (Body[Pos] != '$' || Pos + 1 == End)
1800 char Next = Body[Pos + 1];
1801 if (Next == '$' || Next == 'n' ||
1802 isdigit(static_cast<unsigned char>(Next)))
1805 // This macro has parameters, look for \foo, \bar, etc.
1806 if (Body[Pos] == '\\' && Pos + 1 != End)
1812 OS << Body.slice(0, Pos);
1814 // Check if we reached the end.
1818 if (IsDarwin && !NParameters) {
1819 switch (Body[Pos + 1]) {
1825 // $n => number of arguments
1830 // $[0-9] => argument
1832 // Missing arguments are ignored.
1833 unsigned Index = Body[Pos + 1] - '0';
1834 if (Index >= A.size())
1837 // Otherwise substitute with the token values, with spaces eliminated.
1838 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1839 ie = A[Index].end();
1841 OS << it->getString();
1847 unsigned I = Pos + 1;
1849 // Check for the \@ pseudo-variable.
1850 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1853 while (isIdentifierChar(Body[I]) && I + 1 != End)
1856 const char *Begin = Body.data() + Pos + 1;
1857 StringRef Argument(Begin, I - (Pos + 1));
1860 if (Argument == "@") {
1861 OS << NumOfMacroInstantiations;
1864 for (; Index < NParameters; ++Index)
1865 if (Parameters[Index].Name == Argument)
1868 if (Index == NParameters) {
1869 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1872 OS << '\\' << Argument;
1876 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1877 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1878 ie = A[Index].end();
1880 // We expect no quotes around the string's contents when
1881 // parsing for varargs.
1882 if (it->getKind() != AsmToken::String || VarargParameter)
1883 OS << it->getString();
1885 OS << it->getStringContents();
1887 Pos += 1 + Argument.size();
1891 // Update the scan point.
1892 Body = Body.substr(Pos);
1898 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1899 size_t CondStackDepth)
1900 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1901 CondStackDepth(CondStackDepth) {}
1903 static bool isOperator(AsmToken::TokenKind kind) {
1907 case AsmToken::Plus:
1908 case AsmToken::Minus:
1909 case AsmToken::Tilde:
1910 case AsmToken::Slash:
1911 case AsmToken::Star:
1913 case AsmToken::Equal:
1914 case AsmToken::EqualEqual:
1915 case AsmToken::Pipe:
1916 case AsmToken::PipePipe:
1917 case AsmToken::Caret:
1919 case AsmToken::AmpAmp:
1920 case AsmToken::Exclaim:
1921 case AsmToken::ExclaimEqual:
1922 case AsmToken::Percent:
1923 case AsmToken::Less:
1924 case AsmToken::LessEqual:
1925 case AsmToken::LessLess:
1926 case AsmToken::LessGreater:
1927 case AsmToken::Greater:
1928 case AsmToken::GreaterEqual:
1929 case AsmToken::GreaterGreater:
1935 class AsmLexerSkipSpaceRAII {
1937 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1938 Lexer.setSkipSpace(SkipSpace);
1941 ~AsmLexerSkipSpaceRAII() {
1942 Lexer.setSkipSpace(true);
1950 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1953 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1954 StringRef Str = parseStringToEndOfStatement();
1955 MA.emplace_back(AsmToken::String, Str);
1960 unsigned ParenLevel = 0;
1961 unsigned AddTokens = 0;
1963 // Darwin doesn't use spaces to delmit arguments.
1964 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1967 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1968 return TokError("unexpected token in macro instantiation");
1970 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1973 if (Lexer.is(AsmToken::Space)) {
1974 Lex(); // Eat spaces
1976 // Spaces can delimit parameters, but could also be part an expression.
1977 // If the token after a space is an operator, add the token and the next
1978 // one into this argument
1980 if (isOperator(Lexer.getKind())) {
1981 // Check to see whether the token is used as an operator,
1982 // or part of an identifier
1983 const char *NextChar = getTok().getEndLoc().getPointer();
1984 if (*NextChar == ' ')
1988 if (!AddTokens && ParenLevel == 0) {
1994 // handleMacroEntry relies on not advancing the lexer here
1995 // to be able to fill in the remaining default parameter values
1996 if (Lexer.is(AsmToken::EndOfStatement))
1999 // Adjust the current parentheses level.
2000 if (Lexer.is(AsmToken::LParen))
2002 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2005 // Append the token to the current argument list.
2006 MA.push_back(getTok());
2012 if (ParenLevel != 0)
2013 return TokError("unbalanced parentheses in macro argument");
2017 // Parse the macro instantiation arguments.
2018 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2019 MCAsmMacroArguments &A) {
2020 const unsigned NParameters = M ? M->Parameters.size() : 0;
2021 bool NamedParametersFound = false;
2022 SmallVector<SMLoc, 4> FALocs;
2024 A.resize(NParameters);
2025 FALocs.resize(NParameters);
2027 // Parse two kinds of macro invocations:
2028 // - macros defined without any parameters accept an arbitrary number of them
2029 // - macros defined with parameters accept at most that many of them
2030 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2031 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2033 SMLoc IDLoc = Lexer.getLoc();
2034 MCAsmMacroParameter FA;
2036 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2037 if (parseIdentifier(FA.Name)) {
2038 Error(IDLoc, "invalid argument identifier for formal argument");
2039 eatToEndOfStatement();
2043 if (!Lexer.is(AsmToken::Equal)) {
2044 TokError("expected '=' after formal parameter identifier");
2045 eatToEndOfStatement();
2050 NamedParametersFound = true;
2053 if (NamedParametersFound && FA.Name.empty()) {
2054 Error(IDLoc, "cannot mix positional and keyword arguments");
2055 eatToEndOfStatement();
2059 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2060 if (parseMacroArgument(FA.Value, Vararg))
2063 unsigned PI = Parameter;
2064 if (!FA.Name.empty()) {
2066 for (FAI = 0; FAI < NParameters; ++FAI)
2067 if (M->Parameters[FAI].Name == FA.Name)
2070 if (FAI >= NParameters) {
2071 assert(M && "expected macro to be defined");
2073 "parameter named '" + FA.Name + "' does not exist for macro '" +
2080 if (!FA.Value.empty()) {
2085 if (FALocs.size() <= PI)
2086 FALocs.resize(PI + 1);
2088 FALocs[PI] = Lexer.getLoc();
2091 // At the end of the statement, fill in remaining arguments that have
2092 // default values. If there aren't any, then the next argument is
2093 // required but missing
2094 if (Lexer.is(AsmToken::EndOfStatement)) {
2095 bool Failure = false;
2096 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2097 if (A[FAI].empty()) {
2098 if (M->Parameters[FAI].Required) {
2099 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2100 "missing value for required parameter "
2101 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2105 if (!M->Parameters[FAI].Value.empty())
2106 A[FAI] = M->Parameters[FAI].Value;
2112 if (Lexer.is(AsmToken::Comma))
2116 return TokError("too many positional arguments");
2119 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2120 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2121 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2124 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2125 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2128 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2130 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2131 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2132 // this, although we should protect against infinite loops.
2133 if (ActiveMacros.size() == 20)
2134 return TokError("macros cannot be nested more than 20 levels deep");
2136 MCAsmMacroArguments A;
2137 if (parseMacroArguments(M, A))
2140 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2141 // to hold the macro body with substitutions.
2142 SmallString<256> Buf;
2143 StringRef Body = M->Body;
2144 raw_svector_ostream OS(Buf);
2146 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2149 // We include the .endmacro in the buffer as our cue to exit the macro
2151 OS << ".endmacro\n";
2153 std::unique_ptr<MemoryBuffer> Instantiation =
2154 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2156 // Create the macro instantiation object and add to the current macro
2157 // instantiation stack.
2158 MacroInstantiation *MI = new MacroInstantiation(
2159 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2160 ActiveMacros.push_back(MI);
2162 ++NumOfMacroInstantiations;
2164 // Jump to the macro instantiation and prime the lexer.
2165 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2166 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2172 void AsmParser::handleMacroExit() {
2173 // Jump to the EndOfStatement we should return to, and consume it.
2174 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2177 // Pop the instantiation entry.
2178 delete ActiveMacros.back();
2179 ActiveMacros.pop_back();
2182 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2185 const MCExpr *Value;
2186 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2191 // In the case where we parse an expression starting with a '.', we will
2192 // not generate an error, nor will we create a symbol. In this case we
2193 // should just return out.
2197 // Do the assignment.
2198 Out.EmitAssignment(Sym, Value);
2200 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2205 /// parseIdentifier:
2208 bool AsmParser::parseIdentifier(StringRef &Res) {
2209 // The assembler has relaxed rules for accepting identifiers, in particular we
2210 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2211 // separate tokens. At this level, we have already lexed so we cannot (currently)
2212 // handle this as a context dependent token, instead we detect adjacent tokens
2213 // and return the combined identifier.
2214 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2215 SMLoc PrefixLoc = getLexer().getLoc();
2217 // Consume the prefix character, and check for a following identifier.
2219 if (Lexer.isNot(AsmToken::Identifier))
2222 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2223 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2226 // Construct the joined identifier and consume the token.
2228 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2233 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2236 Res = getTok().getIdentifier();
2238 Lex(); // Consume the identifier token.
2243 /// parseDirectiveSet:
2244 /// ::= .equ identifier ',' expression
2245 /// ::= .equiv identifier ',' expression
2246 /// ::= .set identifier ',' expression
2247 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2250 if (parseIdentifier(Name))
2251 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2253 if (getLexer().isNot(AsmToken::Comma))
2254 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2257 return parseAssignment(Name, allow_redef, true);
2260 bool AsmParser::parseEscapedString(std::string &Data) {
2261 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2264 StringRef Str = getTok().getStringContents();
2265 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2266 if (Str[i] != '\\') {
2271 // Recognize escaped characters. Note that this escape semantics currently
2272 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2275 return TokError("unexpected backslash at end of string");
2277 // Recognize octal sequences.
2278 if ((unsigned)(Str[i] - '0') <= 7) {
2279 // Consume up to three octal characters.
2280 unsigned Value = Str[i] - '0';
2282 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2284 Value = Value * 8 + (Str[i] - '0');
2286 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2288 Value = Value * 8 + (Str[i] - '0');
2293 return TokError("invalid octal escape sequence (out of range)");
2295 Data += (unsigned char)Value;
2299 // Otherwise recognize individual escapes.
2302 // Just reject invalid escape sequences for now.
2303 return TokError("invalid escape sequence (unrecognized character)");
2305 case 'b': Data += '\b'; break;
2306 case 'f': Data += '\f'; break;
2307 case 'n': Data += '\n'; break;
2308 case 'r': Data += '\r'; break;
2309 case 't': Data += '\t'; break;
2310 case '"': Data += '"'; break;
2311 case '\\': Data += '\\'; break;
2318 /// parseDirectiveAscii:
2319 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2320 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2322 checkForValidSection();
2325 if (getLexer().isNot(AsmToken::String))
2326 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2329 if (parseEscapedString(Data))
2332 getStreamer().EmitBytes(Data);
2334 getStreamer().EmitBytes(StringRef("\0", 1));
2338 if (getLexer().is(AsmToken::EndOfStatement))
2341 if (getLexer().isNot(AsmToken::Comma))
2342 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2351 /// parseDirectiveValue
2352 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2353 bool AsmParser::parseDirectiveValue(unsigned Size) {
2354 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2355 checkForValidSection();
2358 const MCExpr *Value;
2359 SMLoc ExprLoc = getLexer().getLoc();
2360 if (parseExpression(Value))
2363 // Special case constant expressions to match code generator.
2364 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2365 assert(Size <= 8 && "Invalid size");
2366 uint64_t IntValue = MCE->getValue();
2367 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2368 return Error(ExprLoc, "literal value out of range for directive");
2369 getStreamer().EmitIntValue(IntValue, Size);
2371 getStreamer().EmitValue(Value, Size, ExprLoc);
2373 if (getLexer().is(AsmToken::EndOfStatement))
2376 // FIXME: Improve diagnostic.
2377 if (getLexer().isNot(AsmToken::Comma))
2378 return TokError("unexpected token in directive");
2387 /// ParseDirectiveOctaValue
2388 /// ::= .octa [ hexconstant (, hexconstant)* ]
2389 bool AsmParser::parseDirectiveOctaValue() {
2390 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2391 checkForValidSection();
2394 if (Lexer.getKind() == AsmToken::Error)
2396 if (Lexer.getKind() != AsmToken::Integer &&
2397 Lexer.getKind() != AsmToken::BigNum)
2398 return TokError("unknown token in expression");
2400 SMLoc ExprLoc = getLexer().getLoc();
2401 APInt IntValue = getTok().getAPIntVal();
2405 if (IntValue.isIntN(64)) {
2407 lo = IntValue.getZExtValue();
2408 } else if (IntValue.isIntN(128)) {
2409 // It might actually have more than 128 bits, but the top ones are zero.
2410 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2411 lo = IntValue.getLoBits(64).getZExtValue();
2413 return Error(ExprLoc, "literal value out of range for directive");
2415 if (MAI.isLittleEndian()) {
2416 getStreamer().EmitIntValue(lo, 8);
2417 getStreamer().EmitIntValue(hi, 8);
2419 getStreamer().EmitIntValue(hi, 8);
2420 getStreamer().EmitIntValue(lo, 8);
2423 if (getLexer().is(AsmToken::EndOfStatement))
2426 // FIXME: Improve diagnostic.
2427 if (getLexer().isNot(AsmToken::Comma))
2428 return TokError("unexpected token in directive");
2437 /// parseDirectiveRealValue
2438 /// ::= (.single | .double) [ expression (, expression)* ]
2439 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2440 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2441 checkForValidSection();
2444 // We don't truly support arithmetic on floating point expressions, so we
2445 // have to manually parse unary prefixes.
2447 if (getLexer().is(AsmToken::Minus)) {
2450 } else if (getLexer().is(AsmToken::Plus))
2453 if (getLexer().isNot(AsmToken::Integer) &&
2454 getLexer().isNot(AsmToken::Real) &&
2455 getLexer().isNot(AsmToken::Identifier))
2456 return TokError("unexpected token in directive");
2458 // Convert to an APFloat.
2459 APFloat Value(Semantics);
2460 StringRef IDVal = getTok().getString();
2461 if (getLexer().is(AsmToken::Identifier)) {
2462 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2463 Value = APFloat::getInf(Semantics);
2464 else if (!IDVal.compare_lower("nan"))
2465 Value = APFloat::getNaN(Semantics, false, ~0);
2467 return TokError("invalid floating point literal");
2468 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2469 APFloat::opInvalidOp)
2470 return TokError("invalid floating point literal");
2474 // Consume the numeric token.
2477 // Emit the value as an integer.
2478 APInt AsInt = Value.bitcastToAPInt();
2479 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2480 AsInt.getBitWidth() / 8);
2482 if (getLexer().is(AsmToken::EndOfStatement))
2485 if (getLexer().isNot(AsmToken::Comma))
2486 return TokError("unexpected token in directive");
2495 /// parseDirectiveZero
2496 /// ::= .zero expression
2497 bool AsmParser::parseDirectiveZero() {
2498 checkForValidSection();
2501 if (parseAbsoluteExpression(NumBytes))
2505 if (getLexer().is(AsmToken::Comma)) {
2507 if (parseAbsoluteExpression(Val))
2511 if (getLexer().isNot(AsmToken::EndOfStatement))
2512 return TokError("unexpected token in '.zero' directive");
2516 getStreamer().EmitFill(NumBytes, Val);
2521 /// parseDirectiveFill
2522 /// ::= .fill expression [ , expression [ , expression ] ]
2523 bool AsmParser::parseDirectiveFill() {
2524 checkForValidSection();
2526 SMLoc RepeatLoc = getLexer().getLoc();
2528 if (parseAbsoluteExpression(NumValues))
2531 if (NumValues < 0) {
2533 "'.fill' directive with negative repeat count has no effect");
2537 int64_t FillSize = 1;
2538 int64_t FillExpr = 0;
2540 SMLoc SizeLoc, ExprLoc;
2541 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return TokError("unexpected token in '.fill' directive");
2546 SizeLoc = getLexer().getLoc();
2547 if (parseAbsoluteExpression(FillSize))
2550 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2551 if (getLexer().isNot(AsmToken::Comma))
2552 return TokError("unexpected token in '.fill' directive");
2555 ExprLoc = getLexer().getLoc();
2556 if (parseAbsoluteExpression(FillExpr))
2559 if (getLexer().isNot(AsmToken::EndOfStatement))
2560 return TokError("unexpected token in '.fill' directive");
2567 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2571 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2575 if (!isUInt<32>(FillExpr) && FillSize > 4)
2576 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2578 if (NumValues > 0) {
2579 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2580 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2581 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2582 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2583 if (NonZeroFillSize < FillSize)
2584 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2591 /// parseDirectiveOrg
2592 /// ::= .org expression [ , expression ]
2593 bool AsmParser::parseDirectiveOrg() {
2594 checkForValidSection();
2596 const MCExpr *Offset;
2597 SMLoc Loc = getTok().getLoc();
2598 if (parseExpression(Offset))
2601 // Parse optional fill expression.
2602 int64_t FillExpr = 0;
2603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2604 if (getLexer().isNot(AsmToken::Comma))
2605 return TokError("unexpected token in '.org' directive");
2608 if (parseAbsoluteExpression(FillExpr))
2611 if (getLexer().isNot(AsmToken::EndOfStatement))
2612 return TokError("unexpected token in '.org' directive");
2617 // Only limited forms of relocatable expressions are accepted here, it
2618 // has to be relative to the current section. The streamer will return
2619 // 'true' if the expression wasn't evaluatable.
2620 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2621 return Error(Loc, "expected assembly-time absolute expression");
2626 /// parseDirectiveAlign
2627 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2628 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2629 checkForValidSection();
2631 SMLoc AlignmentLoc = getLexer().getLoc();
2633 if (parseAbsoluteExpression(Alignment))
2637 bool HasFillExpr = false;
2638 int64_t FillExpr = 0;
2639 int64_t MaxBytesToFill = 0;
2640 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2641 if (getLexer().isNot(AsmToken::Comma))
2642 return TokError("unexpected token in directive");
2645 // The fill expression can be omitted while specifying a maximum number of
2646 // alignment bytes, e.g:
2648 if (getLexer().isNot(AsmToken::Comma)) {
2650 if (parseAbsoluteExpression(FillExpr))
2654 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2655 if (getLexer().isNot(AsmToken::Comma))
2656 return TokError("unexpected token in directive");
2659 MaxBytesLoc = getLexer().getLoc();
2660 if (parseAbsoluteExpression(MaxBytesToFill))
2663 if (getLexer().isNot(AsmToken::EndOfStatement))
2664 return TokError("unexpected token in directive");
2673 // Compute alignment in bytes.
2675 // FIXME: Diagnose overflow.
2676 if (Alignment >= 32) {
2677 Error(AlignmentLoc, "invalid alignment value");
2681 Alignment = 1ULL << Alignment;
2683 // Reject alignments that aren't a power of two, for gas compatibility.
2684 if (!isPowerOf2_64(Alignment))
2685 Error(AlignmentLoc, "alignment must be a power of 2");
2688 // Diagnose non-sensical max bytes to align.
2689 if (MaxBytesLoc.isValid()) {
2690 if (MaxBytesToFill < 1) {
2691 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2692 "many bytes, ignoring maximum bytes expression");
2696 if (MaxBytesToFill >= Alignment) {
2697 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2703 // Check whether we should use optimal code alignment for this .align
2705 const MCSection *Section = getStreamer().getCurrentSection().first;
2706 assert(Section && "must have section to emit alignment");
2707 bool UseCodeAlign = Section->UseCodeAlign();
2708 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2709 ValueSize == 1 && UseCodeAlign) {
2710 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2712 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2713 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2720 /// parseDirectiveFile
2721 /// ::= .file [number] filename
2722 /// ::= .file number directory filename
2723 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2724 // FIXME: I'm not sure what this is.
2725 int64_t FileNumber = -1;
2726 SMLoc FileNumberLoc = getLexer().getLoc();
2727 if (getLexer().is(AsmToken::Integer)) {
2728 FileNumber = getTok().getIntVal();
2732 return TokError("file number less than one");
2735 if (getLexer().isNot(AsmToken::String))
2736 return TokError("unexpected token in '.file' directive");
2738 // Usually the directory and filename together, otherwise just the directory.
2739 // Allow the strings to have escaped octal character sequence.
2740 std::string Path = getTok().getString();
2741 if (parseEscapedString(Path))
2745 StringRef Directory;
2747 std::string FilenameData;
2748 if (getLexer().is(AsmToken::String)) {
2749 if (FileNumber == -1)
2750 return TokError("explicit path specified, but no file number");
2751 if (parseEscapedString(FilenameData))
2753 Filename = FilenameData;
2760 if (getLexer().isNot(AsmToken::EndOfStatement))
2761 return TokError("unexpected token in '.file' directive");
2763 if (FileNumber == -1)
2764 getStreamer().EmitFileDirective(Filename);
2766 if (getContext().getGenDwarfForAssembly())
2768 "input can't have .file dwarf directives when -g is "
2769 "used to generate dwarf debug info for assembly code");
2771 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2773 Error(FileNumberLoc, "file number already allocated");
2779 /// parseDirectiveLine
2780 /// ::= .line [number]
2781 bool AsmParser::parseDirectiveLine() {
2782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2783 if (getLexer().isNot(AsmToken::Integer))
2784 return TokError("unexpected token in '.line' directive");
2786 int64_t LineNumber = getTok().getIntVal();
2790 // FIXME: Do something with the .line.
2793 if (getLexer().isNot(AsmToken::EndOfStatement))
2794 return TokError("unexpected token in '.line' directive");
2799 /// parseDirectiveLoc
2800 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2801 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2802 /// The first number is a file number, must have been previously assigned with
2803 /// a .file directive, the second number is the line number and optionally the
2804 /// third number is a column position (zero if not specified). The remaining
2805 /// optional items are .loc sub-directives.
2806 bool AsmParser::parseDirectiveLoc() {
2807 if (getLexer().isNot(AsmToken::Integer))
2808 return TokError("unexpected token in '.loc' directive");
2809 int64_t FileNumber = getTok().getIntVal();
2811 return TokError("file number less than one in '.loc' directive");
2812 if (!getContext().isValidDwarfFileNumber(FileNumber))
2813 return TokError("unassigned file number in '.loc' directive");
2816 int64_t LineNumber = 0;
2817 if (getLexer().is(AsmToken::Integer)) {
2818 LineNumber = getTok().getIntVal();
2820 return TokError("line number less than zero in '.loc' directive");
2824 int64_t ColumnPos = 0;
2825 if (getLexer().is(AsmToken::Integer)) {
2826 ColumnPos = getTok().getIntVal();
2828 return TokError("column position less than zero in '.loc' directive");
2832 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2834 int64_t Discriminator = 0;
2835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2837 if (getLexer().is(AsmToken::EndOfStatement))
2841 SMLoc Loc = getTok().getLoc();
2842 if (parseIdentifier(Name))
2843 return TokError("unexpected token in '.loc' directive");
2845 if (Name == "basic_block")
2846 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2847 else if (Name == "prologue_end")
2848 Flags |= DWARF2_FLAG_PROLOGUE_END;
2849 else if (Name == "epilogue_begin")
2850 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2851 else if (Name == "is_stmt") {
2852 Loc = getTok().getLoc();
2853 const MCExpr *Value;
2854 if (parseExpression(Value))
2856 // The expression must be the constant 0 or 1.
2857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2858 int Value = MCE->getValue();
2860 Flags &= ~DWARF2_FLAG_IS_STMT;
2861 else if (Value == 1)
2862 Flags |= DWARF2_FLAG_IS_STMT;
2864 return Error(Loc, "is_stmt value not 0 or 1");
2866 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2868 } else if (Name == "isa") {
2869 Loc = getTok().getLoc();
2870 const MCExpr *Value;
2871 if (parseExpression(Value))
2873 // The expression must be a constant greater or equal to 0.
2874 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2875 int Value = MCE->getValue();
2877 return Error(Loc, "isa number less than zero");
2880 return Error(Loc, "isa number not a constant value");
2882 } else if (Name == "discriminator") {
2883 if (parseAbsoluteExpression(Discriminator))
2886 return Error(Loc, "unknown sub-directive in '.loc' directive");
2889 if (getLexer().is(AsmToken::EndOfStatement))
2894 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2895 Isa, Discriminator, StringRef());
2900 /// parseDirectiveStabs
2901 /// ::= .stabs string, number, number, number
2902 bool AsmParser::parseDirectiveStabs() {
2903 return TokError("unsupported directive '.stabs'");
2906 /// parseDirectiveCFISections
2907 /// ::= .cfi_sections section [, section]
2908 bool AsmParser::parseDirectiveCFISections() {
2913 if (parseIdentifier(Name))
2914 return TokError("Expected an identifier");
2916 if (Name == ".eh_frame")
2918 else if (Name == ".debug_frame")
2921 if (getLexer().is(AsmToken::Comma)) {
2924 if (parseIdentifier(Name))
2925 return TokError("Expected an identifier");
2927 if (Name == ".eh_frame")
2929 else if (Name == ".debug_frame")
2933 getStreamer().EmitCFISections(EH, Debug);
2937 /// parseDirectiveCFIStartProc
2938 /// ::= .cfi_startproc [simple]
2939 bool AsmParser::parseDirectiveCFIStartProc() {
2941 if (getLexer().isNot(AsmToken::EndOfStatement))
2942 if (parseIdentifier(Simple) || Simple != "simple")
2943 return TokError("unexpected token in .cfi_startproc directive");
2945 getStreamer().EmitCFIStartProc(!Simple.empty());
2949 /// parseDirectiveCFIEndProc
2950 /// ::= .cfi_endproc
2951 bool AsmParser::parseDirectiveCFIEndProc() {
2952 getStreamer().EmitCFIEndProc();
2956 /// \brief parse register name or number.
2957 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2958 SMLoc DirectiveLoc) {
2961 if (getLexer().isNot(AsmToken::Integer)) {
2962 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2964 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2966 return parseAbsoluteExpression(Register);
2971 /// parseDirectiveCFIDefCfa
2972 /// ::= .cfi_def_cfa register, offset
2973 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2974 int64_t Register = 0;
2975 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2978 if (getLexer().isNot(AsmToken::Comma))
2979 return TokError("unexpected token in directive");
2983 if (parseAbsoluteExpression(Offset))
2986 getStreamer().EmitCFIDefCfa(Register, Offset);
2990 /// parseDirectiveCFIDefCfaOffset
2991 /// ::= .cfi_def_cfa_offset offset
2992 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2994 if (parseAbsoluteExpression(Offset))
2997 getStreamer().EmitCFIDefCfaOffset(Offset);
3001 /// parseDirectiveCFIRegister
3002 /// ::= .cfi_register register, register
3003 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3004 int64_t Register1 = 0;
3005 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3008 if (getLexer().isNot(AsmToken::Comma))
3009 return TokError("unexpected token in directive");
3012 int64_t Register2 = 0;
3013 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3016 getStreamer().EmitCFIRegister(Register1, Register2);
3020 /// parseDirectiveCFIWindowSave
3021 /// ::= .cfi_window_save
3022 bool AsmParser::parseDirectiveCFIWindowSave() {
3023 getStreamer().EmitCFIWindowSave();
3027 /// parseDirectiveCFIAdjustCfaOffset
3028 /// ::= .cfi_adjust_cfa_offset adjustment
3029 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3030 int64_t Adjustment = 0;
3031 if (parseAbsoluteExpression(Adjustment))
3034 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3038 /// parseDirectiveCFIDefCfaRegister
3039 /// ::= .cfi_def_cfa_register register
3040 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3041 int64_t Register = 0;
3042 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3045 getStreamer().EmitCFIDefCfaRegister(Register);
3049 /// parseDirectiveCFIOffset
3050 /// ::= .cfi_offset register, offset
3051 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3052 int64_t Register = 0;
3055 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3058 if (getLexer().isNot(AsmToken::Comma))
3059 return TokError("unexpected token in directive");
3062 if (parseAbsoluteExpression(Offset))
3065 getStreamer().EmitCFIOffset(Register, Offset);
3069 /// parseDirectiveCFIRelOffset
3070 /// ::= .cfi_rel_offset register, offset
3071 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3072 int64_t Register = 0;
3074 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3077 if (getLexer().isNot(AsmToken::Comma))
3078 return TokError("unexpected token in directive");
3082 if (parseAbsoluteExpression(Offset))
3085 getStreamer().EmitCFIRelOffset(Register, Offset);
3089 static bool isValidEncoding(int64_t Encoding) {
3090 if (Encoding & ~0xff)
3093 if (Encoding == dwarf::DW_EH_PE_omit)
3096 const unsigned Format = Encoding & 0xf;
3097 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3098 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3099 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3100 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3103 const unsigned Application = Encoding & 0x70;
3104 if (Application != dwarf::DW_EH_PE_absptr &&
3105 Application != dwarf::DW_EH_PE_pcrel)
3111 /// parseDirectiveCFIPersonalityOrLsda
3112 /// IsPersonality true for cfi_personality, false for cfi_lsda
3113 /// ::= .cfi_personality encoding, [symbol_name]
3114 /// ::= .cfi_lsda encoding, [symbol_name]
3115 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3116 int64_t Encoding = 0;
3117 if (parseAbsoluteExpression(Encoding))
3119 if (Encoding == dwarf::DW_EH_PE_omit)
3122 if (!isValidEncoding(Encoding))
3123 return TokError("unsupported encoding.");
3125 if (getLexer().isNot(AsmToken::Comma))
3126 return TokError("unexpected token in directive");
3130 if (parseIdentifier(Name))
3131 return TokError("expected identifier in directive");
3133 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3136 getStreamer().EmitCFIPersonality(Sym, Encoding);
3138 getStreamer().EmitCFILsda(Sym, Encoding);
3142 /// parseDirectiveCFIRememberState
3143 /// ::= .cfi_remember_state
3144 bool AsmParser::parseDirectiveCFIRememberState() {
3145 getStreamer().EmitCFIRememberState();
3149 /// parseDirectiveCFIRestoreState
3150 /// ::= .cfi_remember_state
3151 bool AsmParser::parseDirectiveCFIRestoreState() {
3152 getStreamer().EmitCFIRestoreState();
3156 /// parseDirectiveCFISameValue
3157 /// ::= .cfi_same_value register
3158 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3159 int64_t Register = 0;
3161 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3164 getStreamer().EmitCFISameValue(Register);
3168 /// parseDirectiveCFIRestore
3169 /// ::= .cfi_restore register
3170 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3171 int64_t Register = 0;
3172 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3175 getStreamer().EmitCFIRestore(Register);
3179 /// parseDirectiveCFIEscape
3180 /// ::= .cfi_escape expression[,...]
3181 bool AsmParser::parseDirectiveCFIEscape() {
3184 if (parseAbsoluteExpression(CurrValue))
3187 Values.push_back((uint8_t)CurrValue);
3189 while (getLexer().is(AsmToken::Comma)) {
3192 if (parseAbsoluteExpression(CurrValue))
3195 Values.push_back((uint8_t)CurrValue);
3198 getStreamer().EmitCFIEscape(Values);
3202 /// parseDirectiveCFISignalFrame
3203 /// ::= .cfi_signal_frame
3204 bool AsmParser::parseDirectiveCFISignalFrame() {
3205 if (getLexer().isNot(AsmToken::EndOfStatement))
3206 return Error(getLexer().getLoc(),
3207 "unexpected token in '.cfi_signal_frame'");
3209 getStreamer().EmitCFISignalFrame();
3213 /// parseDirectiveCFIUndefined
3214 /// ::= .cfi_undefined register
3215 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3216 int64_t Register = 0;
3218 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3221 getStreamer().EmitCFIUndefined(Register);
3225 /// parseDirectiveMacrosOnOff
3228 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3229 if (getLexer().isNot(AsmToken::EndOfStatement))
3230 return Error(getLexer().getLoc(),
3231 "unexpected token in '" + Directive + "' directive");
3233 setMacrosEnabled(Directive == ".macros_on");
3237 /// parseDirectiveMacro
3238 /// ::= .macro name[,] [parameters]
3239 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3241 if (parseIdentifier(Name))
3242 return TokError("expected identifier in '.macro' directive");
3244 if (getLexer().is(AsmToken::Comma))
3247 MCAsmMacroParameters Parameters;
3248 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3250 if (!Parameters.empty() && Parameters.back().Vararg)
3251 return Error(Lexer.getLoc(),
3252 "Vararg parameter '" + Parameters.back().Name +
3253 "' should be last one in the list of parameters.");
3255 MCAsmMacroParameter Parameter;
3256 if (parseIdentifier(Parameter.Name))
3257 return TokError("expected identifier in '.macro' directive");
3259 if (Lexer.is(AsmToken::Colon)) {
3260 Lex(); // consume ':'
3263 StringRef Qualifier;
3265 QualLoc = Lexer.getLoc();
3266 if (parseIdentifier(Qualifier))
3267 return Error(QualLoc, "missing parameter qualifier for "
3268 "'" + Parameter.Name + "' in macro '" + Name + "'");
3270 if (Qualifier == "req")
3271 Parameter.Required = true;
3272 else if (Qualifier == "vararg")
3273 Parameter.Vararg = true;
3275 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3276 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3279 if (getLexer().is(AsmToken::Equal)) {
3284 ParamLoc = Lexer.getLoc();
3285 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3288 if (Parameter.Required)
3289 Warning(ParamLoc, "pointless default value for required parameter "
3290 "'" + Parameter.Name + "' in macro '" + Name + "'");
3293 Parameters.push_back(std::move(Parameter));
3295 if (getLexer().is(AsmToken::Comma))
3299 // Eat the end of statement.
3302 AsmToken EndToken, StartToken = getTok();
3303 unsigned MacroDepth = 0;
3305 // Lex the macro definition.
3307 // Check whether we have reached the end of the file.
3308 if (getLexer().is(AsmToken::Eof))
3309 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3311 // Otherwise, check whether we have reach the .endmacro.
3312 if (getLexer().is(AsmToken::Identifier)) {
3313 if (getTok().getIdentifier() == ".endm" ||
3314 getTok().getIdentifier() == ".endmacro") {
3315 if (MacroDepth == 0) { // Outermost macro.
3316 EndToken = getTok();
3318 if (getLexer().isNot(AsmToken::EndOfStatement))
3319 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3323 // Otherwise we just found the end of an inner macro.
3326 } else if (getTok().getIdentifier() == ".macro") {
3327 // We allow nested macros. Those aren't instantiated until the outermost
3328 // macro is expanded so just ignore them for now.
3333 // Otherwise, scan til the end of the statement.
3334 eatToEndOfStatement();
3337 if (lookupMacro(Name)) {
3338 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3341 const char *BodyStart = StartToken.getLoc().getPointer();
3342 const char *BodyEnd = EndToken.getLoc().getPointer();
3343 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3344 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3345 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3349 /// checkForBadMacro
3351 /// With the support added for named parameters there may be code out there that
3352 /// is transitioning from positional parameters. In versions of gas that did
3353 /// not support named parameters they would be ignored on the macro definition.
3354 /// But to support both styles of parameters this is not possible so if a macro
3355 /// definition has named parameters but does not use them and has what appears
3356 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3357 /// warning that the positional parameter found in body which have no effect.
3358 /// Hoping the developer will either remove the named parameters from the macro
3359 /// definition so the positional parameters get used if that was what was
3360 /// intended or change the macro to use the named parameters. It is possible
3361 /// this warning will trigger when the none of the named parameters are used
3362 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3363 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3365 ArrayRef<MCAsmMacroParameter> Parameters) {
3366 // If this macro is not defined with named parameters the warning we are
3367 // checking for here doesn't apply.
3368 unsigned NParameters = Parameters.size();
3369 if (NParameters == 0)
3372 bool NamedParametersFound = false;
3373 bool PositionalParametersFound = false;
3375 // Look at the body of the macro for use of both the named parameters and what
3376 // are likely to be positional parameters. This is what expandMacro() is
3377 // doing when it finds the parameters in the body.
3378 while (!Body.empty()) {
3379 // Scan for the next possible parameter.
3380 std::size_t End = Body.size(), Pos = 0;
3381 for (; Pos != End; ++Pos) {
3382 // Check for a substitution or escape.
3383 // This macro is defined with parameters, look for \foo, \bar, etc.
3384 if (Body[Pos] == '\\' && Pos + 1 != End)
3387 // This macro should have parameters, but look for $0, $1, ..., $n too.
3388 if (Body[Pos] != '$' || Pos + 1 == End)
3390 char Next = Body[Pos + 1];
3391 if (Next == '$' || Next == 'n' ||
3392 isdigit(static_cast<unsigned char>(Next)))
3396 // Check if we reached the end.
3400 if (Body[Pos] == '$') {
3401 switch (Body[Pos + 1]) {
3406 // $n => number of arguments
3408 PositionalParametersFound = true;
3411 // $[0-9] => argument
3413 PositionalParametersFound = true;
3419 unsigned I = Pos + 1;
3420 while (isIdentifierChar(Body[I]) && I + 1 != End)
3423 const char *Begin = Body.data() + Pos + 1;
3424 StringRef Argument(Begin, I - (Pos + 1));
3426 for (; Index < NParameters; ++Index)
3427 if (Parameters[Index].Name == Argument)
3430 if (Index == NParameters) {
3431 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3437 NamedParametersFound = true;
3438 Pos += 1 + Argument.size();
3441 // Update the scan point.
3442 Body = Body.substr(Pos);
3445 if (!NamedParametersFound && PositionalParametersFound)
3446 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3447 "used in macro body, possible positional parameter "
3448 "found in body which will have no effect");
3451 /// parseDirectiveExitMacro
3453 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3454 if (getLexer().isNot(AsmToken::EndOfStatement))
3455 return TokError("unexpected token in '" + Directive + "' directive");
3457 if (!isInsideMacroInstantiation())
3458 return TokError("unexpected '" + Directive + "' in file, "
3459 "no current macro definition");
3461 // Exit all conditionals that are active in the current macro.
3462 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3463 TheCondState = TheCondStack.back();
3464 TheCondStack.pop_back();
3471 /// parseDirectiveEndMacro
3474 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3475 if (getLexer().isNot(AsmToken::EndOfStatement))
3476 return TokError("unexpected token in '" + Directive + "' directive");
3478 // If we are inside a macro instantiation, terminate the current
3480 if (isInsideMacroInstantiation()) {
3485 // Otherwise, this .endmacro is a stray entry in the file; well formed
3486 // .endmacro directives are handled during the macro definition parsing.
3487 return TokError("unexpected '" + Directive + "' in file, "
3488 "no current macro definition");
3491 /// parseDirectivePurgeMacro
3493 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3495 if (parseIdentifier(Name))
3496 return TokError("expected identifier in '.purgem' directive");
3498 if (getLexer().isNot(AsmToken::EndOfStatement))
3499 return TokError("unexpected token in '.purgem' directive");
3501 if (!lookupMacro(Name))
3502 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3504 undefineMacro(Name);
3508 /// parseDirectiveBundleAlignMode
3509 /// ::= {.bundle_align_mode} expression
3510 bool AsmParser::parseDirectiveBundleAlignMode() {
3511 checkForValidSection();
3513 // Expect a single argument: an expression that evaluates to a constant
3514 // in the inclusive range 0-30.
3515 SMLoc ExprLoc = getLexer().getLoc();
3516 int64_t AlignSizePow2;
3517 if (parseAbsoluteExpression(AlignSizePow2))
3519 else if (getLexer().isNot(AsmToken::EndOfStatement))
3520 return TokError("unexpected token after expression in"
3521 " '.bundle_align_mode' directive");
3522 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3523 return Error(ExprLoc,
3524 "invalid bundle alignment size (expected between 0 and 30)");
3528 // Because of AlignSizePow2's verified range we can safely truncate it to
3530 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3534 /// parseDirectiveBundleLock
3535 /// ::= {.bundle_lock} [align_to_end]
3536 bool AsmParser::parseDirectiveBundleLock() {
3537 checkForValidSection();
3538 bool AlignToEnd = false;
3540 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3542 SMLoc Loc = getTok().getLoc();
3543 const char *kInvalidOptionError =
3544 "invalid option for '.bundle_lock' directive";
3546 if (parseIdentifier(Option))
3547 return Error(Loc, kInvalidOptionError);
3549 if (Option != "align_to_end")
3550 return Error(Loc, kInvalidOptionError);
3551 else if (getLexer().isNot(AsmToken::EndOfStatement))
3553 "unexpected token after '.bundle_lock' directive option");
3559 getStreamer().EmitBundleLock(AlignToEnd);
3563 /// parseDirectiveBundleLock
3564 /// ::= {.bundle_lock}
3565 bool AsmParser::parseDirectiveBundleUnlock() {
3566 checkForValidSection();
3568 if (getLexer().isNot(AsmToken::EndOfStatement))
3569 return TokError("unexpected token in '.bundle_unlock' directive");
3572 getStreamer().EmitBundleUnlock();
3576 /// parseDirectiveSpace
3577 /// ::= (.skip | .space) expression [ , expression ]
3578 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3579 checkForValidSection();
3582 if (parseAbsoluteExpression(NumBytes))
3585 int64_t FillExpr = 0;
3586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3587 if (getLexer().isNot(AsmToken::Comma))
3588 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3591 if (parseAbsoluteExpression(FillExpr))
3594 if (getLexer().isNot(AsmToken::EndOfStatement))
3595 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3601 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3604 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3605 getStreamer().EmitFill(NumBytes, FillExpr);
3610 /// parseDirectiveLEB128
3611 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3612 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3613 checkForValidSection();
3614 const MCExpr *Value;
3617 if (parseExpression(Value))
3621 getStreamer().EmitSLEB128Value(Value);
3623 getStreamer().EmitULEB128Value(Value);
3625 if (getLexer().is(AsmToken::EndOfStatement))
3628 if (getLexer().isNot(AsmToken::Comma))
3629 return TokError("unexpected token in directive");
3636 /// parseDirectiveSymbolAttribute
3637 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3638 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3639 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3642 SMLoc Loc = getTok().getLoc();
3644 if (parseIdentifier(Name))
3645 return Error(Loc, "expected identifier in directive");
3647 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3649 // Assembler local symbols don't make any sense here. Complain loudly.
3650 if (Sym->isTemporary())
3651 return Error(Loc, "non-local symbol required in directive");
3653 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3654 return Error(Loc, "unable to emit symbol attribute");
3656 if (getLexer().is(AsmToken::EndOfStatement))
3659 if (getLexer().isNot(AsmToken::Comma))
3660 return TokError("unexpected token in directive");
3669 /// parseDirectiveComm
3670 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3671 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3672 checkForValidSection();
3674 SMLoc IDLoc = getLexer().getLoc();
3676 if (parseIdentifier(Name))
3677 return TokError("expected identifier in directive");
3679 // Handle the identifier as the key symbol.
3680 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3682 if (getLexer().isNot(AsmToken::Comma))
3683 return TokError("unexpected token in directive");
3687 SMLoc SizeLoc = getLexer().getLoc();
3688 if (parseAbsoluteExpression(Size))
3691 int64_t Pow2Alignment = 0;
3692 SMLoc Pow2AlignmentLoc;
3693 if (getLexer().is(AsmToken::Comma)) {
3695 Pow2AlignmentLoc = getLexer().getLoc();
3696 if (parseAbsoluteExpression(Pow2Alignment))
3699 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3700 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3701 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3703 // If this target takes alignments in bytes (not log) validate and convert.
3704 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3705 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3706 if (!isPowerOf2_64(Pow2Alignment))
3707 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3708 Pow2Alignment = Log2_64(Pow2Alignment);
3712 if (getLexer().isNot(AsmToken::EndOfStatement))
3713 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3717 // NOTE: a size of zero for a .comm should create a undefined symbol
3718 // but a size of .lcomm creates a bss symbol of size zero.
3720 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3721 "be less than zero");
3723 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3724 // may internally end up wanting an alignment in bytes.
3725 // FIXME: Diagnose overflow.
3726 if (Pow2Alignment < 0)
3727 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3728 "alignment, can't be less than zero");
3730 if (!Sym->isUndefined())
3731 return Error(IDLoc, "invalid symbol redefinition");
3733 // Create the Symbol as a common or local common with Size and Pow2Alignment
3735 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3739 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3743 /// parseDirectiveAbort
3744 /// ::= .abort [... message ...]
3745 bool AsmParser::parseDirectiveAbort() {
3746 // FIXME: Use loc from directive.
3747 SMLoc Loc = getLexer().getLoc();
3749 StringRef Str = parseStringToEndOfStatement();
3750 if (getLexer().isNot(AsmToken::EndOfStatement))
3751 return TokError("unexpected token in '.abort' directive");
3756 Error(Loc, ".abort detected. Assembly stopping.");
3758 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3759 // FIXME: Actually abort assembly here.
3764 /// parseDirectiveInclude
3765 /// ::= .include "filename"
3766 bool AsmParser::parseDirectiveInclude() {
3767 if (getLexer().isNot(AsmToken::String))
3768 return TokError("expected string in '.include' directive");
3770 // Allow the strings to have escaped octal character sequence.
3771 std::string Filename;
3772 if (parseEscapedString(Filename))
3774 SMLoc IncludeLoc = getLexer().getLoc();
3777 if (getLexer().isNot(AsmToken::EndOfStatement))
3778 return TokError("unexpected token in '.include' directive");
3780 // Attempt to switch the lexer to the included file before consuming the end
3781 // of statement to avoid losing it when we switch.
3782 if (enterIncludeFile(Filename)) {
3783 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3790 /// parseDirectiveIncbin
3791 /// ::= .incbin "filename"
3792 bool AsmParser::parseDirectiveIncbin() {
3793 if (getLexer().isNot(AsmToken::String))
3794 return TokError("expected string in '.incbin' directive");
3796 // Allow the strings to have escaped octal character sequence.
3797 std::string Filename;
3798 if (parseEscapedString(Filename))
3800 SMLoc IncbinLoc = getLexer().getLoc();
3803 if (getLexer().isNot(AsmToken::EndOfStatement))
3804 return TokError("unexpected token in '.incbin' directive");
3806 // Attempt to process the included file.
3807 if (processIncbinFile(Filename)) {
3808 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3815 /// parseDirectiveIf
3816 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3817 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3818 TheCondStack.push_back(TheCondState);
3819 TheCondState.TheCond = AsmCond::IfCond;
3820 if (TheCondState.Ignore) {
3821 eatToEndOfStatement();
3824 if (parseAbsoluteExpression(ExprValue))
3827 if (getLexer().isNot(AsmToken::EndOfStatement))
3828 return TokError("unexpected token in '.if' directive");
3834 llvm_unreachable("unsupported directive");
3839 ExprValue = ExprValue == 0;
3842 ExprValue = ExprValue >= 0;
3845 ExprValue = ExprValue > 0;
3848 ExprValue = ExprValue <= 0;
3851 ExprValue = ExprValue < 0;
3855 TheCondState.CondMet = ExprValue;
3856 TheCondState.Ignore = !TheCondState.CondMet;
3862 /// parseDirectiveIfb
3864 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3865 TheCondStack.push_back(TheCondState);
3866 TheCondState.TheCond = AsmCond::IfCond;
3868 if (TheCondState.Ignore) {
3869 eatToEndOfStatement();
3871 StringRef Str = parseStringToEndOfStatement();
3873 if (getLexer().isNot(AsmToken::EndOfStatement))
3874 return TokError("unexpected token in '.ifb' directive");
3878 TheCondState.CondMet = ExpectBlank == Str.empty();
3879 TheCondState.Ignore = !TheCondState.CondMet;
3885 /// parseDirectiveIfc
3886 /// ::= .ifc string1, string2
3887 /// ::= .ifnc string1, string2
3888 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3889 TheCondStack.push_back(TheCondState);
3890 TheCondState.TheCond = AsmCond::IfCond;
3892 if (TheCondState.Ignore) {
3893 eatToEndOfStatement();
3895 StringRef Str1 = parseStringToComma();
3897 if (getLexer().isNot(AsmToken::Comma))
3898 return TokError("unexpected token in '.ifc' directive");
3902 StringRef Str2 = parseStringToEndOfStatement();
3904 if (getLexer().isNot(AsmToken::EndOfStatement))
3905 return TokError("unexpected token in '.ifc' directive");
3909 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3910 TheCondState.Ignore = !TheCondState.CondMet;
3916 /// parseDirectiveIfeqs
3917 /// ::= .ifeqs string1, string2
3918 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3919 if (Lexer.isNot(AsmToken::String)) {
3921 TokError("expected string parameter for '.ifeqs' directive");
3923 TokError("expected string parameter for '.ifnes' directive");
3924 eatToEndOfStatement();
3928 StringRef String1 = getTok().getStringContents();
3931 if (Lexer.isNot(AsmToken::Comma)) {
3933 TokError("expected comma after first string for '.ifeqs' directive");
3935 TokError("expected comma after first string for '.ifnes' directive");
3936 eatToEndOfStatement();
3942 if (Lexer.isNot(AsmToken::String)) {
3944 TokError("expected string parameter for '.ifeqs' directive");
3946 TokError("expected string parameter for '.ifnes' directive");
3947 eatToEndOfStatement();
3951 StringRef String2 = getTok().getStringContents();
3954 TheCondStack.push_back(TheCondState);
3955 TheCondState.TheCond = AsmCond::IfCond;
3956 TheCondState.CondMet = ExpectEqual == (String1 == String2);
3957 TheCondState.Ignore = !TheCondState.CondMet;
3962 /// parseDirectiveIfdef
3963 /// ::= .ifdef symbol
3964 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3966 TheCondStack.push_back(TheCondState);
3967 TheCondState.TheCond = AsmCond::IfCond;
3969 if (TheCondState.Ignore) {
3970 eatToEndOfStatement();
3972 if (parseIdentifier(Name))
3973 return TokError("expected identifier after '.ifdef'");
3977 MCSymbol *Sym = getContext().lookupSymbol(Name);
3980 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3982 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3983 TheCondState.Ignore = !TheCondState.CondMet;
3989 /// parseDirectiveElseIf
3990 /// ::= .elseif expression
3991 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3992 if (TheCondState.TheCond != AsmCond::IfCond &&
3993 TheCondState.TheCond != AsmCond::ElseIfCond)
3994 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3996 TheCondState.TheCond = AsmCond::ElseIfCond;
3998 bool LastIgnoreState = false;
3999 if (!TheCondStack.empty())
4000 LastIgnoreState = TheCondStack.back().Ignore;
4001 if (LastIgnoreState || TheCondState.CondMet) {
4002 TheCondState.Ignore = true;
4003 eatToEndOfStatement();
4006 if (parseAbsoluteExpression(ExprValue))
4009 if (getLexer().isNot(AsmToken::EndOfStatement))
4010 return TokError("unexpected token in '.elseif' directive");
4013 TheCondState.CondMet = ExprValue;
4014 TheCondState.Ignore = !TheCondState.CondMet;
4020 /// parseDirectiveElse
4022 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4023 if (getLexer().isNot(AsmToken::EndOfStatement))
4024 return TokError("unexpected token in '.else' directive");
4028 if (TheCondState.TheCond != AsmCond::IfCond &&
4029 TheCondState.TheCond != AsmCond::ElseIfCond)
4030 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4032 TheCondState.TheCond = AsmCond::ElseCond;
4033 bool LastIgnoreState = false;
4034 if (!TheCondStack.empty())
4035 LastIgnoreState = TheCondStack.back().Ignore;
4036 if (LastIgnoreState || TheCondState.CondMet)
4037 TheCondState.Ignore = true;
4039 TheCondState.Ignore = false;
4044 /// parseDirectiveEnd
4046 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4047 if (getLexer().isNot(AsmToken::EndOfStatement))
4048 return TokError("unexpected token in '.end' directive");
4052 while (Lexer.isNot(AsmToken::Eof))
4058 /// parseDirectiveError
4060 /// ::= .error [string]
4061 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4062 if (!TheCondStack.empty()) {
4063 if (TheCondStack.back().Ignore) {
4064 eatToEndOfStatement();
4070 return Error(L, ".err encountered");
4072 StringRef Message = ".error directive invoked in source file";
4073 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4074 if (Lexer.isNot(AsmToken::String)) {
4075 TokError(".error argument must be a string");
4076 eatToEndOfStatement();
4080 Message = getTok().getStringContents();
4088 /// parseDirectiveWarning
4089 /// ::= .warning [string]
4090 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4091 if (!TheCondStack.empty()) {
4092 if (TheCondStack.back().Ignore) {
4093 eatToEndOfStatement();
4098 StringRef Message = ".warning directive invoked in source file";
4099 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4100 if (Lexer.isNot(AsmToken::String)) {
4101 TokError(".warning argument must be a string");
4102 eatToEndOfStatement();
4106 Message = getTok().getStringContents();
4110 Warning(L, Message);
4114 /// parseDirectiveEndIf
4116 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4117 if (getLexer().isNot(AsmToken::EndOfStatement))
4118 return TokError("unexpected token in '.endif' directive");
4122 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4123 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4125 if (!TheCondStack.empty()) {
4126 TheCondState = TheCondStack.back();
4127 TheCondStack.pop_back();
4133 void AsmParser::initializeDirectiveKindMap() {
4134 DirectiveKindMap[".set"] = DK_SET;
4135 DirectiveKindMap[".equ"] = DK_EQU;
4136 DirectiveKindMap[".equiv"] = DK_EQUIV;
4137 DirectiveKindMap[".ascii"] = DK_ASCII;
4138 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4139 DirectiveKindMap[".string"] = DK_STRING;
4140 DirectiveKindMap[".byte"] = DK_BYTE;
4141 DirectiveKindMap[".short"] = DK_SHORT;
4142 DirectiveKindMap[".value"] = DK_VALUE;
4143 DirectiveKindMap[".2byte"] = DK_2BYTE;
4144 DirectiveKindMap[".long"] = DK_LONG;
4145 DirectiveKindMap[".int"] = DK_INT;
4146 DirectiveKindMap[".4byte"] = DK_4BYTE;
4147 DirectiveKindMap[".quad"] = DK_QUAD;
4148 DirectiveKindMap[".8byte"] = DK_8BYTE;
4149 DirectiveKindMap[".octa"] = DK_OCTA;
4150 DirectiveKindMap[".single"] = DK_SINGLE;
4151 DirectiveKindMap[".float"] = DK_FLOAT;
4152 DirectiveKindMap[".double"] = DK_DOUBLE;
4153 DirectiveKindMap[".align"] = DK_ALIGN;
4154 DirectiveKindMap[".align32"] = DK_ALIGN32;
4155 DirectiveKindMap[".balign"] = DK_BALIGN;
4156 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4157 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4158 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4159 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4160 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4161 DirectiveKindMap[".org"] = DK_ORG;
4162 DirectiveKindMap[".fill"] = DK_FILL;
4163 DirectiveKindMap[".zero"] = DK_ZERO;
4164 DirectiveKindMap[".extern"] = DK_EXTERN;
4165 DirectiveKindMap[".globl"] = DK_GLOBL;
4166 DirectiveKindMap[".global"] = DK_GLOBAL;
4167 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4168 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4169 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4170 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4171 DirectiveKindMap[".reference"] = DK_REFERENCE;
4172 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4173 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4174 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4175 DirectiveKindMap[".comm"] = DK_COMM;
4176 DirectiveKindMap[".common"] = DK_COMMON;
4177 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4178 DirectiveKindMap[".abort"] = DK_ABORT;
4179 DirectiveKindMap[".include"] = DK_INCLUDE;
4180 DirectiveKindMap[".incbin"] = DK_INCBIN;
4181 DirectiveKindMap[".code16"] = DK_CODE16;
4182 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4183 DirectiveKindMap[".rept"] = DK_REPT;
4184 DirectiveKindMap[".rep"] = DK_REPT;
4185 DirectiveKindMap[".irp"] = DK_IRP;
4186 DirectiveKindMap[".irpc"] = DK_IRPC;
4187 DirectiveKindMap[".endr"] = DK_ENDR;
4188 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4189 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4190 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4191 DirectiveKindMap[".if"] = DK_IF;
4192 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4193 DirectiveKindMap[".ifge"] = DK_IFGE;
4194 DirectiveKindMap[".ifgt"] = DK_IFGT;
4195 DirectiveKindMap[".ifle"] = DK_IFLE;
4196 DirectiveKindMap[".iflt"] = DK_IFLT;
4197 DirectiveKindMap[".ifne"] = DK_IFNE;
4198 DirectiveKindMap[".ifb"] = DK_IFB;
4199 DirectiveKindMap[".ifnb"] = DK_IFNB;
4200 DirectiveKindMap[".ifc"] = DK_IFC;
4201 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4202 DirectiveKindMap[".ifnc"] = DK_IFNC;
4203 DirectiveKindMap[".ifnes"] = DK_IFNES;
4204 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4205 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4206 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4207 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4208 DirectiveKindMap[".else"] = DK_ELSE;
4209 DirectiveKindMap[".end"] = DK_END;
4210 DirectiveKindMap[".endif"] = DK_ENDIF;
4211 DirectiveKindMap[".skip"] = DK_SKIP;
4212 DirectiveKindMap[".space"] = DK_SPACE;
4213 DirectiveKindMap[".file"] = DK_FILE;
4214 DirectiveKindMap[".line"] = DK_LINE;
4215 DirectiveKindMap[".loc"] = DK_LOC;
4216 DirectiveKindMap[".stabs"] = DK_STABS;
4217 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4218 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4219 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4220 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4221 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4222 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4223 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4224 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4225 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4226 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4227 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4228 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4229 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4230 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4231 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4232 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4233 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4234 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4235 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4236 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4237 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4238 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4239 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4240 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4241 DirectiveKindMap[".macro"] = DK_MACRO;
4242 DirectiveKindMap[".exitm"] = DK_EXITM;
4243 DirectiveKindMap[".endm"] = DK_ENDM;
4244 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4245 DirectiveKindMap[".purgem"] = DK_PURGEM;
4246 DirectiveKindMap[".err"] = DK_ERR;
4247 DirectiveKindMap[".error"] = DK_ERROR;
4248 DirectiveKindMap[".warning"] = DK_WARNING;
4251 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4252 AsmToken EndToken, StartToken = getTok();
4254 unsigned NestLevel = 0;
4256 // Check whether we have reached the end of the file.
4257 if (getLexer().is(AsmToken::Eof)) {
4258 Error(DirectiveLoc, "no matching '.endr' in definition");
4262 if (Lexer.is(AsmToken::Identifier) &&
4263 (getTok().getIdentifier() == ".rept")) {
4267 // Otherwise, check whether we have reached the .endr.
4268 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4269 if (NestLevel == 0) {
4270 EndToken = getTok();
4272 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4273 TokError("unexpected token in '.endr' directive");
4281 // Otherwise, scan till the end of the statement.
4282 eatToEndOfStatement();
4285 const char *BodyStart = StartToken.getLoc().getPointer();
4286 const char *BodyEnd = EndToken.getLoc().getPointer();
4287 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4289 // We Are Anonymous.
4290 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4291 return &MacroLikeBodies.back();
4294 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4295 raw_svector_ostream &OS) {
4298 std::unique_ptr<MemoryBuffer> Instantiation =
4299 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4301 // Create the macro instantiation object and add to the current macro
4302 // instantiation stack.
4303 MacroInstantiation *MI = new MacroInstantiation(
4304 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4305 ActiveMacros.push_back(MI);
4307 // Jump to the macro instantiation and prime the lexer.
4308 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4309 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4313 /// parseDirectiveRept
4314 /// ::= .rep | .rept count
4315 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4316 const MCExpr *CountExpr;
4317 SMLoc CountLoc = getTok().getLoc();
4318 if (parseExpression(CountExpr))
4322 if (!CountExpr->evaluateAsAbsolute(Count)) {
4323 eatToEndOfStatement();
4324 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4328 return Error(CountLoc, "Count is negative");
4330 if (Lexer.isNot(AsmToken::EndOfStatement))
4331 return TokError("unexpected token in '" + Dir + "' directive");
4333 // Eat the end of statement.
4336 // Lex the rept definition.
4337 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4341 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4342 // to hold the macro body with substitutions.
4343 SmallString<256> Buf;
4344 raw_svector_ostream OS(Buf);
4346 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4347 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4350 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4355 /// parseDirectiveIrp
4356 /// ::= .irp symbol,values
4357 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4358 MCAsmMacroParameter Parameter;
4360 if (parseIdentifier(Parameter.Name))
4361 return TokError("expected identifier in '.irp' directive");
4363 if (Lexer.isNot(AsmToken::Comma))
4364 return TokError("expected comma in '.irp' directive");
4368 MCAsmMacroArguments A;
4369 if (parseMacroArguments(nullptr, A))
4372 // Eat the end of statement.
4375 // Lex the irp definition.
4376 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4380 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4381 // to hold the macro body with substitutions.
4382 SmallString<256> Buf;
4383 raw_svector_ostream OS(Buf);
4385 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4386 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4387 // This is undocumented, but GAS seems to support it.
4388 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4392 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4397 /// parseDirectiveIrpc
4398 /// ::= .irpc symbol,values
4399 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4400 MCAsmMacroParameter Parameter;
4402 if (parseIdentifier(Parameter.Name))
4403 return TokError("expected identifier in '.irpc' directive");
4405 if (Lexer.isNot(AsmToken::Comma))
4406 return TokError("expected comma in '.irpc' directive");
4410 MCAsmMacroArguments A;
4411 if (parseMacroArguments(nullptr, A))
4414 if (A.size() != 1 || A.front().size() != 1)
4415 return TokError("unexpected token in '.irpc' directive");
4417 // Eat the end of statement.
4420 // Lex the irpc definition.
4421 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4425 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4426 // to hold the macro body with substitutions.
4427 SmallString<256> Buf;
4428 raw_svector_ostream OS(Buf);
4430 StringRef Values = A.front().front().getString();
4431 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4432 MCAsmMacroArgument Arg;
4433 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4435 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4436 // This is undocumented, but GAS seems to support it.
4437 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4441 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4446 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4447 if (ActiveMacros.empty())
4448 return TokError("unmatched '.endr' directive");
4450 // The only .repl that should get here are the ones created by
4451 // instantiateMacroLikeBody.
4452 assert(getLexer().is(AsmToken::EndOfStatement));
4458 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4460 const MCExpr *Value;
4461 SMLoc ExprLoc = getLexer().getLoc();
4462 if (parseExpression(Value))
4464 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4466 return Error(ExprLoc, "unexpected expression in _emit");
4467 uint64_t IntValue = MCE->getValue();
4468 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4469 return Error(ExprLoc, "literal value out of range for directive");
4471 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4475 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4476 const MCExpr *Value;
4477 SMLoc ExprLoc = getLexer().getLoc();
4478 if (parseExpression(Value))
4480 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4482 return Error(ExprLoc, "unexpected expression in align");
4483 uint64_t IntValue = MCE->getValue();
4484 if (!isPowerOf2_64(IntValue))
4485 return Error(ExprLoc, "literal value not a power of two greater then zero");
4487 Info.AsmRewrites->push_back(
4488 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4492 // We are comparing pointers, but the pointers are relative to a single string.
4493 // Thus, this should always be deterministic.
4494 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4495 const AsmRewrite *AsmRewriteB) {
4496 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4498 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4501 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4502 // rewrite to the same location. Make sure the SizeDirective rewrite is
4503 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4504 // ensures the sort algorithm is stable.
4505 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4506 AsmRewritePrecedence[AsmRewriteB->Kind])
4509 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4510 AsmRewritePrecedence[AsmRewriteB->Kind])
4512 llvm_unreachable("Unstable rewrite sort.");
4515 bool AsmParser::parseMSInlineAsm(
4516 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4517 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4518 SmallVectorImpl<std::string> &Constraints,
4519 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4520 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4521 SmallVector<void *, 4> InputDecls;
4522 SmallVector<void *, 4> OutputDecls;
4523 SmallVector<bool, 4> InputDeclsAddressOf;
4524 SmallVector<bool, 4> OutputDeclsAddressOf;
4525 SmallVector<std::string, 4> InputConstraints;
4526 SmallVector<std::string, 4> OutputConstraints;
4527 SmallVector<unsigned, 4> ClobberRegs;
4529 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4534 // While we have input, parse each statement.
4535 unsigned InputIdx = 0;
4536 unsigned OutputIdx = 0;
4537 while (getLexer().isNot(AsmToken::Eof)) {
4538 ParseStatementInfo Info(&AsmStrRewrites);
4539 if (parseStatement(Info, &SI))
4542 if (Info.ParseError)
4545 if (Info.Opcode == ~0U)
4548 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4550 // Build the list of clobbers, outputs and inputs.
4551 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4552 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4555 if (Operand.isImm())
4558 // Register operand.
4559 if (Operand.isReg() && !Operand.needAddressOf() &&
4560 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4561 unsigned NumDefs = Desc.getNumDefs();
4563 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4564 ClobberRegs.push_back(Operand.getReg());
4568 // Expr/Input or Output.
4569 StringRef SymName = Operand.getSymName();
4570 if (SymName.empty())
4573 void *OpDecl = Operand.getOpDecl();
4577 bool isOutput = (i == 1) && Desc.mayStore();
4578 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4581 OutputDecls.push_back(OpDecl);
4582 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4583 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4584 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4586 InputDecls.push_back(OpDecl);
4587 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4588 InputConstraints.push_back(Operand.getConstraint().str());
4589 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4593 // Consider implicit defs to be clobbers. Think of cpuid and push.
4594 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4595 Desc.getNumImplicitDefs());
4596 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4599 // Set the number of Outputs and Inputs.
4600 NumOutputs = OutputDecls.size();
4601 NumInputs = InputDecls.size();
4603 // Set the unique clobbers.
4604 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4605 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4607 Clobbers.assign(ClobberRegs.size(), std::string());
4608 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4609 raw_string_ostream OS(Clobbers[I]);
4610 IP->printRegName(OS, ClobberRegs[I]);
4613 // Merge the various outputs and inputs. Output are expected first.
4614 if (NumOutputs || NumInputs) {
4615 unsigned NumExprs = NumOutputs + NumInputs;
4616 OpDecls.resize(NumExprs);
4617 Constraints.resize(NumExprs);
4618 for (unsigned i = 0; i < NumOutputs; ++i) {
4619 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4620 Constraints[i] = OutputConstraints[i];
4622 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4623 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4624 Constraints[j] = InputConstraints[i];
4628 // Build the IR assembly string.
4629 std::string AsmStringIR;
4630 raw_string_ostream OS(AsmStringIR);
4631 StringRef ASMString =
4632 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4633 const char *AsmStart = ASMString.begin();
4634 const char *AsmEnd = ASMString.end();
4635 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4636 for (const AsmRewrite &AR : AsmStrRewrites) {
4637 AsmRewriteKind Kind = AR.Kind;
4638 if (Kind == AOK_Delete)
4641 const char *Loc = AR.Loc.getPointer();
4642 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4644 // Emit everything up to the immediate/expression.
4645 if (unsigned Len = Loc - AsmStart)
4646 OS << StringRef(AsmStart, Len);
4648 // Skip the original expression.
4649 if (Kind == AOK_Skip) {
4650 AsmStart = Loc + AR.Len;
4654 unsigned AdditionalSkip = 0;
4655 // Rewrite expressions in $N notation.
4660 OS << "$$" << AR.Val;
4666 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4669 OS << '$' << InputIdx++;
4672 OS << '$' << OutputIdx++;
4674 case AOK_SizeDirective:
4677 case 8: OS << "byte ptr "; break;
4678 case 16: OS << "word ptr "; break;
4679 case 32: OS << "dword ptr "; break;
4680 case 64: OS << "qword ptr "; break;
4681 case 80: OS << "xword ptr "; break;
4682 case 128: OS << "xmmword ptr "; break;
4683 case 256: OS << "ymmword ptr "; break;
4690 unsigned Val = AR.Val;
4691 OS << ".align " << Val;
4693 // Skip the original immediate.
4694 assert(Val < 10 && "Expected alignment less then 2^10.");
4695 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4698 case AOK_DotOperator:
4699 // Insert the dot if the user omitted it.
4701 if (AsmStringIR.back() != '.')
4707 // Skip the original expression.
4708 AsmStart = Loc + AR.Len + AdditionalSkip;
4711 // Emit the remainder of the asm string.
4712 if (AsmStart != AsmEnd)
4713 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4715 AsmString = OS.str();
4720 namespace MCParserUtils {
4722 /// Returns whether the given symbol is used anywhere in the given expression,
4723 /// or subexpressions.
4724 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4725 switch (Value->getKind()) {
4726 case MCExpr::Binary: {
4727 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4728 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4729 isSymbolUsedInExpression(Sym, BE->getRHS());
4731 case MCExpr::Target:
4732 case MCExpr::Constant:
4734 case MCExpr::SymbolRef: {
4736 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4738 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4742 return isSymbolUsedInExpression(
4743 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4746 llvm_unreachable("Unknown expr kind!");
4749 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4750 MCAsmParser &Parser, MCSymbol *&Sym,
4751 const MCExpr *&Value) {
4752 MCAsmLexer &Lexer = Parser.getLexer();
4754 // FIXME: Use better location, we should use proper tokens.
4755 SMLoc EqualLoc = Lexer.getLoc();
4757 if (Parser.parseExpression(Value)) {
4758 Parser.TokError("missing expression");
4759 Parser.eatToEndOfStatement();
4763 // Note: we don't count b as used in "a = b". This is to allow
4767 if (Lexer.isNot(AsmToken::EndOfStatement))
4768 return Parser.TokError("unexpected token in assignment");
4770 // Eat the end of statement marker.
4773 // Validate that the LHS is allowed to be a variable (either it has not been
4774 // used as a symbol, or it is an absolute symbol).
4775 Sym = Parser.getContext().lookupSymbol(Name);
4777 // Diagnose assignment to a label.
4779 // FIXME: Diagnostics. Note the location of the definition as a label.
4780 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4781 if (isSymbolUsedInExpression(Sym, Value))
4782 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4783 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4784 ; // Allow redefinitions of undefined symbols only used in directives.
4785 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4786 ; // Allow redefinitions of variables that haven't yet been used.
4787 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4788 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4789 else if (!Sym->isVariable())
4790 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4791 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4792 return Parser.Error(EqualLoc,
4793 "invalid reassignment of non-absolute variable '" +
4796 // Don't count these checks as uses.
4797 Sym->setUsed(false);
4798 } else if (Name == ".") {
4799 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4800 Parser.Error(EqualLoc, "expected absolute expression");
4801 Parser.eatToEndOfStatement();
4806 Sym = Parser.getContext().getOrCreateSymbol(Name);
4808 Sym->setRedefinable(allow_redef);
4813 } // namespace MCParserUtils
4816 /// \brief Create an MCAsmParser instance.
4817 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4818 MCStreamer &Out, const MCAsmInfo &MAI) {
4819 return new AsmParser(SM, C, Out, MAI);