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 parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
238 SMLoc &EndLoc) override;
239 bool parseAbsoluteExpression(int64_t &Res) override;
241 /// \brief Parse an identifier or string (as a quoted identifier)
242 /// and set \p Res to the identifier contents.
243 bool parseIdentifier(StringRef &Res) override;
244 void eatToEndOfStatement() override;
246 void checkForValidSection() override;
251 bool parseStatement(ParseStatementInfo &Info,
252 MCAsmParserSemaCallback *SI);
253 void eatToEndOfLine();
254 bool parseCppHashLineFilenameComment(const SMLoc &L);
256 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
257 ArrayRef<MCAsmMacroParameter> Parameters);
258 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters,
260 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
263 /// \brief Are macros enabled in the parser?
264 bool areMacrosEnabled() {return MacrosEnabledFlag;}
266 /// \brief Control a flag in the parser that enables or disables macros.
267 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
269 /// \brief Lookup a previously defined macro.
270 /// \param Name Macro name.
271 /// \returns Pointer to macro. NULL if no such macro was defined.
272 const MCAsmMacro* lookupMacro(StringRef Name);
274 /// \brief Define a new macro with the given name and information.
275 void defineMacro(StringRef Name, MCAsmMacro Macro);
277 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
278 void undefineMacro(StringRef Name);
280 /// \brief Are we inside a macro instantiation?
281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
283 /// \brief Handle entry to macro instantiation.
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
289 /// \brief Handle exit from macro instantiation.
290 void handleMacroExit();
292 /// \brief Extract AsmTokens for a macro argument.
293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
295 /// \brief Parse all macro arguments for a given macro.
296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
300 ArrayRef<SMRange> Ranges = None) const {
301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
308 /// \brief Process the specified file for the .incbin directive.
309 /// This returns true on failure.
310 bool processIncbinFile(const std::string &Filename);
312 /// \brief Reset the current lexer position to that given by \p Loc. The
313 /// current token is not set; clients should ensure Lex() is called
316 /// \param InBuffer If not 0, should be the known buffer id that contains the
318 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
323 StringRef parseStringToEndOfStatement() override;
325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
327 StringRef parseStringToComma();
329 bool parseAssignment(StringRef Name, bool allow_redef,
330 bool NoDeadStrip = false);
332 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
333 MCBinaryExpr::Opcode &Kind);
335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
341 // Generic (target and platform independent) directive parsing.
343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
354 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
355 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
356 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
364 DK_MACROS_ON, DK_MACROS_OFF,
365 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
366 DK_SLEB128, DK_ULEB128,
367 DK_ERR, DK_ERROR, DK_WARNING,
371 /// \brief Maps directive name --> DirectiveKind enum, for
372 /// directives parsed by this class.
373 StringMap<DirectiveKind> DirectiveKindMap;
375 // ".ascii", ".asciz", ".string"
376 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
377 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
378 bool parseDirectiveOctaValue(); // ".octa"
379 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
380 bool parseDirectiveFill(); // ".fill"
381 bool parseDirectiveZero(); // ".zero"
382 // ".set", ".equ", ".equiv"
383 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
384 bool parseDirectiveOrg(); // ".org"
385 // ".align{,32}", ".p2align{,w,l}"
386 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
388 // ".file", ".line", ".loc", ".stabs"
389 bool parseDirectiveFile(SMLoc DirectiveLoc);
390 bool parseDirectiveLine();
391 bool parseDirectiveLoc();
392 bool parseDirectiveStabs();
395 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIWindowSave();
397 bool parseDirectiveCFISections();
398 bool parseDirectiveCFIStartProc();
399 bool parseDirectiveCFIEndProc();
400 bool parseDirectiveCFIDefCfaOffset();
401 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIAdjustCfaOffset();
403 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
407 bool parseDirectiveCFIRememberState();
408 bool parseDirectiveCFIRestoreState();
409 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
411 bool parseDirectiveCFIEscape();
412 bool parseDirectiveCFISignalFrame();
413 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
416 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveExitMacro(StringRef Directive);
418 bool parseDirectiveEndMacro(StringRef Directive);
419 bool parseDirectiveMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveMacrosOnOff(StringRef Directive);
422 // ".bundle_align_mode"
423 bool parseDirectiveBundleAlignMode();
425 bool parseDirectiveBundleLock();
427 bool parseDirectiveBundleUnlock();
430 bool parseDirectiveSpace(StringRef IDVal);
432 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
433 bool parseDirectiveLEB128(bool Signed);
435 /// \brief Parse a directive like ".globl" which
436 /// accepts a single symbol (which should be a label or an external).
437 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
439 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
441 bool parseDirectiveAbort(); // ".abort"
442 bool parseDirectiveInclude(); // ".include"
443 bool parseDirectiveIncbin(); // ".incbin"
445 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
446 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
447 // ".ifb" or ".ifnb", depending on ExpectBlank.
448 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
449 // ".ifc" or ".ifnc", depending on ExpectEqual.
450 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
451 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
452 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
453 // ".ifdef" or ".ifndef", depending on expect_defined
454 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
455 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
456 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
457 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
458 bool parseEscapedString(std::string &Data) override;
460 const MCExpr *applyModifierToExpr(const MCExpr *E,
461 MCSymbolRefExpr::VariantKind Variant);
463 // Macro-like directives
464 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
465 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
466 raw_svector_ostream &OS);
467 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
468 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
469 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
470 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
472 // "_emit" or "__emit"
473 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
477 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
480 bool parseDirectiveEnd(SMLoc DirectiveLoc);
482 // ".err" or ".error"
483 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
486 bool parseDirectiveWarning(SMLoc DirectiveLoc);
488 void initializeDirectiveKindMap();
494 extern MCAsmParserExtension *createDarwinAsmParser();
495 extern MCAsmParserExtension *createELFAsmParser();
496 extern MCAsmParserExtension *createCOFFAsmParser();
500 enum { DEFAULT_ADDRSPACE = 0 };
502 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
503 const MCAsmInfo &MAI)
504 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
505 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
506 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
507 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
508 // Save the old handler.
509 SavedDiagHandler = SrcMgr.getDiagHandler();
510 SavedDiagContext = SrcMgr.getDiagContext();
511 // Set our own handler which calls the saved handler.
512 SrcMgr.setDiagHandler(DiagHandler, this);
513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
515 // Initialize the platform / file format parser.
516 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
517 case MCObjectFileInfo::IsCOFF:
518 PlatformParser.reset(createCOFFAsmParser());
520 case MCObjectFileInfo::IsMachO:
521 PlatformParser.reset(createDarwinAsmParser());
524 case MCObjectFileInfo::IsELF:
525 PlatformParser.reset(createELFAsmParser());
529 PlatformParser->Initialize(*this);
530 initializeDirectiveKindMap();
532 NumOfMacroInstantiations = 0;
535 AsmParser::~AsmParser() {
536 assert((HadError || ActiveMacros.empty()) &&
537 "Unexpected active macro instantiation!");
540 void AsmParser::printMacroInstantiations() {
541 // Print the active macro instantiation stack.
542 for (std::vector<MacroInstantiation *>::const_reverse_iterator
543 it = ActiveMacros.rbegin(),
544 ie = ActiveMacros.rend();
546 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
547 "while in macro instantiation");
550 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
552 printMacroInstantiations();
555 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 if(getTargetParser().getTargetOptions().MCNoWarn)
558 if (getTargetParser().getTargetOptions().MCFatalWarnings)
559 return Error(L, Msg, Ranges);
560 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
561 printMacroInstantiations();
565 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
567 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
568 printMacroInstantiations();
572 bool AsmParser::enterIncludeFile(const std::string &Filename) {
573 std::string IncludedFile;
575 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
580 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
584 /// Process the specified .incbin file by searching for it in the include paths
585 /// then just emitting the byte contents of the file to the streamer. This
586 /// returns true on failure.
587 bool AsmParser::processIncbinFile(const std::string &Filename) {
588 std::string IncludedFile;
590 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
594 // Pick up the bytes from the file and emit them.
595 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
599 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
600 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
601 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
605 const AsmToken &AsmParser::Lex() {
606 const AsmToken *tok = &Lexer.Lex();
608 if (tok->is(AsmToken::Eof)) {
609 // If this is the end of an included file, pop the parent file off the
611 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
612 if (ParentIncludeLoc != SMLoc()) {
613 jumpToLoc(ParentIncludeLoc);
618 if (tok->is(AsmToken::Error))
619 Error(Lexer.getErrLoc(), Lexer.getErr());
624 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
625 // Create the initial section, if requested.
626 if (!NoInitialTextSection)
627 Out.InitSections(false);
633 AsmCond StartingCondState = TheCondState;
635 // If we are generating dwarf for assembly source files save the initial text
636 // section and generate a .file directive.
637 if (getContext().getGenDwarfForAssembly()) {
638 MCSection *Sec = getStreamer().getCurrentSection().first;
639 if (!Sec->getBeginSymbol()) {
640 MCSymbol *SectionStartSym = getContext().createTempSymbol();
641 getStreamer().EmitLabel(SectionStartSym);
642 Sec->setBeginSymbol(SectionStartSym);
644 bool InsertResult = getContext().addGenDwarfSection(Sec);
645 assert(InsertResult && ".text section should not have debug info yet");
647 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
648 0, StringRef(), getContext().getMainFileName()));
651 // While we have input, parse each statement.
652 while (Lexer.isNot(AsmToken::Eof)) {
653 ParseStatementInfo Info;
654 if (!parseStatement(Info, nullptr))
657 // We had an error, validate that one was emitted and recover by skipping to
659 assert(HadError && "Parse statement returned an error, but none emitted!");
660 eatToEndOfStatement();
663 if (TheCondState.TheCond != StartingCondState.TheCond ||
664 TheCondState.Ignore != StartingCondState.Ignore)
665 return TokError("unmatched .ifs or .elses");
667 // Check to see there are no empty DwarfFile slots.
668 const auto &LineTables = getContext().getMCDwarfLineTables();
669 if (!LineTables.empty()) {
671 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
672 if (File.Name.empty() && Index != 0)
673 TokError("unassigned file number: " + Twine(Index) +
674 " for .file directives");
679 // Check to see that all assembler local symbols were actually defined.
680 // Targets that don't do subsections via symbols may not want this, though,
681 // so conservatively exclude them. Only do this if we're finalizing, though,
682 // as otherwise we won't necessarilly have seen everything yet.
683 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
684 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
685 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
688 MCSymbol *Sym = i->getValue();
689 // Variable symbols may not be marked as defined, so check those
690 // explicitly. If we know it's a variable, we have a definition for
691 // the purposes of this check.
692 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
693 // FIXME: We would really like to refer back to where the symbol was
694 // first referenced for a source location. We need to add something
695 // to track that. Currently, we just point to the end of the file.
697 getLexer().getLoc(), SourceMgr::DK_Error,
698 "assembler local symbol '" + Sym->getName() + "' not defined");
702 // Finalize the output stream if there are no errors and if the client wants
704 if (!HadError && !NoFinalize)
710 void AsmParser::checkForValidSection() {
711 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
712 TokError("expected section directive before assembly directive");
713 Out.InitSections(false);
717 /// \brief Throw away the rest of the line for testing purposes.
718 void AsmParser::eatToEndOfStatement() {
719 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
723 if (Lexer.is(AsmToken::EndOfStatement))
727 StringRef AsmParser::parseStringToEndOfStatement() {
728 const char *Start = getTok().getLoc().getPointer();
730 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
733 const char *End = getTok().getLoc().getPointer();
734 return StringRef(Start, End - Start);
737 StringRef AsmParser::parseStringToComma() {
738 const char *Start = getTok().getLoc().getPointer();
740 while (Lexer.isNot(AsmToken::EndOfStatement) &&
741 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
744 const char *End = getTok().getLoc().getPointer();
745 return StringRef(Start, End - Start);
748 /// \brief Parse a paren expression and return it.
749 /// NOTE: This assumes the leading '(' has already been consumed.
751 /// parenexpr ::= expr)
753 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
754 if (parseExpression(Res))
756 if (Lexer.isNot(AsmToken::RParen))
757 return TokError("expected ')' in parentheses expression");
758 EndLoc = Lexer.getTok().getEndLoc();
763 /// \brief Parse a bracket expression and return it.
764 /// NOTE: This assumes the leading '[' has already been consumed.
766 /// bracketexpr ::= expr]
768 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
769 if (parseExpression(Res))
771 if (Lexer.isNot(AsmToken::RBrac))
772 return TokError("expected ']' in brackets expression");
773 EndLoc = Lexer.getTok().getEndLoc();
778 /// \brief Parse a primary expression and return it.
779 /// primaryexpr ::= (parenexpr
780 /// primaryexpr ::= symbol
781 /// primaryexpr ::= number
782 /// primaryexpr ::= '.'
783 /// primaryexpr ::= ~,+,- primaryexpr
784 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
785 SMLoc FirstTokenLoc = getLexer().getLoc();
786 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
787 switch (FirstTokenKind) {
789 return TokError("unknown token in expression");
790 // If we have an error assume that we've already handled it.
791 case AsmToken::Error:
793 case AsmToken::Exclaim:
794 Lex(); // Eat the operator.
795 if (parsePrimaryExpr(Res, EndLoc))
797 Res = MCUnaryExpr::createLNot(Res, getContext());
799 case AsmToken::Dollar:
801 case AsmToken::String:
802 case AsmToken::Identifier: {
803 StringRef Identifier;
804 if (parseIdentifier(Identifier)) {
805 if (FirstTokenKind == AsmToken::Dollar) {
806 if (Lexer.getMAI().getDollarIsPC()) {
807 // This is a '$' reference, which references the current PC. Emit a
808 // temporary label to the streamer and refer to it.
809 MCSymbol *Sym = Ctx.createTempSymbol();
811 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
813 EndLoc = FirstTokenLoc;
816 return Error(FirstTokenLoc, "invalid token in expression");
819 // Parse symbol variant
820 std::pair<StringRef, StringRef> Split;
821 if (!MAI.useParensForSymbolVariant()) {
822 if (FirstTokenKind == AsmToken::String) {
823 if (Lexer.is(AsmToken::At)) {
824 Lexer.Lex(); // eat @
825 SMLoc AtLoc = getLexer().getLoc();
827 if (parseIdentifier(VName))
828 return Error(AtLoc, "expected symbol variant after '@'");
830 Split = std::make_pair(Identifier, VName);
833 Split = Identifier.split('@');
835 } else if (Lexer.is(AsmToken::LParen)) {
836 Lexer.Lex(); // eat (
838 parseIdentifier(VName);
839 if (Lexer.isNot(AsmToken::RParen)) {
840 return Error(Lexer.getTok().getLoc(),
841 "unexpected token in variant, expected ')'");
843 Lexer.Lex(); // eat )
844 Split = std::make_pair(Identifier, VName);
847 EndLoc = SMLoc::getFromPointer(Identifier.end());
849 // This is a symbol reference.
850 StringRef SymbolName = Identifier;
851 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
853 // Lookup the symbol variant if used.
854 if (Split.second.size()) {
855 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
856 if (Variant != MCSymbolRefExpr::VK_Invalid) {
857 SymbolName = Split.first;
858 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
859 Variant = MCSymbolRefExpr::VK_None;
861 return Error(SMLoc::getFromPointer(Split.second.begin()),
862 "invalid variant '" + Split.second + "'");
866 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
868 // If this is an absolute variable reference, substitute it now to preserve
869 // semantics in the face of reassignment.
870 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
872 return Error(EndLoc, "unexpected modifier on variable reference");
874 Res = Sym->getVariableValue();
878 // Otherwise create a symbol ref.
879 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
882 case AsmToken::BigNum:
883 return TokError("literal value out of range for directive");
884 case AsmToken::Integer: {
885 SMLoc Loc = getTok().getLoc();
886 int64_t IntVal = getTok().getIntVal();
887 Res = MCConstantExpr::create(IntVal, getContext());
888 EndLoc = Lexer.getTok().getEndLoc();
890 // Look for 'b' or 'f' following an Integer as a directional label
891 if (Lexer.getKind() == AsmToken::Identifier) {
892 StringRef IDVal = getTok().getString();
893 // Lookup the symbol variant if used.
894 std::pair<StringRef, StringRef> Split = IDVal.split('@');
895 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
896 if (Split.first.size() != IDVal.size()) {
897 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
898 if (Variant == MCSymbolRefExpr::VK_Invalid)
899 return TokError("invalid variant '" + Split.second + "'");
902 if (IDVal == "f" || IDVal == "b") {
904 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
905 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
906 if (IDVal == "b" && Sym->isUndefined())
907 return Error(Loc, "invalid reference to undefined symbol");
908 EndLoc = Lexer.getTok().getEndLoc();
909 Lex(); // Eat identifier.
914 case AsmToken::Real: {
915 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
916 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
917 Res = MCConstantExpr::create(IntVal, getContext());
918 EndLoc = Lexer.getTok().getEndLoc();
922 case AsmToken::Dot: {
923 // This is a '.' reference, which references the current PC. Emit a
924 // temporary label to the streamer and refer to it.
925 MCSymbol *Sym = Ctx.createTempSymbol();
927 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
928 EndLoc = Lexer.getTok().getEndLoc();
929 Lex(); // Eat identifier.
932 case AsmToken::LParen:
933 Lex(); // Eat the '('.
934 return parseParenExpr(Res, EndLoc);
935 case AsmToken::LBrac:
936 if (!PlatformParser->HasBracketExpressions())
937 return TokError("brackets expression not supported on this target");
938 Lex(); // Eat the '['.
939 return parseBracketExpr(Res, EndLoc);
940 case AsmToken::Minus:
941 Lex(); // Eat the operator.
942 if (parsePrimaryExpr(Res, EndLoc))
944 Res = MCUnaryExpr::createMinus(Res, getContext());
947 Lex(); // Eat the operator.
948 if (parsePrimaryExpr(Res, EndLoc))
950 Res = MCUnaryExpr::createPlus(Res, getContext());
952 case AsmToken::Tilde:
953 Lex(); // Eat the operator.
954 if (parsePrimaryExpr(Res, EndLoc))
956 Res = MCUnaryExpr::createNot(Res, getContext());
961 bool AsmParser::parseExpression(const MCExpr *&Res) {
963 return parseExpression(Res, EndLoc);
967 AsmParser::applyModifierToExpr(const MCExpr *E,
968 MCSymbolRefExpr::VariantKind Variant) {
969 // Ask the target implementation about this expression first.
970 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
973 // Recurse over the given expression, rebuilding it to apply the given variant
974 // if there is exactly one symbol.
975 switch (E->getKind()) {
977 case MCExpr::Constant:
980 case MCExpr::SymbolRef: {
981 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
983 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
984 TokError("invalid variant on expression '" + getTok().getIdentifier() +
985 "' (already modified)");
989 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
992 case MCExpr::Unary: {
993 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
994 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
997 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1000 case MCExpr::Binary: {
1001 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1002 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1003 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1013 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1017 llvm_unreachable("Invalid expression kind!");
1020 /// \brief Parse an expression and return it.
1022 /// expr ::= expr &&,|| expr -> lowest.
1023 /// expr ::= expr |,^,&,! expr
1024 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1025 /// expr ::= expr <<,>> expr
1026 /// expr ::= expr +,- expr
1027 /// expr ::= expr *,/,% expr -> highest.
1028 /// expr ::= primaryexpr
1030 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1031 // Parse the expression.
1033 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1036 // As a special case, we support 'a op b @ modifier' by rewriting the
1037 // expression to include the modifier. This is inefficient, but in general we
1038 // expect users to use 'a@modifier op b'.
1039 if (Lexer.getKind() == AsmToken::At) {
1042 if (Lexer.isNot(AsmToken::Identifier))
1043 return TokError("unexpected symbol modifier following '@'");
1045 MCSymbolRefExpr::VariantKind Variant =
1046 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1047 if (Variant == MCSymbolRefExpr::VK_Invalid)
1048 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1050 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1052 return TokError("invalid modifier '" + getTok().getIdentifier() +
1053 "' (no symbols present)");
1060 // Try to constant fold it up front, if possible.
1062 if (Res->evaluateAsAbsolute(Value))
1063 Res = MCConstantExpr::create(Value, getContext());
1068 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1070 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1073 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1075 if (parseParenExpr(Res, EndLoc))
1078 for (; ParenDepth > 0; --ParenDepth) {
1079 if (parseBinOpRHS(1, Res, EndLoc))
1082 // We don't Lex() the last RParen.
1083 // This is the same behavior as parseParenExpression().
1084 if (ParenDepth - 1 > 0) {
1085 if (Lexer.isNot(AsmToken::RParen))
1086 return TokError("expected ')' in parentheses expression");
1087 EndLoc = Lexer.getTok().getEndLoc();
1094 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1097 SMLoc StartLoc = Lexer.getLoc();
1098 if (parseExpression(Expr))
1101 if (!Expr->evaluateAsAbsolute(Res))
1102 return Error(StartLoc, "expected absolute expression");
1107 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1108 MCBinaryExpr::Opcode &Kind) {
1111 return 0; // not a binop.
1113 // Lowest Precedence: &&, ||
1114 case AsmToken::AmpAmp:
1115 Kind = MCBinaryExpr::LAnd;
1117 case AsmToken::PipePipe:
1118 Kind = MCBinaryExpr::LOr;
1121 // Low Precedence: |, &, ^
1123 // FIXME: gas seems to support '!' as an infix operator?
1124 case AsmToken::Pipe:
1125 Kind = MCBinaryExpr::Or;
1127 case AsmToken::Caret:
1128 Kind = MCBinaryExpr::Xor;
1131 Kind = MCBinaryExpr::And;
1134 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1135 case AsmToken::EqualEqual:
1136 Kind = MCBinaryExpr::EQ;
1138 case AsmToken::ExclaimEqual:
1139 case AsmToken::LessGreater:
1140 Kind = MCBinaryExpr::NE;
1142 case AsmToken::Less:
1143 Kind = MCBinaryExpr::LT;
1145 case AsmToken::LessEqual:
1146 Kind = MCBinaryExpr::LTE;
1148 case AsmToken::Greater:
1149 Kind = MCBinaryExpr::GT;
1151 case AsmToken::GreaterEqual:
1152 Kind = MCBinaryExpr::GTE;
1155 // Intermediate Precedence: <<, >>
1156 case AsmToken::LessLess:
1157 Kind = MCBinaryExpr::Shl;
1159 case AsmToken::GreaterGreater:
1160 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1163 // High Intermediate Precedence: +, -
1164 case AsmToken::Plus:
1165 Kind = MCBinaryExpr::Add;
1167 case AsmToken::Minus:
1168 Kind = MCBinaryExpr::Sub;
1171 // Highest Precedence: *, /, %
1172 case AsmToken::Star:
1173 Kind = MCBinaryExpr::Mul;
1175 case AsmToken::Slash:
1176 Kind = MCBinaryExpr::Div;
1178 case AsmToken::Percent:
1179 Kind = MCBinaryExpr::Mod;
1184 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1185 /// Res contains the LHS of the expression on input.
1186 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1189 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1190 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1192 // If the next token is lower precedence than we are allowed to eat, return
1193 // successfully with what we ate already.
1194 if (TokPrec < Precedence)
1199 // Eat the next primary expression.
1201 if (parsePrimaryExpr(RHS, EndLoc))
1204 // If BinOp binds less tightly with RHS than the operator after RHS, let
1205 // the pending operator take RHS as its LHS.
1206 MCBinaryExpr::Opcode Dummy;
1207 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1208 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1211 // Merge LHS and RHS according to operator.
1212 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1217 /// ::= EndOfStatement
1218 /// ::= Label* Directive ...Operands... EndOfStatement
1219 /// ::= Label* Identifier OperandList* EndOfStatement
1220 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1221 MCAsmParserSemaCallback *SI) {
1222 if (Lexer.is(AsmToken::EndOfStatement)) {
1228 // Statements always start with an identifier or are a full line comment.
1229 AsmToken ID = getTok();
1230 SMLoc IDLoc = ID.getLoc();
1232 int64_t LocalLabelVal = -1;
1233 // A full line comment is a '#' as the first token.
1234 if (Lexer.is(AsmToken::Hash))
1235 return parseCppHashLineFilenameComment(IDLoc);
1237 // Allow an integer followed by a ':' as a directional local label.
1238 if (Lexer.is(AsmToken::Integer)) {
1239 LocalLabelVal = getTok().getIntVal();
1240 if (LocalLabelVal < 0) {
1241 if (!TheCondState.Ignore)
1242 return TokError("unexpected token at start of statement");
1245 IDVal = getTok().getString();
1246 Lex(); // Consume the integer token to be used as an identifier token.
1247 if (Lexer.getKind() != AsmToken::Colon) {
1248 if (!TheCondState.Ignore)
1249 return TokError("unexpected token at start of statement");
1252 } else if (Lexer.is(AsmToken::Dot)) {
1253 // Treat '.' as a valid identifier in this context.
1256 } else if (parseIdentifier(IDVal)) {
1257 if (!TheCondState.Ignore)
1258 return TokError("unexpected token at start of statement");
1262 // Handle conditional assembly here before checking for skipping. We
1263 // have to do this so that .endif isn't skipped in a ".if 0" block for
1265 StringMap<DirectiveKind>::const_iterator DirKindIt =
1266 DirectiveKindMap.find(IDVal);
1267 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1269 : DirKindIt->getValue();
1280 return parseDirectiveIf(IDLoc, DirKind);
1282 return parseDirectiveIfb(IDLoc, true);
1284 return parseDirectiveIfb(IDLoc, false);
1286 return parseDirectiveIfc(IDLoc, true);
1288 return parseDirectiveIfeqs(IDLoc, true);
1290 return parseDirectiveIfc(IDLoc, false);
1292 return parseDirectiveIfeqs(IDLoc, false);
1294 return parseDirectiveIfdef(IDLoc, true);
1297 return parseDirectiveIfdef(IDLoc, false);
1299 return parseDirectiveElseIf(IDLoc);
1301 return parseDirectiveElse(IDLoc);
1303 return parseDirectiveEndIf(IDLoc);
1306 // Ignore the statement if in the middle of inactive conditional
1308 if (TheCondState.Ignore) {
1309 eatToEndOfStatement();
1313 // FIXME: Recurse on local labels?
1315 // See what kind of statement we have.
1316 switch (Lexer.getKind()) {
1317 case AsmToken::Colon: {
1318 checkForValidSection();
1320 // identifier ':' -> Label.
1323 // Diagnose attempt to use '.' as a label.
1325 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1327 // Diagnose attempt to use a variable as a label.
1329 // FIXME: Diagnostics. Note the location of the definition as a label.
1330 // FIXME: This doesn't diagnose assignment to a symbol which has been
1331 // implicitly marked as external.
1333 if (LocalLabelVal == -1) {
1334 if (ParsingInlineAsm && SI) {
1335 StringRef RewrittenLabel =
1336 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1337 assert(RewrittenLabel.size() &&
1338 "We should have an internal name here.");
1339 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1340 IDVal.size(), RewrittenLabel));
1341 IDVal = RewrittenLabel;
1343 Sym = getContext().getOrCreateSymbol(IDVal);
1345 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1347 Sym->redefineIfPossible();
1349 if (!Sym->isUndefined() || Sym->isVariable())
1350 return Error(IDLoc, "invalid symbol redefinition");
1353 if (!ParsingInlineAsm)
1356 // If we are generating dwarf for assembly source files then gather the
1357 // info to make a dwarf label entry for this label if needed.
1358 if (getContext().getGenDwarfForAssembly())
1359 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1362 getTargetParser().onLabelParsed(Sym);
1364 // Consume any end of statement token, if present, to avoid spurious
1365 // AddBlankLine calls().
1366 if (Lexer.is(AsmToken::EndOfStatement)) {
1368 if (Lexer.is(AsmToken::Eof))
1375 case AsmToken::Equal:
1376 // identifier '=' ... -> assignment statement
1379 return parseAssignment(IDVal, true);
1381 default: // Normal instruction or directive.
1385 // If macros are enabled, check to see if this is a macro instantiation.
1386 if (areMacrosEnabled())
1387 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1388 return handleMacroEntry(M, IDLoc);
1391 // Otherwise, we have a normal instruction or directive.
1393 // Directives start with "."
1394 if (IDVal[0] == '.' && IDVal != ".") {
1395 // There are several entities interested in parsing directives:
1397 // 1. The target-specific assembly parser. Some directives are target
1398 // specific or may potentially behave differently on certain targets.
1399 // 2. Asm parser extensions. For example, platform-specific parsers
1400 // (like the ELF parser) register themselves as extensions.
1401 // 3. The generic directive parser implemented by this class. These are
1402 // all the directives that behave in a target and platform independent
1403 // manner, or at least have a default behavior that's shared between
1404 // all targets and platforms.
1406 // First query the target-specific parser. It will return 'true' if it
1407 // isn't interested in this directive.
1408 if (!getTargetParser().ParseDirective(ID))
1411 // Next, check the extension directive map to see if any extension has
1412 // registered itself to parse this directive.
1413 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1414 ExtensionDirectiveMap.lookup(IDVal);
1416 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1418 // Finally, if no one else is interested in this directive, it must be
1419 // generic and familiar to this class.
1425 return parseDirectiveSet(IDVal, true);
1427 return parseDirectiveSet(IDVal, false);
1429 return parseDirectiveAscii(IDVal, false);
1432 return parseDirectiveAscii(IDVal, true);
1434 return parseDirectiveValue(1);
1438 return parseDirectiveValue(2);
1442 return parseDirectiveValue(4);
1445 return parseDirectiveValue(8);
1447 return parseDirectiveOctaValue();
1450 return parseDirectiveRealValue(APFloat::IEEEsingle);
1452 return parseDirectiveRealValue(APFloat::IEEEdouble);
1454 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1455 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1458 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1459 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1462 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1464 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1466 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1468 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1470 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1472 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1474 return parseDirectiveOrg();
1476 return parseDirectiveFill();
1478 return parseDirectiveZero();
1480 eatToEndOfStatement(); // .extern is the default, ignore it.
1484 return parseDirectiveSymbolAttribute(MCSA_Global);
1485 case DK_LAZY_REFERENCE:
1486 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1487 case DK_NO_DEAD_STRIP:
1488 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1489 case DK_SYMBOL_RESOLVER:
1490 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1491 case DK_PRIVATE_EXTERN:
1492 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1494 return parseDirectiveSymbolAttribute(MCSA_Reference);
1495 case DK_WEAK_DEFINITION:
1496 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1497 case DK_WEAK_REFERENCE:
1498 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1499 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1500 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1503 return parseDirectiveComm(/*IsLocal=*/false);
1505 return parseDirectiveComm(/*IsLocal=*/true);
1507 return parseDirectiveAbort();
1509 return parseDirectiveInclude();
1511 return parseDirectiveIncbin();
1514 return TokError(Twine(IDVal) + " not supported yet");
1516 return parseDirectiveRept(IDLoc, IDVal);
1518 return parseDirectiveIrp(IDLoc);
1520 return parseDirectiveIrpc(IDLoc);
1522 return parseDirectiveEndr(IDLoc);
1523 case DK_BUNDLE_ALIGN_MODE:
1524 return parseDirectiveBundleAlignMode();
1525 case DK_BUNDLE_LOCK:
1526 return parseDirectiveBundleLock();
1527 case DK_BUNDLE_UNLOCK:
1528 return parseDirectiveBundleUnlock();
1530 return parseDirectiveLEB128(true);
1532 return parseDirectiveLEB128(false);
1535 return parseDirectiveSpace(IDVal);
1537 return parseDirectiveFile(IDLoc);
1539 return parseDirectiveLine();
1541 return parseDirectiveLoc();
1543 return parseDirectiveStabs();
1544 case DK_CFI_SECTIONS:
1545 return parseDirectiveCFISections();
1546 case DK_CFI_STARTPROC:
1547 return parseDirectiveCFIStartProc();
1548 case DK_CFI_ENDPROC:
1549 return parseDirectiveCFIEndProc();
1550 case DK_CFI_DEF_CFA:
1551 return parseDirectiveCFIDefCfa(IDLoc);
1552 case DK_CFI_DEF_CFA_OFFSET:
1553 return parseDirectiveCFIDefCfaOffset();
1554 case DK_CFI_ADJUST_CFA_OFFSET:
1555 return parseDirectiveCFIAdjustCfaOffset();
1556 case DK_CFI_DEF_CFA_REGISTER:
1557 return parseDirectiveCFIDefCfaRegister(IDLoc);
1559 return parseDirectiveCFIOffset(IDLoc);
1560 case DK_CFI_REL_OFFSET:
1561 return parseDirectiveCFIRelOffset(IDLoc);
1562 case DK_CFI_PERSONALITY:
1563 return parseDirectiveCFIPersonalityOrLsda(true);
1565 return parseDirectiveCFIPersonalityOrLsda(false);
1566 case DK_CFI_REMEMBER_STATE:
1567 return parseDirectiveCFIRememberState();
1568 case DK_CFI_RESTORE_STATE:
1569 return parseDirectiveCFIRestoreState();
1570 case DK_CFI_SAME_VALUE:
1571 return parseDirectiveCFISameValue(IDLoc);
1572 case DK_CFI_RESTORE:
1573 return parseDirectiveCFIRestore(IDLoc);
1575 return parseDirectiveCFIEscape();
1576 case DK_CFI_SIGNAL_FRAME:
1577 return parseDirectiveCFISignalFrame();
1578 case DK_CFI_UNDEFINED:
1579 return parseDirectiveCFIUndefined(IDLoc);
1580 case DK_CFI_REGISTER:
1581 return parseDirectiveCFIRegister(IDLoc);
1582 case DK_CFI_WINDOW_SAVE:
1583 return parseDirectiveCFIWindowSave();
1586 return parseDirectiveMacrosOnOff(IDVal);
1588 return parseDirectiveMacro(IDLoc);
1590 return parseDirectiveExitMacro(IDVal);
1593 return parseDirectiveEndMacro(IDVal);
1595 return parseDirectivePurgeMacro(IDLoc);
1597 return parseDirectiveEnd(IDLoc);
1599 return parseDirectiveError(IDLoc, false);
1601 return parseDirectiveError(IDLoc, true);
1603 return parseDirectiveWarning(IDLoc);
1606 return Error(IDLoc, "unknown directive");
1609 // __asm _emit or __asm __emit
1610 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1611 IDVal == "_EMIT" || IDVal == "__EMIT"))
1612 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1615 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1616 return parseDirectiveMSAlign(IDLoc, Info);
1618 checkForValidSection();
1620 // Canonicalize the opcode to lower case.
1621 std::string OpcodeStr = IDVal.lower();
1622 ParseInstructionInfo IInfo(Info.AsmRewrites);
1623 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1624 Info.ParsedOperands);
1625 Info.ParseError = HadError;
1627 // Dump the parsed representation, if requested.
1628 if (getShowParsedOperands()) {
1629 SmallString<256> Str;
1630 raw_svector_ostream OS(Str);
1631 OS << "parsed instruction: [";
1632 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1635 Info.ParsedOperands[i]->print(OS);
1639 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1642 // If we are generating dwarf for the current section then generate a .loc
1643 // directive for the instruction.
1644 if (!HadError && getContext().getGenDwarfForAssembly() &&
1645 getContext().getGenDwarfSectionSyms().count(
1646 getStreamer().getCurrentSection().first)) {
1648 if (ActiveMacros.empty())
1649 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1651 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1652 ActiveMacros.front()->ExitBuffer);
1654 // If we previously parsed a cpp hash file line comment then make sure the
1655 // current Dwarf File is for the CppHashFilename if not then emit the
1656 // Dwarf File table for it and adjust the line number for the .loc.
1657 if (CppHashFilename.size()) {
1658 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1659 0, StringRef(), CppHashFilename);
1660 getContext().setGenDwarfFileNumber(FileNumber);
1662 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1663 // cache with the different Loc from the call above we save the last
1664 // info we queried here with SrcMgr.FindLineNumber().
1665 unsigned CppHashLocLineNo;
1666 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1667 CppHashLocLineNo = LastQueryLine;
1669 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1670 LastQueryLine = CppHashLocLineNo;
1671 LastQueryIDLoc = CppHashLoc;
1672 LastQueryBuffer = CppHashBuf;
1674 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1677 getStreamer().EmitDwarfLocDirective(
1678 getContext().getGenDwarfFileNumber(), Line, 0,
1679 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1683 // If parsing succeeded, match the instruction.
1686 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1687 Info.ParsedOperands, Out,
1688 ErrorInfo, ParsingInlineAsm);
1691 // Don't skip the rest of the line, the instruction parser is responsible for
1696 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1697 /// since they may not be able to be tokenized to get to the end of line token.
1698 void AsmParser::eatToEndOfLine() {
1699 if (!Lexer.is(AsmToken::EndOfStatement))
1700 Lexer.LexUntilEndOfLine();
1705 /// parseCppHashLineFilenameComment as this:
1706 /// ::= # number "filename"
1707 /// or just as a full line comment if it doesn't have a number and a string.
1708 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1709 Lex(); // Eat the hash token.
1711 if (getLexer().isNot(AsmToken::Integer)) {
1712 // Consume the line since in cases it is not a well-formed line directive,
1713 // as if were simply a full line comment.
1718 int64_t LineNumber = getTok().getIntVal();
1721 if (getLexer().isNot(AsmToken::String)) {
1726 StringRef Filename = getTok().getString();
1727 // Get rid of the enclosing quotes.
1728 Filename = Filename.substr(1, Filename.size() - 2);
1730 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1732 CppHashFilename = Filename;
1733 CppHashLineNumber = LineNumber;
1734 CppHashBuf = CurBuffer;
1736 // Ignore any trailing characters, they're just comment.
1741 /// \brief will use the last parsed cpp hash line filename comment
1742 /// for the Filename and LineNo if any in the diagnostic.
1743 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1744 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1745 raw_ostream &OS = errs();
1747 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1748 const SMLoc &DiagLoc = Diag.getLoc();
1749 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1750 unsigned CppHashBuf =
1751 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1753 // Like SourceMgr::printMessage() we need to print the include stack if any
1754 // before printing the message.
1755 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1756 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1757 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1758 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1759 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1762 // If we have not parsed a cpp hash line filename comment or the source
1763 // manager changed or buffer changed (like in a nested include) then just
1764 // print the normal diagnostic using its Filename and LineNo.
1765 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1766 DiagBuf != CppHashBuf) {
1767 if (Parser->SavedDiagHandler)
1768 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1770 Diag.print(nullptr, OS);
1774 // Use the CppHashFilename and calculate a line number based on the
1775 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1777 const std::string &Filename = Parser->CppHashFilename;
1779 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1780 int CppHashLocLineNo =
1781 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1783 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1785 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1786 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1787 Diag.getLineContents(), Diag.getRanges());
1789 if (Parser->SavedDiagHandler)
1790 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1792 NewDiag.print(nullptr, OS);
1795 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1796 // difference being that that function accepts '@' as part of identifiers and
1797 // we can't do that. AsmLexer.cpp should probably be changed to handle
1798 // '@' as a special case when needed.
1799 static bool isIdentifierChar(char c) {
1800 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1804 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1805 ArrayRef<MCAsmMacroParameter> Parameters,
1806 ArrayRef<MCAsmMacroArgument> A,
1807 bool EnableAtPseudoVariable, const SMLoc &L) {
1808 unsigned NParameters = Parameters.size();
1809 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1810 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1811 return Error(L, "Wrong number of arguments");
1813 // A macro without parameters is handled differently on Darwin:
1814 // gas accepts no arguments and does no substitutions
1815 while (!Body.empty()) {
1816 // Scan for the next substitution.
1817 std::size_t End = Body.size(), Pos = 0;
1818 for (; Pos != End; ++Pos) {
1819 // Check for a substitution or escape.
1820 if (IsDarwin && !NParameters) {
1821 // This macro has no parameters, look for $0, $1, etc.
1822 if (Body[Pos] != '$' || Pos + 1 == End)
1825 char Next = Body[Pos + 1];
1826 if (Next == '$' || Next == 'n' ||
1827 isdigit(static_cast<unsigned char>(Next)))
1830 // This macro has parameters, look for \foo, \bar, etc.
1831 if (Body[Pos] == '\\' && Pos + 1 != End)
1837 OS << Body.slice(0, Pos);
1839 // Check if we reached the end.
1843 if (IsDarwin && !NParameters) {
1844 switch (Body[Pos + 1]) {
1850 // $n => number of arguments
1855 // $[0-9] => argument
1857 // Missing arguments are ignored.
1858 unsigned Index = Body[Pos + 1] - '0';
1859 if (Index >= A.size())
1862 // Otherwise substitute with the token values, with spaces eliminated.
1863 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1864 ie = A[Index].end();
1866 OS << it->getString();
1872 unsigned I = Pos + 1;
1874 // Check for the \@ pseudo-variable.
1875 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1878 while (isIdentifierChar(Body[I]) && I + 1 != End)
1881 const char *Begin = Body.data() + Pos + 1;
1882 StringRef Argument(Begin, I - (Pos + 1));
1885 if (Argument == "@") {
1886 OS << NumOfMacroInstantiations;
1889 for (; Index < NParameters; ++Index)
1890 if (Parameters[Index].Name == Argument)
1893 if (Index == NParameters) {
1894 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1897 OS << '\\' << Argument;
1901 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1902 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1903 ie = A[Index].end();
1905 // We expect no quotes around the string's contents when
1906 // parsing for varargs.
1907 if (it->getKind() != AsmToken::String || VarargParameter)
1908 OS << it->getString();
1910 OS << it->getStringContents();
1912 Pos += 1 + Argument.size();
1916 // Update the scan point.
1917 Body = Body.substr(Pos);
1923 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1924 size_t CondStackDepth)
1925 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1926 CondStackDepth(CondStackDepth) {}
1928 static bool isOperator(AsmToken::TokenKind kind) {
1932 case AsmToken::Plus:
1933 case AsmToken::Minus:
1934 case AsmToken::Tilde:
1935 case AsmToken::Slash:
1936 case AsmToken::Star:
1938 case AsmToken::Equal:
1939 case AsmToken::EqualEqual:
1940 case AsmToken::Pipe:
1941 case AsmToken::PipePipe:
1942 case AsmToken::Caret:
1944 case AsmToken::AmpAmp:
1945 case AsmToken::Exclaim:
1946 case AsmToken::ExclaimEqual:
1947 case AsmToken::Percent:
1948 case AsmToken::Less:
1949 case AsmToken::LessEqual:
1950 case AsmToken::LessLess:
1951 case AsmToken::LessGreater:
1952 case AsmToken::Greater:
1953 case AsmToken::GreaterEqual:
1954 case AsmToken::GreaterGreater:
1960 class AsmLexerSkipSpaceRAII {
1962 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1963 Lexer.setSkipSpace(SkipSpace);
1966 ~AsmLexerSkipSpaceRAII() {
1967 Lexer.setSkipSpace(true);
1975 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1978 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1979 StringRef Str = parseStringToEndOfStatement();
1980 MA.emplace_back(AsmToken::String, Str);
1985 unsigned ParenLevel = 0;
1986 unsigned AddTokens = 0;
1988 // Darwin doesn't use spaces to delmit arguments.
1989 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1992 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1993 return TokError("unexpected token in macro instantiation");
1995 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1998 if (Lexer.is(AsmToken::Space)) {
1999 Lex(); // Eat spaces
2001 // Spaces can delimit parameters, but could also be part an expression.
2002 // If the token after a space is an operator, add the token and the next
2003 // one into this argument
2005 if (isOperator(Lexer.getKind())) {
2006 // Check to see whether the token is used as an operator,
2007 // or part of an identifier
2008 const char *NextChar = getTok().getEndLoc().getPointer();
2009 if (*NextChar == ' ')
2013 if (!AddTokens && ParenLevel == 0) {
2019 // handleMacroEntry relies on not advancing the lexer here
2020 // to be able to fill in the remaining default parameter values
2021 if (Lexer.is(AsmToken::EndOfStatement))
2024 // Adjust the current parentheses level.
2025 if (Lexer.is(AsmToken::LParen))
2027 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2030 // Append the token to the current argument list.
2031 MA.push_back(getTok());
2037 if (ParenLevel != 0)
2038 return TokError("unbalanced parentheses in macro argument");
2042 // Parse the macro instantiation arguments.
2043 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2044 MCAsmMacroArguments &A) {
2045 const unsigned NParameters = M ? M->Parameters.size() : 0;
2046 bool NamedParametersFound = false;
2047 SmallVector<SMLoc, 4> FALocs;
2049 A.resize(NParameters);
2050 FALocs.resize(NParameters);
2052 // Parse two kinds of macro invocations:
2053 // - macros defined without any parameters accept an arbitrary number of them
2054 // - macros defined with parameters accept at most that many of them
2055 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2056 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2058 SMLoc IDLoc = Lexer.getLoc();
2059 MCAsmMacroParameter FA;
2061 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2062 if (parseIdentifier(FA.Name)) {
2063 Error(IDLoc, "invalid argument identifier for formal argument");
2064 eatToEndOfStatement();
2068 if (!Lexer.is(AsmToken::Equal)) {
2069 TokError("expected '=' after formal parameter identifier");
2070 eatToEndOfStatement();
2075 NamedParametersFound = true;
2078 if (NamedParametersFound && FA.Name.empty()) {
2079 Error(IDLoc, "cannot mix positional and keyword arguments");
2080 eatToEndOfStatement();
2084 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2085 if (parseMacroArgument(FA.Value, Vararg))
2088 unsigned PI = Parameter;
2089 if (!FA.Name.empty()) {
2091 for (FAI = 0; FAI < NParameters; ++FAI)
2092 if (M->Parameters[FAI].Name == FA.Name)
2095 if (FAI >= NParameters) {
2096 assert(M && "expected macro to be defined");
2098 "parameter named '" + FA.Name + "' does not exist for macro '" +
2105 if (!FA.Value.empty()) {
2110 if (FALocs.size() <= PI)
2111 FALocs.resize(PI + 1);
2113 FALocs[PI] = Lexer.getLoc();
2116 // At the end of the statement, fill in remaining arguments that have
2117 // default values. If there aren't any, then the next argument is
2118 // required but missing
2119 if (Lexer.is(AsmToken::EndOfStatement)) {
2120 bool Failure = false;
2121 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2122 if (A[FAI].empty()) {
2123 if (M->Parameters[FAI].Required) {
2124 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2125 "missing value for required parameter "
2126 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2130 if (!M->Parameters[FAI].Value.empty())
2131 A[FAI] = M->Parameters[FAI].Value;
2137 if (Lexer.is(AsmToken::Comma))
2141 return TokError("too many positional arguments");
2144 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2145 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2146 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2149 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2150 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2153 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2155 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2156 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2157 // this, although we should protect against infinite loops.
2158 if (ActiveMacros.size() == 20)
2159 return TokError("macros cannot be nested more than 20 levels deep");
2161 MCAsmMacroArguments A;
2162 if (parseMacroArguments(M, A))
2165 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2166 // to hold the macro body with substitutions.
2167 SmallString<256> Buf;
2168 StringRef Body = M->Body;
2169 raw_svector_ostream OS(Buf);
2171 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2174 // We include the .endmacro in the buffer as our cue to exit the macro
2176 OS << ".endmacro\n";
2178 std::unique_ptr<MemoryBuffer> Instantiation =
2179 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2181 // Create the macro instantiation object and add to the current macro
2182 // instantiation stack.
2183 MacroInstantiation *MI = new MacroInstantiation(
2184 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2185 ActiveMacros.push_back(MI);
2187 ++NumOfMacroInstantiations;
2189 // Jump to the macro instantiation and prime the lexer.
2190 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2191 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2197 void AsmParser::handleMacroExit() {
2198 // Jump to the EndOfStatement we should return to, and consume it.
2199 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2202 // Pop the instantiation entry.
2203 delete ActiveMacros.back();
2204 ActiveMacros.pop_back();
2207 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2210 const MCExpr *Value;
2211 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2216 // In the case where we parse an expression starting with a '.', we will
2217 // not generate an error, nor will we create a symbol. In this case we
2218 // should just return out.
2222 // Do the assignment.
2223 Out.EmitAssignment(Sym, Value);
2225 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2230 /// parseIdentifier:
2233 bool AsmParser::parseIdentifier(StringRef &Res) {
2234 // The assembler has relaxed rules for accepting identifiers, in particular we
2235 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2236 // separate tokens. At this level, we have already lexed so we cannot (currently)
2237 // handle this as a context dependent token, instead we detect adjacent tokens
2238 // and return the combined identifier.
2239 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2240 SMLoc PrefixLoc = getLexer().getLoc();
2242 // Consume the prefix character, and check for a following identifier.
2244 if (Lexer.isNot(AsmToken::Identifier))
2247 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2248 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2251 // Construct the joined identifier and consume the token.
2253 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2258 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2261 Res = getTok().getIdentifier();
2263 Lex(); // Consume the identifier token.
2268 /// parseDirectiveSet:
2269 /// ::= .equ identifier ',' expression
2270 /// ::= .equiv identifier ',' expression
2271 /// ::= .set identifier ',' expression
2272 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2275 if (parseIdentifier(Name))
2276 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2278 if (getLexer().isNot(AsmToken::Comma))
2279 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2282 return parseAssignment(Name, allow_redef, true);
2285 bool AsmParser::parseEscapedString(std::string &Data) {
2286 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2289 StringRef Str = getTok().getStringContents();
2290 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2291 if (Str[i] != '\\') {
2296 // Recognize escaped characters. Note that this escape semantics currently
2297 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2300 return TokError("unexpected backslash at end of string");
2302 // Recognize octal sequences.
2303 if ((unsigned)(Str[i] - '0') <= 7) {
2304 // Consume up to three octal characters.
2305 unsigned Value = Str[i] - '0';
2307 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2309 Value = Value * 8 + (Str[i] - '0');
2311 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2313 Value = Value * 8 + (Str[i] - '0');
2318 return TokError("invalid octal escape sequence (out of range)");
2320 Data += (unsigned char)Value;
2324 // Otherwise recognize individual escapes.
2327 // Just reject invalid escape sequences for now.
2328 return TokError("invalid escape sequence (unrecognized character)");
2330 case 'b': Data += '\b'; break;
2331 case 'f': Data += '\f'; break;
2332 case 'n': Data += '\n'; break;
2333 case 'r': Data += '\r'; break;
2334 case 't': Data += '\t'; break;
2335 case '"': Data += '"'; break;
2336 case '\\': Data += '\\'; break;
2343 /// parseDirectiveAscii:
2344 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2345 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2346 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2347 checkForValidSection();
2350 if (getLexer().isNot(AsmToken::String))
2351 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2354 if (parseEscapedString(Data))
2357 getStreamer().EmitBytes(Data);
2359 getStreamer().EmitBytes(StringRef("\0", 1));
2363 if (getLexer().is(AsmToken::EndOfStatement))
2366 if (getLexer().isNot(AsmToken::Comma))
2367 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2376 /// parseDirectiveValue
2377 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2378 bool AsmParser::parseDirectiveValue(unsigned Size) {
2379 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2380 checkForValidSection();
2383 const MCExpr *Value;
2384 SMLoc ExprLoc = getLexer().getLoc();
2385 if (parseExpression(Value))
2388 // Special case constant expressions to match code generator.
2389 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2390 assert(Size <= 8 && "Invalid size");
2391 uint64_t IntValue = MCE->getValue();
2392 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2393 return Error(ExprLoc, "literal value out of range for directive");
2394 getStreamer().EmitIntValue(IntValue, Size);
2396 getStreamer().EmitValue(Value, Size, ExprLoc);
2398 if (getLexer().is(AsmToken::EndOfStatement))
2401 // FIXME: Improve diagnostic.
2402 if (getLexer().isNot(AsmToken::Comma))
2403 return TokError("unexpected token in directive");
2412 /// ParseDirectiveOctaValue
2413 /// ::= .octa [ hexconstant (, hexconstant)* ]
2414 bool AsmParser::parseDirectiveOctaValue() {
2415 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2416 checkForValidSection();
2419 if (Lexer.getKind() == AsmToken::Error)
2421 if (Lexer.getKind() != AsmToken::Integer &&
2422 Lexer.getKind() != AsmToken::BigNum)
2423 return TokError("unknown token in expression");
2425 SMLoc ExprLoc = getLexer().getLoc();
2426 APInt IntValue = getTok().getAPIntVal();
2430 if (IntValue.isIntN(64)) {
2432 lo = IntValue.getZExtValue();
2433 } else if (IntValue.isIntN(128)) {
2434 // It might actually have more than 128 bits, but the top ones are zero.
2435 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2436 lo = IntValue.getLoBits(64).getZExtValue();
2438 return Error(ExprLoc, "literal value out of range for directive");
2440 if (MAI.isLittleEndian()) {
2441 getStreamer().EmitIntValue(lo, 8);
2442 getStreamer().EmitIntValue(hi, 8);
2444 getStreamer().EmitIntValue(hi, 8);
2445 getStreamer().EmitIntValue(lo, 8);
2448 if (getLexer().is(AsmToken::EndOfStatement))
2451 // FIXME: Improve diagnostic.
2452 if (getLexer().isNot(AsmToken::Comma))
2453 return TokError("unexpected token in directive");
2462 /// parseDirectiveRealValue
2463 /// ::= (.single | .double) [ expression (, expression)* ]
2464 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2465 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2466 checkForValidSection();
2469 // We don't truly support arithmetic on floating point expressions, so we
2470 // have to manually parse unary prefixes.
2472 if (getLexer().is(AsmToken::Minus)) {
2475 } else if (getLexer().is(AsmToken::Plus))
2478 if (getLexer().isNot(AsmToken::Integer) &&
2479 getLexer().isNot(AsmToken::Real) &&
2480 getLexer().isNot(AsmToken::Identifier))
2481 return TokError("unexpected token in directive");
2483 // Convert to an APFloat.
2484 APFloat Value(Semantics);
2485 StringRef IDVal = getTok().getString();
2486 if (getLexer().is(AsmToken::Identifier)) {
2487 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2488 Value = APFloat::getInf(Semantics);
2489 else if (!IDVal.compare_lower("nan"))
2490 Value = APFloat::getNaN(Semantics, false, ~0);
2492 return TokError("invalid floating point literal");
2493 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2494 APFloat::opInvalidOp)
2495 return TokError("invalid floating point literal");
2499 // Consume the numeric token.
2502 // Emit the value as an integer.
2503 APInt AsInt = Value.bitcastToAPInt();
2504 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2505 AsInt.getBitWidth() / 8);
2507 if (getLexer().is(AsmToken::EndOfStatement))
2510 if (getLexer().isNot(AsmToken::Comma))
2511 return TokError("unexpected token in directive");
2520 /// parseDirectiveZero
2521 /// ::= .zero expression
2522 bool AsmParser::parseDirectiveZero() {
2523 checkForValidSection();
2526 if (parseAbsoluteExpression(NumBytes))
2530 if (getLexer().is(AsmToken::Comma)) {
2532 if (parseAbsoluteExpression(Val))
2536 if (getLexer().isNot(AsmToken::EndOfStatement))
2537 return TokError("unexpected token in '.zero' directive");
2541 getStreamer().EmitFill(NumBytes, Val);
2546 /// parseDirectiveFill
2547 /// ::= .fill expression [ , expression [ , expression ] ]
2548 bool AsmParser::parseDirectiveFill() {
2549 checkForValidSection();
2551 SMLoc RepeatLoc = getLexer().getLoc();
2553 if (parseAbsoluteExpression(NumValues))
2556 if (NumValues < 0) {
2558 "'.fill' directive with negative repeat count has no effect");
2562 int64_t FillSize = 1;
2563 int64_t FillExpr = 0;
2565 SMLoc SizeLoc, ExprLoc;
2566 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2567 if (getLexer().isNot(AsmToken::Comma))
2568 return TokError("unexpected token in '.fill' directive");
2571 SizeLoc = getLexer().getLoc();
2572 if (parseAbsoluteExpression(FillSize))
2575 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2576 if (getLexer().isNot(AsmToken::Comma))
2577 return TokError("unexpected token in '.fill' directive");
2580 ExprLoc = getLexer().getLoc();
2581 if (parseAbsoluteExpression(FillExpr))
2584 if (getLexer().isNot(AsmToken::EndOfStatement))
2585 return TokError("unexpected token in '.fill' directive");
2592 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2596 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2600 if (!isUInt<32>(FillExpr) && FillSize > 4)
2601 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2603 if (NumValues > 0) {
2604 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2605 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2606 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2607 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2608 if (NonZeroFillSize < FillSize)
2609 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2616 /// parseDirectiveOrg
2617 /// ::= .org expression [ , expression ]
2618 bool AsmParser::parseDirectiveOrg() {
2619 checkForValidSection();
2621 const MCExpr *Offset;
2622 SMLoc Loc = getTok().getLoc();
2623 if (parseExpression(Offset))
2626 // Parse optional fill expression.
2627 int64_t FillExpr = 0;
2628 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2629 if (getLexer().isNot(AsmToken::Comma))
2630 return TokError("unexpected token in '.org' directive");
2633 if (parseAbsoluteExpression(FillExpr))
2636 if (getLexer().isNot(AsmToken::EndOfStatement))
2637 return TokError("unexpected token in '.org' directive");
2642 // Only limited forms of relocatable expressions are accepted here, it
2643 // has to be relative to the current section. The streamer will return
2644 // 'true' if the expression wasn't evaluatable.
2645 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2646 return Error(Loc, "expected assembly-time absolute expression");
2651 /// parseDirectiveAlign
2652 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2653 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2654 checkForValidSection();
2656 SMLoc AlignmentLoc = getLexer().getLoc();
2658 if (parseAbsoluteExpression(Alignment))
2662 bool HasFillExpr = false;
2663 int64_t FillExpr = 0;
2664 int64_t MaxBytesToFill = 0;
2665 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2666 if (getLexer().isNot(AsmToken::Comma))
2667 return TokError("unexpected token in directive");
2670 // The fill expression can be omitted while specifying a maximum number of
2671 // alignment bytes, e.g:
2673 if (getLexer().isNot(AsmToken::Comma)) {
2675 if (parseAbsoluteExpression(FillExpr))
2679 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2680 if (getLexer().isNot(AsmToken::Comma))
2681 return TokError("unexpected token in directive");
2684 MaxBytesLoc = getLexer().getLoc();
2685 if (parseAbsoluteExpression(MaxBytesToFill))
2688 if (getLexer().isNot(AsmToken::EndOfStatement))
2689 return TokError("unexpected token in directive");
2698 // Compute alignment in bytes.
2700 // FIXME: Diagnose overflow.
2701 if (Alignment >= 32) {
2702 Error(AlignmentLoc, "invalid alignment value");
2706 Alignment = 1ULL << Alignment;
2708 // Reject alignments that aren't a power of two, for gas compatibility.
2709 if (!isPowerOf2_64(Alignment))
2710 Error(AlignmentLoc, "alignment must be a power of 2");
2713 // Diagnose non-sensical max bytes to align.
2714 if (MaxBytesLoc.isValid()) {
2715 if (MaxBytesToFill < 1) {
2716 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2717 "many bytes, ignoring maximum bytes expression");
2721 if (MaxBytesToFill >= Alignment) {
2722 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2728 // Check whether we should use optimal code alignment for this .align
2730 const MCSection *Section = getStreamer().getCurrentSection().first;
2731 assert(Section && "must have section to emit alignment");
2732 bool UseCodeAlign = Section->UseCodeAlign();
2733 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2734 ValueSize == 1 && UseCodeAlign) {
2735 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2737 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2738 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2745 /// parseDirectiveFile
2746 /// ::= .file [number] filename
2747 /// ::= .file number directory filename
2748 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2749 // FIXME: I'm not sure what this is.
2750 int64_t FileNumber = -1;
2751 SMLoc FileNumberLoc = getLexer().getLoc();
2752 if (getLexer().is(AsmToken::Integer)) {
2753 FileNumber = getTok().getIntVal();
2757 return TokError("file number less than one");
2760 if (getLexer().isNot(AsmToken::String))
2761 return TokError("unexpected token in '.file' directive");
2763 // Usually the directory and filename together, otherwise just the directory.
2764 // Allow the strings to have escaped octal character sequence.
2765 std::string Path = getTok().getString();
2766 if (parseEscapedString(Path))
2770 StringRef Directory;
2772 std::string FilenameData;
2773 if (getLexer().is(AsmToken::String)) {
2774 if (FileNumber == -1)
2775 return TokError("explicit path specified, but no file number");
2776 if (parseEscapedString(FilenameData))
2778 Filename = FilenameData;
2785 if (getLexer().isNot(AsmToken::EndOfStatement))
2786 return TokError("unexpected token in '.file' directive");
2788 if (FileNumber == -1)
2789 getStreamer().EmitFileDirective(Filename);
2791 if (getContext().getGenDwarfForAssembly())
2793 "input can't have .file dwarf directives when -g is "
2794 "used to generate dwarf debug info for assembly code");
2796 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2798 Error(FileNumberLoc, "file number already allocated");
2804 /// parseDirectiveLine
2805 /// ::= .line [number]
2806 bool AsmParser::parseDirectiveLine() {
2807 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2808 if (getLexer().isNot(AsmToken::Integer))
2809 return TokError("unexpected token in '.line' directive");
2811 int64_t LineNumber = getTok().getIntVal();
2815 // FIXME: Do something with the .line.
2818 if (getLexer().isNot(AsmToken::EndOfStatement))
2819 return TokError("unexpected token in '.line' directive");
2824 /// parseDirectiveLoc
2825 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2826 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2827 /// The first number is a file number, must have been previously assigned with
2828 /// a .file directive, the second number is the line number and optionally the
2829 /// third number is a column position (zero if not specified). The remaining
2830 /// optional items are .loc sub-directives.
2831 bool AsmParser::parseDirectiveLoc() {
2832 if (getLexer().isNot(AsmToken::Integer))
2833 return TokError("unexpected token in '.loc' directive");
2834 int64_t FileNumber = getTok().getIntVal();
2836 return TokError("file number less than one in '.loc' directive");
2837 if (!getContext().isValidDwarfFileNumber(FileNumber))
2838 return TokError("unassigned file number in '.loc' directive");
2841 int64_t LineNumber = 0;
2842 if (getLexer().is(AsmToken::Integer)) {
2843 LineNumber = getTok().getIntVal();
2845 return TokError("line number less than zero in '.loc' directive");
2849 int64_t ColumnPos = 0;
2850 if (getLexer().is(AsmToken::Integer)) {
2851 ColumnPos = getTok().getIntVal();
2853 return TokError("column position less than zero in '.loc' directive");
2857 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2859 int64_t Discriminator = 0;
2860 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2862 if (getLexer().is(AsmToken::EndOfStatement))
2866 SMLoc Loc = getTok().getLoc();
2867 if (parseIdentifier(Name))
2868 return TokError("unexpected token in '.loc' directive");
2870 if (Name == "basic_block")
2871 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2872 else if (Name == "prologue_end")
2873 Flags |= DWARF2_FLAG_PROLOGUE_END;
2874 else if (Name == "epilogue_begin")
2875 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2876 else if (Name == "is_stmt") {
2877 Loc = getTok().getLoc();
2878 const MCExpr *Value;
2879 if (parseExpression(Value))
2881 // The expression must be the constant 0 or 1.
2882 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2883 int Value = MCE->getValue();
2885 Flags &= ~DWARF2_FLAG_IS_STMT;
2886 else if (Value == 1)
2887 Flags |= DWARF2_FLAG_IS_STMT;
2889 return Error(Loc, "is_stmt value not 0 or 1");
2891 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2893 } else if (Name == "isa") {
2894 Loc = getTok().getLoc();
2895 const MCExpr *Value;
2896 if (parseExpression(Value))
2898 // The expression must be a constant greater or equal to 0.
2899 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2900 int Value = MCE->getValue();
2902 return Error(Loc, "isa number less than zero");
2905 return Error(Loc, "isa number not a constant value");
2907 } else if (Name == "discriminator") {
2908 if (parseAbsoluteExpression(Discriminator))
2911 return Error(Loc, "unknown sub-directive in '.loc' directive");
2914 if (getLexer().is(AsmToken::EndOfStatement))
2919 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2920 Isa, Discriminator, StringRef());
2925 /// parseDirectiveStabs
2926 /// ::= .stabs string, number, number, number
2927 bool AsmParser::parseDirectiveStabs() {
2928 return TokError("unsupported directive '.stabs'");
2931 /// parseDirectiveCFISections
2932 /// ::= .cfi_sections section [, section]
2933 bool AsmParser::parseDirectiveCFISections() {
2938 if (parseIdentifier(Name))
2939 return TokError("Expected an identifier");
2941 if (Name == ".eh_frame")
2943 else if (Name == ".debug_frame")
2946 if (getLexer().is(AsmToken::Comma)) {
2949 if (parseIdentifier(Name))
2950 return TokError("Expected an identifier");
2952 if (Name == ".eh_frame")
2954 else if (Name == ".debug_frame")
2958 getStreamer().EmitCFISections(EH, Debug);
2962 /// parseDirectiveCFIStartProc
2963 /// ::= .cfi_startproc [simple]
2964 bool AsmParser::parseDirectiveCFIStartProc() {
2966 if (getLexer().isNot(AsmToken::EndOfStatement))
2967 if (parseIdentifier(Simple) || Simple != "simple")
2968 return TokError("unexpected token in .cfi_startproc directive");
2970 getStreamer().EmitCFIStartProc(!Simple.empty());
2974 /// parseDirectiveCFIEndProc
2975 /// ::= .cfi_endproc
2976 bool AsmParser::parseDirectiveCFIEndProc() {
2977 getStreamer().EmitCFIEndProc();
2981 /// \brief parse register name or number.
2982 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2983 SMLoc DirectiveLoc) {
2986 if (getLexer().isNot(AsmToken::Integer)) {
2987 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2989 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2991 return parseAbsoluteExpression(Register);
2996 /// parseDirectiveCFIDefCfa
2997 /// ::= .cfi_def_cfa register, offset
2998 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2999 int64_t Register = 0;
3000 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3003 if (getLexer().isNot(AsmToken::Comma))
3004 return TokError("unexpected token in directive");
3008 if (parseAbsoluteExpression(Offset))
3011 getStreamer().EmitCFIDefCfa(Register, Offset);
3015 /// parseDirectiveCFIDefCfaOffset
3016 /// ::= .cfi_def_cfa_offset offset
3017 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3019 if (parseAbsoluteExpression(Offset))
3022 getStreamer().EmitCFIDefCfaOffset(Offset);
3026 /// parseDirectiveCFIRegister
3027 /// ::= .cfi_register register, register
3028 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3029 int64_t Register1 = 0;
3030 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3033 if (getLexer().isNot(AsmToken::Comma))
3034 return TokError("unexpected token in directive");
3037 int64_t Register2 = 0;
3038 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3041 getStreamer().EmitCFIRegister(Register1, Register2);
3045 /// parseDirectiveCFIWindowSave
3046 /// ::= .cfi_window_save
3047 bool AsmParser::parseDirectiveCFIWindowSave() {
3048 getStreamer().EmitCFIWindowSave();
3052 /// parseDirectiveCFIAdjustCfaOffset
3053 /// ::= .cfi_adjust_cfa_offset adjustment
3054 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3055 int64_t Adjustment = 0;
3056 if (parseAbsoluteExpression(Adjustment))
3059 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3063 /// parseDirectiveCFIDefCfaRegister
3064 /// ::= .cfi_def_cfa_register register
3065 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3066 int64_t Register = 0;
3067 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3070 getStreamer().EmitCFIDefCfaRegister(Register);
3074 /// parseDirectiveCFIOffset
3075 /// ::= .cfi_offset register, offset
3076 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3077 int64_t Register = 0;
3080 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3083 if (getLexer().isNot(AsmToken::Comma))
3084 return TokError("unexpected token in directive");
3087 if (parseAbsoluteExpression(Offset))
3090 getStreamer().EmitCFIOffset(Register, Offset);
3094 /// parseDirectiveCFIRelOffset
3095 /// ::= .cfi_rel_offset register, offset
3096 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3097 int64_t Register = 0;
3099 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3102 if (getLexer().isNot(AsmToken::Comma))
3103 return TokError("unexpected token in directive");
3107 if (parseAbsoluteExpression(Offset))
3110 getStreamer().EmitCFIRelOffset(Register, Offset);
3114 static bool isValidEncoding(int64_t Encoding) {
3115 if (Encoding & ~0xff)
3118 if (Encoding == dwarf::DW_EH_PE_omit)
3121 const unsigned Format = Encoding & 0xf;
3122 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3123 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3124 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3125 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3128 const unsigned Application = Encoding & 0x70;
3129 if (Application != dwarf::DW_EH_PE_absptr &&
3130 Application != dwarf::DW_EH_PE_pcrel)
3136 /// parseDirectiveCFIPersonalityOrLsda
3137 /// IsPersonality true for cfi_personality, false for cfi_lsda
3138 /// ::= .cfi_personality encoding, [symbol_name]
3139 /// ::= .cfi_lsda encoding, [symbol_name]
3140 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3141 int64_t Encoding = 0;
3142 if (parseAbsoluteExpression(Encoding))
3144 if (Encoding == dwarf::DW_EH_PE_omit)
3147 if (!isValidEncoding(Encoding))
3148 return TokError("unsupported encoding.");
3150 if (getLexer().isNot(AsmToken::Comma))
3151 return TokError("unexpected token in directive");
3155 if (parseIdentifier(Name))
3156 return TokError("expected identifier in directive");
3158 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3161 getStreamer().EmitCFIPersonality(Sym, Encoding);
3163 getStreamer().EmitCFILsda(Sym, Encoding);
3167 /// parseDirectiveCFIRememberState
3168 /// ::= .cfi_remember_state
3169 bool AsmParser::parseDirectiveCFIRememberState() {
3170 getStreamer().EmitCFIRememberState();
3174 /// parseDirectiveCFIRestoreState
3175 /// ::= .cfi_remember_state
3176 bool AsmParser::parseDirectiveCFIRestoreState() {
3177 getStreamer().EmitCFIRestoreState();
3181 /// parseDirectiveCFISameValue
3182 /// ::= .cfi_same_value register
3183 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3184 int64_t Register = 0;
3186 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3189 getStreamer().EmitCFISameValue(Register);
3193 /// parseDirectiveCFIRestore
3194 /// ::= .cfi_restore register
3195 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3196 int64_t Register = 0;
3197 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3200 getStreamer().EmitCFIRestore(Register);
3204 /// parseDirectiveCFIEscape
3205 /// ::= .cfi_escape expression[,...]
3206 bool AsmParser::parseDirectiveCFIEscape() {
3209 if (parseAbsoluteExpression(CurrValue))
3212 Values.push_back((uint8_t)CurrValue);
3214 while (getLexer().is(AsmToken::Comma)) {
3217 if (parseAbsoluteExpression(CurrValue))
3220 Values.push_back((uint8_t)CurrValue);
3223 getStreamer().EmitCFIEscape(Values);
3227 /// parseDirectiveCFISignalFrame
3228 /// ::= .cfi_signal_frame
3229 bool AsmParser::parseDirectiveCFISignalFrame() {
3230 if (getLexer().isNot(AsmToken::EndOfStatement))
3231 return Error(getLexer().getLoc(),
3232 "unexpected token in '.cfi_signal_frame'");
3234 getStreamer().EmitCFISignalFrame();
3238 /// parseDirectiveCFIUndefined
3239 /// ::= .cfi_undefined register
3240 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3241 int64_t Register = 0;
3243 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3246 getStreamer().EmitCFIUndefined(Register);
3250 /// parseDirectiveMacrosOnOff
3253 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3254 if (getLexer().isNot(AsmToken::EndOfStatement))
3255 return Error(getLexer().getLoc(),
3256 "unexpected token in '" + Directive + "' directive");
3258 setMacrosEnabled(Directive == ".macros_on");
3262 /// parseDirectiveMacro
3263 /// ::= .macro name[,] [parameters]
3264 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3266 if (parseIdentifier(Name))
3267 return TokError("expected identifier in '.macro' directive");
3269 if (getLexer().is(AsmToken::Comma))
3272 MCAsmMacroParameters Parameters;
3273 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3275 if (!Parameters.empty() && Parameters.back().Vararg)
3276 return Error(Lexer.getLoc(),
3277 "Vararg parameter '" + Parameters.back().Name +
3278 "' should be last one in the list of parameters.");
3280 MCAsmMacroParameter Parameter;
3281 if (parseIdentifier(Parameter.Name))
3282 return TokError("expected identifier in '.macro' directive");
3284 if (Lexer.is(AsmToken::Colon)) {
3285 Lex(); // consume ':'
3288 StringRef Qualifier;
3290 QualLoc = Lexer.getLoc();
3291 if (parseIdentifier(Qualifier))
3292 return Error(QualLoc, "missing parameter qualifier for "
3293 "'" + Parameter.Name + "' in macro '" + Name + "'");
3295 if (Qualifier == "req")
3296 Parameter.Required = true;
3297 else if (Qualifier == "vararg")
3298 Parameter.Vararg = true;
3300 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3301 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3304 if (getLexer().is(AsmToken::Equal)) {
3309 ParamLoc = Lexer.getLoc();
3310 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3313 if (Parameter.Required)
3314 Warning(ParamLoc, "pointless default value for required parameter "
3315 "'" + Parameter.Name + "' in macro '" + Name + "'");
3318 Parameters.push_back(std::move(Parameter));
3320 if (getLexer().is(AsmToken::Comma))
3324 // Eat the end of statement.
3327 AsmToken EndToken, StartToken = getTok();
3328 unsigned MacroDepth = 0;
3330 // Lex the macro definition.
3332 // Check whether we have reached the end of the file.
3333 if (getLexer().is(AsmToken::Eof))
3334 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3336 // Otherwise, check whether we have reach the .endmacro.
3337 if (getLexer().is(AsmToken::Identifier)) {
3338 if (getTok().getIdentifier() == ".endm" ||
3339 getTok().getIdentifier() == ".endmacro") {
3340 if (MacroDepth == 0) { // Outermost macro.
3341 EndToken = getTok();
3343 if (getLexer().isNot(AsmToken::EndOfStatement))
3344 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3348 // Otherwise we just found the end of an inner macro.
3351 } else if (getTok().getIdentifier() == ".macro") {
3352 // We allow nested macros. Those aren't instantiated until the outermost
3353 // macro is expanded so just ignore them for now.
3358 // Otherwise, scan til the end of the statement.
3359 eatToEndOfStatement();
3362 if (lookupMacro(Name)) {
3363 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3366 const char *BodyStart = StartToken.getLoc().getPointer();
3367 const char *BodyEnd = EndToken.getLoc().getPointer();
3368 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3369 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3370 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3374 /// checkForBadMacro
3376 /// With the support added for named parameters there may be code out there that
3377 /// is transitioning from positional parameters. In versions of gas that did
3378 /// not support named parameters they would be ignored on the macro definition.
3379 /// But to support both styles of parameters this is not possible so if a macro
3380 /// definition has named parameters but does not use them and has what appears
3381 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3382 /// warning that the positional parameter found in body which have no effect.
3383 /// Hoping the developer will either remove the named parameters from the macro
3384 /// definition so the positional parameters get used if that was what was
3385 /// intended or change the macro to use the named parameters. It is possible
3386 /// this warning will trigger when the none of the named parameters are used
3387 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3388 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3390 ArrayRef<MCAsmMacroParameter> Parameters) {
3391 // If this macro is not defined with named parameters the warning we are
3392 // checking for here doesn't apply.
3393 unsigned NParameters = Parameters.size();
3394 if (NParameters == 0)
3397 bool NamedParametersFound = false;
3398 bool PositionalParametersFound = false;
3400 // Look at the body of the macro for use of both the named parameters and what
3401 // are likely to be positional parameters. This is what expandMacro() is
3402 // doing when it finds the parameters in the body.
3403 while (!Body.empty()) {
3404 // Scan for the next possible parameter.
3405 std::size_t End = Body.size(), Pos = 0;
3406 for (; Pos != End; ++Pos) {
3407 // Check for a substitution or escape.
3408 // This macro is defined with parameters, look for \foo, \bar, etc.
3409 if (Body[Pos] == '\\' && Pos + 1 != End)
3412 // This macro should have parameters, but look for $0, $1, ..., $n too.
3413 if (Body[Pos] != '$' || Pos + 1 == End)
3415 char Next = Body[Pos + 1];
3416 if (Next == '$' || Next == 'n' ||
3417 isdigit(static_cast<unsigned char>(Next)))
3421 // Check if we reached the end.
3425 if (Body[Pos] == '$') {
3426 switch (Body[Pos + 1]) {
3431 // $n => number of arguments
3433 PositionalParametersFound = true;
3436 // $[0-9] => argument
3438 PositionalParametersFound = true;
3444 unsigned I = Pos + 1;
3445 while (isIdentifierChar(Body[I]) && I + 1 != End)
3448 const char *Begin = Body.data() + Pos + 1;
3449 StringRef Argument(Begin, I - (Pos + 1));
3451 for (; Index < NParameters; ++Index)
3452 if (Parameters[Index].Name == Argument)
3455 if (Index == NParameters) {
3456 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3462 NamedParametersFound = true;
3463 Pos += 1 + Argument.size();
3466 // Update the scan point.
3467 Body = Body.substr(Pos);
3470 if (!NamedParametersFound && PositionalParametersFound)
3471 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3472 "used in macro body, possible positional parameter "
3473 "found in body which will have no effect");
3476 /// parseDirectiveExitMacro
3478 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3479 if (getLexer().isNot(AsmToken::EndOfStatement))
3480 return TokError("unexpected token in '" + Directive + "' directive");
3482 if (!isInsideMacroInstantiation())
3483 return TokError("unexpected '" + Directive + "' in file, "
3484 "no current macro definition");
3486 // Exit all conditionals that are active in the current macro.
3487 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3488 TheCondState = TheCondStack.back();
3489 TheCondStack.pop_back();
3496 /// parseDirectiveEndMacro
3499 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3500 if (getLexer().isNot(AsmToken::EndOfStatement))
3501 return TokError("unexpected token in '" + Directive + "' directive");
3503 // If we are inside a macro instantiation, terminate the current
3505 if (isInsideMacroInstantiation()) {
3510 // Otherwise, this .endmacro is a stray entry in the file; well formed
3511 // .endmacro directives are handled during the macro definition parsing.
3512 return TokError("unexpected '" + Directive + "' in file, "
3513 "no current macro definition");
3516 /// parseDirectivePurgeMacro
3518 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3520 if (parseIdentifier(Name))
3521 return TokError("expected identifier in '.purgem' directive");
3523 if (getLexer().isNot(AsmToken::EndOfStatement))
3524 return TokError("unexpected token in '.purgem' directive");
3526 if (!lookupMacro(Name))
3527 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3529 undefineMacro(Name);
3533 /// parseDirectiveBundleAlignMode
3534 /// ::= {.bundle_align_mode} expression
3535 bool AsmParser::parseDirectiveBundleAlignMode() {
3536 checkForValidSection();
3538 // Expect a single argument: an expression that evaluates to a constant
3539 // in the inclusive range 0-30.
3540 SMLoc ExprLoc = getLexer().getLoc();
3541 int64_t AlignSizePow2;
3542 if (parseAbsoluteExpression(AlignSizePow2))
3544 else if (getLexer().isNot(AsmToken::EndOfStatement))
3545 return TokError("unexpected token after expression in"
3546 " '.bundle_align_mode' directive");
3547 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3548 return Error(ExprLoc,
3549 "invalid bundle alignment size (expected between 0 and 30)");
3553 // Because of AlignSizePow2's verified range we can safely truncate it to
3555 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3559 /// parseDirectiveBundleLock
3560 /// ::= {.bundle_lock} [align_to_end]
3561 bool AsmParser::parseDirectiveBundleLock() {
3562 checkForValidSection();
3563 bool AlignToEnd = false;
3565 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3567 SMLoc Loc = getTok().getLoc();
3568 const char *kInvalidOptionError =
3569 "invalid option for '.bundle_lock' directive";
3571 if (parseIdentifier(Option))
3572 return Error(Loc, kInvalidOptionError);
3574 if (Option != "align_to_end")
3575 return Error(Loc, kInvalidOptionError);
3576 else if (getLexer().isNot(AsmToken::EndOfStatement))
3578 "unexpected token after '.bundle_lock' directive option");
3584 getStreamer().EmitBundleLock(AlignToEnd);
3588 /// parseDirectiveBundleLock
3589 /// ::= {.bundle_lock}
3590 bool AsmParser::parseDirectiveBundleUnlock() {
3591 checkForValidSection();
3593 if (getLexer().isNot(AsmToken::EndOfStatement))
3594 return TokError("unexpected token in '.bundle_unlock' directive");
3597 getStreamer().EmitBundleUnlock();
3601 /// parseDirectiveSpace
3602 /// ::= (.skip | .space) expression [ , expression ]
3603 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3604 checkForValidSection();
3607 if (parseAbsoluteExpression(NumBytes))
3610 int64_t FillExpr = 0;
3611 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3612 if (getLexer().isNot(AsmToken::Comma))
3613 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3616 if (parseAbsoluteExpression(FillExpr))
3619 if (getLexer().isNot(AsmToken::EndOfStatement))
3620 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3626 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3629 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3630 getStreamer().EmitFill(NumBytes, FillExpr);
3635 /// parseDirectiveLEB128
3636 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3637 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3638 checkForValidSection();
3639 const MCExpr *Value;
3642 if (parseExpression(Value))
3646 getStreamer().EmitSLEB128Value(Value);
3648 getStreamer().EmitULEB128Value(Value);
3650 if (getLexer().is(AsmToken::EndOfStatement))
3653 if (getLexer().isNot(AsmToken::Comma))
3654 return TokError("unexpected token in directive");
3661 /// parseDirectiveSymbolAttribute
3662 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3663 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3664 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3667 SMLoc Loc = getTok().getLoc();
3669 if (parseIdentifier(Name))
3670 return Error(Loc, "expected identifier in directive");
3672 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3674 // Assembler local symbols don't make any sense here. Complain loudly.
3675 if (Sym->isTemporary())
3676 return Error(Loc, "non-local symbol required in directive");
3678 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3679 return Error(Loc, "unable to emit symbol attribute");
3681 if (getLexer().is(AsmToken::EndOfStatement))
3684 if (getLexer().isNot(AsmToken::Comma))
3685 return TokError("unexpected token in directive");
3694 /// parseDirectiveComm
3695 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3696 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3697 checkForValidSection();
3699 SMLoc IDLoc = getLexer().getLoc();
3701 if (parseIdentifier(Name))
3702 return TokError("expected identifier in directive");
3704 // Handle the identifier as the key symbol.
3705 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3707 if (getLexer().isNot(AsmToken::Comma))
3708 return TokError("unexpected token in directive");
3712 SMLoc SizeLoc = getLexer().getLoc();
3713 if (parseAbsoluteExpression(Size))
3716 int64_t Pow2Alignment = 0;
3717 SMLoc Pow2AlignmentLoc;
3718 if (getLexer().is(AsmToken::Comma)) {
3720 Pow2AlignmentLoc = getLexer().getLoc();
3721 if (parseAbsoluteExpression(Pow2Alignment))
3724 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3725 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3726 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3728 // If this target takes alignments in bytes (not log) validate and convert.
3729 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3730 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3731 if (!isPowerOf2_64(Pow2Alignment))
3732 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3733 Pow2Alignment = Log2_64(Pow2Alignment);
3737 if (getLexer().isNot(AsmToken::EndOfStatement))
3738 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3742 // NOTE: a size of zero for a .comm should create a undefined symbol
3743 // but a size of .lcomm creates a bss symbol of size zero.
3745 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3746 "be less than zero");
3748 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3749 // may internally end up wanting an alignment in bytes.
3750 // FIXME: Diagnose overflow.
3751 if (Pow2Alignment < 0)
3752 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3753 "alignment, can't be less than zero");
3755 if (!Sym->isUndefined())
3756 return Error(IDLoc, "invalid symbol redefinition");
3758 // Create the Symbol as a common or local common with Size and Pow2Alignment
3760 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3764 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3768 /// parseDirectiveAbort
3769 /// ::= .abort [... message ...]
3770 bool AsmParser::parseDirectiveAbort() {
3771 // FIXME: Use loc from directive.
3772 SMLoc Loc = getLexer().getLoc();
3774 StringRef Str = parseStringToEndOfStatement();
3775 if (getLexer().isNot(AsmToken::EndOfStatement))
3776 return TokError("unexpected token in '.abort' directive");
3781 Error(Loc, ".abort detected. Assembly stopping.");
3783 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3784 // FIXME: Actually abort assembly here.
3789 /// parseDirectiveInclude
3790 /// ::= .include "filename"
3791 bool AsmParser::parseDirectiveInclude() {
3792 if (getLexer().isNot(AsmToken::String))
3793 return TokError("expected string in '.include' directive");
3795 // Allow the strings to have escaped octal character sequence.
3796 std::string Filename;
3797 if (parseEscapedString(Filename))
3799 SMLoc IncludeLoc = getLexer().getLoc();
3802 if (getLexer().isNot(AsmToken::EndOfStatement))
3803 return TokError("unexpected token in '.include' directive");
3805 // Attempt to switch the lexer to the included file before consuming the end
3806 // of statement to avoid losing it when we switch.
3807 if (enterIncludeFile(Filename)) {
3808 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3815 /// parseDirectiveIncbin
3816 /// ::= .incbin "filename"
3817 bool AsmParser::parseDirectiveIncbin() {
3818 if (getLexer().isNot(AsmToken::String))
3819 return TokError("expected string in '.incbin' directive");
3821 // Allow the strings to have escaped octal character sequence.
3822 std::string Filename;
3823 if (parseEscapedString(Filename))
3825 SMLoc IncbinLoc = getLexer().getLoc();
3828 if (getLexer().isNot(AsmToken::EndOfStatement))
3829 return TokError("unexpected token in '.incbin' directive");
3831 // Attempt to process the included file.
3832 if (processIncbinFile(Filename)) {
3833 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3840 /// parseDirectiveIf
3841 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3842 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3843 TheCondStack.push_back(TheCondState);
3844 TheCondState.TheCond = AsmCond::IfCond;
3845 if (TheCondState.Ignore) {
3846 eatToEndOfStatement();
3849 if (parseAbsoluteExpression(ExprValue))
3852 if (getLexer().isNot(AsmToken::EndOfStatement))
3853 return TokError("unexpected token in '.if' directive");
3859 llvm_unreachable("unsupported directive");
3864 ExprValue = ExprValue == 0;
3867 ExprValue = ExprValue >= 0;
3870 ExprValue = ExprValue > 0;
3873 ExprValue = ExprValue <= 0;
3876 ExprValue = ExprValue < 0;
3880 TheCondState.CondMet = ExprValue;
3881 TheCondState.Ignore = !TheCondState.CondMet;
3887 /// parseDirectiveIfb
3889 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3890 TheCondStack.push_back(TheCondState);
3891 TheCondState.TheCond = AsmCond::IfCond;
3893 if (TheCondState.Ignore) {
3894 eatToEndOfStatement();
3896 StringRef Str = parseStringToEndOfStatement();
3898 if (getLexer().isNot(AsmToken::EndOfStatement))
3899 return TokError("unexpected token in '.ifb' directive");
3903 TheCondState.CondMet = ExpectBlank == Str.empty();
3904 TheCondState.Ignore = !TheCondState.CondMet;
3910 /// parseDirectiveIfc
3911 /// ::= .ifc string1, string2
3912 /// ::= .ifnc string1, string2
3913 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3914 TheCondStack.push_back(TheCondState);
3915 TheCondState.TheCond = AsmCond::IfCond;
3917 if (TheCondState.Ignore) {
3918 eatToEndOfStatement();
3920 StringRef Str1 = parseStringToComma();
3922 if (getLexer().isNot(AsmToken::Comma))
3923 return TokError("unexpected token in '.ifc' directive");
3927 StringRef Str2 = parseStringToEndOfStatement();
3929 if (getLexer().isNot(AsmToken::EndOfStatement))
3930 return TokError("unexpected token in '.ifc' directive");
3934 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3935 TheCondState.Ignore = !TheCondState.CondMet;
3941 /// parseDirectiveIfeqs
3942 /// ::= .ifeqs string1, string2
3943 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3944 if (Lexer.isNot(AsmToken::String)) {
3946 TokError("expected string parameter for '.ifeqs' directive");
3948 TokError("expected string parameter for '.ifnes' directive");
3949 eatToEndOfStatement();
3953 StringRef String1 = getTok().getStringContents();
3956 if (Lexer.isNot(AsmToken::Comma)) {
3958 TokError("expected comma after first string for '.ifeqs' directive");
3960 TokError("expected comma after first string for '.ifnes' directive");
3961 eatToEndOfStatement();
3967 if (Lexer.isNot(AsmToken::String)) {
3969 TokError("expected string parameter for '.ifeqs' directive");
3971 TokError("expected string parameter for '.ifnes' directive");
3972 eatToEndOfStatement();
3976 StringRef String2 = getTok().getStringContents();
3979 TheCondStack.push_back(TheCondState);
3980 TheCondState.TheCond = AsmCond::IfCond;
3981 TheCondState.CondMet = ExpectEqual == (String1 == String2);
3982 TheCondState.Ignore = !TheCondState.CondMet;
3987 /// parseDirectiveIfdef
3988 /// ::= .ifdef symbol
3989 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3991 TheCondStack.push_back(TheCondState);
3992 TheCondState.TheCond = AsmCond::IfCond;
3994 if (TheCondState.Ignore) {
3995 eatToEndOfStatement();
3997 if (parseIdentifier(Name))
3998 return TokError("expected identifier after '.ifdef'");
4002 MCSymbol *Sym = getContext().lookupSymbol(Name);
4005 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4007 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4008 TheCondState.Ignore = !TheCondState.CondMet;
4014 /// parseDirectiveElseIf
4015 /// ::= .elseif expression
4016 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4017 if (TheCondState.TheCond != AsmCond::IfCond &&
4018 TheCondState.TheCond != AsmCond::ElseIfCond)
4019 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4021 TheCondState.TheCond = AsmCond::ElseIfCond;
4023 bool LastIgnoreState = false;
4024 if (!TheCondStack.empty())
4025 LastIgnoreState = TheCondStack.back().Ignore;
4026 if (LastIgnoreState || TheCondState.CondMet) {
4027 TheCondState.Ignore = true;
4028 eatToEndOfStatement();
4031 if (parseAbsoluteExpression(ExprValue))
4034 if (getLexer().isNot(AsmToken::EndOfStatement))
4035 return TokError("unexpected token in '.elseif' directive");
4038 TheCondState.CondMet = ExprValue;
4039 TheCondState.Ignore = !TheCondState.CondMet;
4045 /// parseDirectiveElse
4047 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4048 if (getLexer().isNot(AsmToken::EndOfStatement))
4049 return TokError("unexpected token in '.else' directive");
4053 if (TheCondState.TheCond != AsmCond::IfCond &&
4054 TheCondState.TheCond != AsmCond::ElseIfCond)
4055 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4057 TheCondState.TheCond = AsmCond::ElseCond;
4058 bool LastIgnoreState = false;
4059 if (!TheCondStack.empty())
4060 LastIgnoreState = TheCondStack.back().Ignore;
4061 if (LastIgnoreState || TheCondState.CondMet)
4062 TheCondState.Ignore = true;
4064 TheCondState.Ignore = false;
4069 /// parseDirectiveEnd
4071 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4072 if (getLexer().isNot(AsmToken::EndOfStatement))
4073 return TokError("unexpected token in '.end' directive");
4077 while (Lexer.isNot(AsmToken::Eof))
4083 /// parseDirectiveError
4085 /// ::= .error [string]
4086 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4087 if (!TheCondStack.empty()) {
4088 if (TheCondStack.back().Ignore) {
4089 eatToEndOfStatement();
4095 return Error(L, ".err encountered");
4097 StringRef Message = ".error directive invoked in source file";
4098 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4099 if (Lexer.isNot(AsmToken::String)) {
4100 TokError(".error argument must be a string");
4101 eatToEndOfStatement();
4105 Message = getTok().getStringContents();
4113 /// parseDirectiveWarning
4114 /// ::= .warning [string]
4115 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4116 if (!TheCondStack.empty()) {
4117 if (TheCondStack.back().Ignore) {
4118 eatToEndOfStatement();
4123 StringRef Message = ".warning directive invoked in source file";
4124 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4125 if (Lexer.isNot(AsmToken::String)) {
4126 TokError(".warning argument must be a string");
4127 eatToEndOfStatement();
4131 Message = getTok().getStringContents();
4135 Warning(L, Message);
4139 /// parseDirectiveEndIf
4141 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4142 if (getLexer().isNot(AsmToken::EndOfStatement))
4143 return TokError("unexpected token in '.endif' directive");
4147 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4148 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4150 if (!TheCondStack.empty()) {
4151 TheCondState = TheCondStack.back();
4152 TheCondStack.pop_back();
4158 void AsmParser::initializeDirectiveKindMap() {
4159 DirectiveKindMap[".set"] = DK_SET;
4160 DirectiveKindMap[".equ"] = DK_EQU;
4161 DirectiveKindMap[".equiv"] = DK_EQUIV;
4162 DirectiveKindMap[".ascii"] = DK_ASCII;
4163 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4164 DirectiveKindMap[".string"] = DK_STRING;
4165 DirectiveKindMap[".byte"] = DK_BYTE;
4166 DirectiveKindMap[".short"] = DK_SHORT;
4167 DirectiveKindMap[".value"] = DK_VALUE;
4168 DirectiveKindMap[".2byte"] = DK_2BYTE;
4169 DirectiveKindMap[".long"] = DK_LONG;
4170 DirectiveKindMap[".int"] = DK_INT;
4171 DirectiveKindMap[".4byte"] = DK_4BYTE;
4172 DirectiveKindMap[".quad"] = DK_QUAD;
4173 DirectiveKindMap[".8byte"] = DK_8BYTE;
4174 DirectiveKindMap[".octa"] = DK_OCTA;
4175 DirectiveKindMap[".single"] = DK_SINGLE;
4176 DirectiveKindMap[".float"] = DK_FLOAT;
4177 DirectiveKindMap[".double"] = DK_DOUBLE;
4178 DirectiveKindMap[".align"] = DK_ALIGN;
4179 DirectiveKindMap[".align32"] = DK_ALIGN32;
4180 DirectiveKindMap[".balign"] = DK_BALIGN;
4181 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4182 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4183 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4184 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4185 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4186 DirectiveKindMap[".org"] = DK_ORG;
4187 DirectiveKindMap[".fill"] = DK_FILL;
4188 DirectiveKindMap[".zero"] = DK_ZERO;
4189 DirectiveKindMap[".extern"] = DK_EXTERN;
4190 DirectiveKindMap[".globl"] = DK_GLOBL;
4191 DirectiveKindMap[".global"] = DK_GLOBAL;
4192 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4193 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4194 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4195 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4196 DirectiveKindMap[".reference"] = DK_REFERENCE;
4197 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4198 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4199 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4200 DirectiveKindMap[".comm"] = DK_COMM;
4201 DirectiveKindMap[".common"] = DK_COMMON;
4202 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4203 DirectiveKindMap[".abort"] = DK_ABORT;
4204 DirectiveKindMap[".include"] = DK_INCLUDE;
4205 DirectiveKindMap[".incbin"] = DK_INCBIN;
4206 DirectiveKindMap[".code16"] = DK_CODE16;
4207 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4208 DirectiveKindMap[".rept"] = DK_REPT;
4209 DirectiveKindMap[".rep"] = DK_REPT;
4210 DirectiveKindMap[".irp"] = DK_IRP;
4211 DirectiveKindMap[".irpc"] = DK_IRPC;
4212 DirectiveKindMap[".endr"] = DK_ENDR;
4213 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4214 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4215 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4216 DirectiveKindMap[".if"] = DK_IF;
4217 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4218 DirectiveKindMap[".ifge"] = DK_IFGE;
4219 DirectiveKindMap[".ifgt"] = DK_IFGT;
4220 DirectiveKindMap[".ifle"] = DK_IFLE;
4221 DirectiveKindMap[".iflt"] = DK_IFLT;
4222 DirectiveKindMap[".ifne"] = DK_IFNE;
4223 DirectiveKindMap[".ifb"] = DK_IFB;
4224 DirectiveKindMap[".ifnb"] = DK_IFNB;
4225 DirectiveKindMap[".ifc"] = DK_IFC;
4226 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4227 DirectiveKindMap[".ifnc"] = DK_IFNC;
4228 DirectiveKindMap[".ifnes"] = DK_IFNES;
4229 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4230 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4231 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4232 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4233 DirectiveKindMap[".else"] = DK_ELSE;
4234 DirectiveKindMap[".end"] = DK_END;
4235 DirectiveKindMap[".endif"] = DK_ENDIF;
4236 DirectiveKindMap[".skip"] = DK_SKIP;
4237 DirectiveKindMap[".space"] = DK_SPACE;
4238 DirectiveKindMap[".file"] = DK_FILE;
4239 DirectiveKindMap[".line"] = DK_LINE;
4240 DirectiveKindMap[".loc"] = DK_LOC;
4241 DirectiveKindMap[".stabs"] = DK_STABS;
4242 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4243 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4244 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4245 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4246 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4247 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4248 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4249 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4250 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4251 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4252 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4253 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4254 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4255 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4256 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4257 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4258 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4259 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4260 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4261 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4262 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4263 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4264 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4265 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4266 DirectiveKindMap[".macro"] = DK_MACRO;
4267 DirectiveKindMap[".exitm"] = DK_EXITM;
4268 DirectiveKindMap[".endm"] = DK_ENDM;
4269 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4270 DirectiveKindMap[".purgem"] = DK_PURGEM;
4271 DirectiveKindMap[".err"] = DK_ERR;
4272 DirectiveKindMap[".error"] = DK_ERROR;
4273 DirectiveKindMap[".warning"] = DK_WARNING;
4276 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4277 AsmToken EndToken, StartToken = getTok();
4279 unsigned NestLevel = 0;
4281 // Check whether we have reached the end of the file.
4282 if (getLexer().is(AsmToken::Eof)) {
4283 Error(DirectiveLoc, "no matching '.endr' in definition");
4287 if (Lexer.is(AsmToken::Identifier) &&
4288 (getTok().getIdentifier() == ".rept")) {
4292 // Otherwise, check whether we have reached the .endr.
4293 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4294 if (NestLevel == 0) {
4295 EndToken = getTok();
4297 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4298 TokError("unexpected token in '.endr' directive");
4306 // Otherwise, scan till the end of the statement.
4307 eatToEndOfStatement();
4310 const char *BodyStart = StartToken.getLoc().getPointer();
4311 const char *BodyEnd = EndToken.getLoc().getPointer();
4312 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4314 // We Are Anonymous.
4315 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4316 return &MacroLikeBodies.back();
4319 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4320 raw_svector_ostream &OS) {
4323 std::unique_ptr<MemoryBuffer> Instantiation =
4324 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4326 // Create the macro instantiation object and add to the current macro
4327 // instantiation stack.
4328 MacroInstantiation *MI = new MacroInstantiation(
4329 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4330 ActiveMacros.push_back(MI);
4332 // Jump to the macro instantiation and prime the lexer.
4333 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4334 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4338 /// parseDirectiveRept
4339 /// ::= .rep | .rept count
4340 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4341 const MCExpr *CountExpr;
4342 SMLoc CountLoc = getTok().getLoc();
4343 if (parseExpression(CountExpr))
4347 if (!CountExpr->evaluateAsAbsolute(Count)) {
4348 eatToEndOfStatement();
4349 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4353 return Error(CountLoc, "Count is negative");
4355 if (Lexer.isNot(AsmToken::EndOfStatement))
4356 return TokError("unexpected token in '" + Dir + "' directive");
4358 // Eat the end of statement.
4361 // Lex the rept definition.
4362 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4366 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4367 // to hold the macro body with substitutions.
4368 SmallString<256> Buf;
4369 raw_svector_ostream OS(Buf);
4371 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4372 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4375 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4380 /// parseDirectiveIrp
4381 /// ::= .irp symbol,values
4382 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4383 MCAsmMacroParameter Parameter;
4385 if (parseIdentifier(Parameter.Name))
4386 return TokError("expected identifier in '.irp' directive");
4388 if (Lexer.isNot(AsmToken::Comma))
4389 return TokError("expected comma in '.irp' directive");
4393 MCAsmMacroArguments A;
4394 if (parseMacroArguments(nullptr, A))
4397 // Eat the end of statement.
4400 // Lex the irp definition.
4401 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4405 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4406 // to hold the macro body with substitutions.
4407 SmallString<256> Buf;
4408 raw_svector_ostream OS(Buf);
4410 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4411 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4412 // This is undocumented, but GAS seems to support it.
4413 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4417 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4422 /// parseDirectiveIrpc
4423 /// ::= .irpc symbol,values
4424 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4425 MCAsmMacroParameter Parameter;
4427 if (parseIdentifier(Parameter.Name))
4428 return TokError("expected identifier in '.irpc' directive");
4430 if (Lexer.isNot(AsmToken::Comma))
4431 return TokError("expected comma in '.irpc' directive");
4435 MCAsmMacroArguments A;
4436 if (parseMacroArguments(nullptr, A))
4439 if (A.size() != 1 || A.front().size() != 1)
4440 return TokError("unexpected token in '.irpc' directive");
4442 // Eat the end of statement.
4445 // Lex the irpc definition.
4446 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4450 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4451 // to hold the macro body with substitutions.
4452 SmallString<256> Buf;
4453 raw_svector_ostream OS(Buf);
4455 StringRef Values = A.front().front().getString();
4456 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4457 MCAsmMacroArgument Arg;
4458 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4460 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4461 // This is undocumented, but GAS seems to support it.
4462 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4466 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4471 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4472 if (ActiveMacros.empty())
4473 return TokError("unmatched '.endr' directive");
4475 // The only .repl that should get here are the ones created by
4476 // instantiateMacroLikeBody.
4477 assert(getLexer().is(AsmToken::EndOfStatement));
4483 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4485 const MCExpr *Value;
4486 SMLoc ExprLoc = getLexer().getLoc();
4487 if (parseExpression(Value))
4489 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4491 return Error(ExprLoc, "unexpected expression in _emit");
4492 uint64_t IntValue = MCE->getValue();
4493 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4494 return Error(ExprLoc, "literal value out of range for directive");
4496 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4500 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4501 const MCExpr *Value;
4502 SMLoc ExprLoc = getLexer().getLoc();
4503 if (parseExpression(Value))
4505 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4507 return Error(ExprLoc, "unexpected expression in align");
4508 uint64_t IntValue = MCE->getValue();
4509 if (!isPowerOf2_64(IntValue))
4510 return Error(ExprLoc, "literal value not a power of two greater then zero");
4512 Info.AsmRewrites->push_back(
4513 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4517 // We are comparing pointers, but the pointers are relative to a single string.
4518 // Thus, this should always be deterministic.
4519 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4520 const AsmRewrite *AsmRewriteB) {
4521 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4523 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4526 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4527 // rewrite to the same location. Make sure the SizeDirective rewrite is
4528 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4529 // ensures the sort algorithm is stable.
4530 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4531 AsmRewritePrecedence[AsmRewriteB->Kind])
4534 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4535 AsmRewritePrecedence[AsmRewriteB->Kind])
4537 llvm_unreachable("Unstable rewrite sort.");
4540 bool AsmParser::parseMSInlineAsm(
4541 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4542 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4543 SmallVectorImpl<std::string> &Constraints,
4544 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4545 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4546 SmallVector<void *, 4> InputDecls;
4547 SmallVector<void *, 4> OutputDecls;
4548 SmallVector<bool, 4> InputDeclsAddressOf;
4549 SmallVector<bool, 4> OutputDeclsAddressOf;
4550 SmallVector<std::string, 4> InputConstraints;
4551 SmallVector<std::string, 4> OutputConstraints;
4552 SmallVector<unsigned, 4> ClobberRegs;
4554 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4559 // While we have input, parse each statement.
4560 unsigned InputIdx = 0;
4561 unsigned OutputIdx = 0;
4562 while (getLexer().isNot(AsmToken::Eof)) {
4563 ParseStatementInfo Info(&AsmStrRewrites);
4564 if (parseStatement(Info, &SI))
4567 if (Info.ParseError)
4570 if (Info.Opcode == ~0U)
4573 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4575 // Build the list of clobbers, outputs and inputs.
4576 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4577 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4580 if (Operand.isImm())
4583 // Register operand.
4584 if (Operand.isReg() && !Operand.needAddressOf() &&
4585 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4586 unsigned NumDefs = Desc.getNumDefs();
4588 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4589 ClobberRegs.push_back(Operand.getReg());
4593 // Expr/Input or Output.
4594 StringRef SymName = Operand.getSymName();
4595 if (SymName.empty())
4598 void *OpDecl = Operand.getOpDecl();
4602 bool isOutput = (i == 1) && Desc.mayStore();
4603 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4606 OutputDecls.push_back(OpDecl);
4607 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4608 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4609 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4611 InputDecls.push_back(OpDecl);
4612 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4613 InputConstraints.push_back(Operand.getConstraint().str());
4614 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4618 // Consider implicit defs to be clobbers. Think of cpuid and push.
4619 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4620 Desc.getNumImplicitDefs());
4621 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4624 // Set the number of Outputs and Inputs.
4625 NumOutputs = OutputDecls.size();
4626 NumInputs = InputDecls.size();
4628 // Set the unique clobbers.
4629 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4630 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4632 Clobbers.assign(ClobberRegs.size(), std::string());
4633 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4634 raw_string_ostream OS(Clobbers[I]);
4635 IP->printRegName(OS, ClobberRegs[I]);
4638 // Merge the various outputs and inputs. Output are expected first.
4639 if (NumOutputs || NumInputs) {
4640 unsigned NumExprs = NumOutputs + NumInputs;
4641 OpDecls.resize(NumExprs);
4642 Constraints.resize(NumExprs);
4643 for (unsigned i = 0; i < NumOutputs; ++i) {
4644 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4645 Constraints[i] = OutputConstraints[i];
4647 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4648 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4649 Constraints[j] = InputConstraints[i];
4653 // Build the IR assembly string.
4654 std::string AsmStringIR;
4655 raw_string_ostream OS(AsmStringIR);
4656 StringRef ASMString =
4657 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4658 const char *AsmStart = ASMString.begin();
4659 const char *AsmEnd = ASMString.end();
4660 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4661 for (const AsmRewrite &AR : AsmStrRewrites) {
4662 AsmRewriteKind Kind = AR.Kind;
4663 if (Kind == AOK_Delete)
4666 const char *Loc = AR.Loc.getPointer();
4667 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4669 // Emit everything up to the immediate/expression.
4670 if (unsigned Len = Loc - AsmStart)
4671 OS << StringRef(AsmStart, Len);
4673 // Skip the original expression.
4674 if (Kind == AOK_Skip) {
4675 AsmStart = Loc + AR.Len;
4679 unsigned AdditionalSkip = 0;
4680 // Rewrite expressions in $N notation.
4685 OS << "$$" << AR.Val;
4691 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4694 OS << '$' << InputIdx++;
4697 OS << '$' << OutputIdx++;
4699 case AOK_SizeDirective:
4702 case 8: OS << "byte ptr "; break;
4703 case 16: OS << "word ptr "; break;
4704 case 32: OS << "dword ptr "; break;
4705 case 64: OS << "qword ptr "; break;
4706 case 80: OS << "xword ptr "; break;
4707 case 128: OS << "xmmword ptr "; break;
4708 case 256: OS << "ymmword ptr "; break;
4715 unsigned Val = AR.Val;
4716 OS << ".align " << Val;
4718 // Skip the original immediate.
4719 assert(Val < 10 && "Expected alignment less then 2^10.");
4720 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4723 case AOK_DotOperator:
4724 // Insert the dot if the user omitted it.
4726 if (AsmStringIR.back() != '.')
4732 // Skip the original expression.
4733 AsmStart = Loc + AR.Len + AdditionalSkip;
4736 // Emit the remainder of the asm string.
4737 if (AsmStart != AsmEnd)
4738 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4740 AsmString = OS.str();
4745 namespace MCParserUtils {
4747 /// Returns whether the given symbol is used anywhere in the given expression,
4748 /// or subexpressions.
4749 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4750 switch (Value->getKind()) {
4751 case MCExpr::Binary: {
4752 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4753 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4754 isSymbolUsedInExpression(Sym, BE->getRHS());
4756 case MCExpr::Target:
4757 case MCExpr::Constant:
4759 case MCExpr::SymbolRef: {
4761 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4763 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4767 return isSymbolUsedInExpression(
4768 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4771 llvm_unreachable("Unknown expr kind!");
4774 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4775 MCAsmParser &Parser, MCSymbol *&Sym,
4776 const MCExpr *&Value) {
4777 MCAsmLexer &Lexer = Parser.getLexer();
4779 // FIXME: Use better location, we should use proper tokens.
4780 SMLoc EqualLoc = Lexer.getLoc();
4782 if (Parser.parseExpression(Value)) {
4783 Parser.TokError("missing expression");
4784 Parser.eatToEndOfStatement();
4788 // Note: we don't count b as used in "a = b". This is to allow
4792 if (Lexer.isNot(AsmToken::EndOfStatement))
4793 return Parser.TokError("unexpected token in assignment");
4795 // Eat the end of statement marker.
4798 // Validate that the LHS is allowed to be a variable (either it has not been
4799 // used as a symbol, or it is an absolute symbol).
4800 Sym = Parser.getContext().lookupSymbol(Name);
4802 // Diagnose assignment to a label.
4804 // FIXME: Diagnostics. Note the location of the definition as a label.
4805 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4806 if (isSymbolUsedInExpression(Sym, Value))
4807 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4808 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4809 ; // Allow redefinitions of undefined symbols only used in directives.
4810 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4811 ; // Allow redefinitions of variables that haven't yet been used.
4812 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4813 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4814 else if (!Sym->isVariable())
4815 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4816 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4817 return Parser.Error(EqualLoc,
4818 "invalid reassignment of non-absolute variable '" +
4821 // Don't count these checks as uses.
4822 Sym->setUsed(false);
4823 } else if (Name == ".") {
4824 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4825 Parser.Error(EqualLoc, "expected absolute expression");
4826 Parser.eatToEndOfStatement();
4831 Sym = Parser.getContext().getOrCreateSymbol(Name);
4833 Sym->setRedefinable(allow_redef);
4838 } // namespace MCParserUtils
4841 /// \brief Create an MCAsmParser instance.
4842 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4843 MCStreamer &Out, const MCAsmInfo &MAI) {
4844 return new AsmParser(SM, C, Out, MAI);