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(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 for (const auto &TableEntry : getContext().getSymbols()) {
685 MCSymbol *Sym = TableEntry.getValue();
686 // Variable symbols may not be marked as defined, so check those
687 // explicitly. If we know it's a variable, we have a definition for
688 // the purposes of this check.
689 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
690 // FIXME: We would really like to refer back to where the symbol was
691 // first referenced for a source location. We need to add something
692 // to track that. Currently, we just point to the end of the file.
693 return Error(getLexer().getLoc(), "assembler local symbol '" +
694 Sym->getName() + "' not defined");
698 // Finalize the output stream if there are no errors and if the client wants
700 if (!HadError && !NoFinalize)
706 void AsmParser::checkForValidSection() {
707 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
708 TokError("expected section directive before assembly directive");
709 Out.InitSections(false);
713 /// \brief Throw away the rest of the line for testing purposes.
714 void AsmParser::eatToEndOfStatement() {
715 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
719 if (Lexer.is(AsmToken::EndOfStatement))
723 StringRef AsmParser::parseStringToEndOfStatement() {
724 const char *Start = getTok().getLoc().getPointer();
726 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
729 const char *End = getTok().getLoc().getPointer();
730 return StringRef(Start, End - Start);
733 StringRef AsmParser::parseStringToComma() {
734 const char *Start = getTok().getLoc().getPointer();
736 while (Lexer.isNot(AsmToken::EndOfStatement) &&
737 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
740 const char *End = getTok().getLoc().getPointer();
741 return StringRef(Start, End - Start);
744 /// \brief Parse a paren expression and return it.
745 /// NOTE: This assumes the leading '(' has already been consumed.
747 /// parenexpr ::= expr)
749 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
750 if (parseExpression(Res))
752 if (Lexer.isNot(AsmToken::RParen))
753 return TokError("expected ')' in parentheses expression");
754 EndLoc = Lexer.getTok().getEndLoc();
759 /// \brief Parse a bracket expression and return it.
760 /// NOTE: This assumes the leading '[' has already been consumed.
762 /// bracketexpr ::= expr]
764 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
765 if (parseExpression(Res))
767 if (Lexer.isNot(AsmToken::RBrac))
768 return TokError("expected ']' in brackets expression");
769 EndLoc = Lexer.getTok().getEndLoc();
774 /// \brief Parse a primary expression and return it.
775 /// primaryexpr ::= (parenexpr
776 /// primaryexpr ::= symbol
777 /// primaryexpr ::= number
778 /// primaryexpr ::= '.'
779 /// primaryexpr ::= ~,+,- primaryexpr
780 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
781 SMLoc FirstTokenLoc = getLexer().getLoc();
782 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
783 switch (FirstTokenKind) {
785 return TokError("unknown token in expression");
786 // If we have an error assume that we've already handled it.
787 case AsmToken::Error:
789 case AsmToken::Exclaim:
790 Lex(); // Eat the operator.
791 if (parsePrimaryExpr(Res, EndLoc))
793 Res = MCUnaryExpr::createLNot(Res, getContext());
795 case AsmToken::Dollar:
797 case AsmToken::String:
798 case AsmToken::Identifier: {
799 StringRef Identifier;
800 if (parseIdentifier(Identifier)) {
801 if (FirstTokenKind == AsmToken::Dollar) {
802 if (Lexer.getMAI().getDollarIsPC()) {
803 // This is a '$' reference, which references the current PC. Emit a
804 // temporary label to the streamer and refer to it.
805 MCSymbol *Sym = Ctx.createTempSymbol();
807 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
809 EndLoc = FirstTokenLoc;
812 return Error(FirstTokenLoc, "invalid token in expression");
815 // Parse symbol variant
816 std::pair<StringRef, StringRef> Split;
817 if (!MAI.useParensForSymbolVariant()) {
818 if (FirstTokenKind == AsmToken::String) {
819 if (Lexer.is(AsmToken::At)) {
820 Lexer.Lex(); // eat @
821 SMLoc AtLoc = getLexer().getLoc();
823 if (parseIdentifier(VName))
824 return Error(AtLoc, "expected symbol variant after '@'");
826 Split = std::make_pair(Identifier, VName);
829 Split = Identifier.split('@');
831 } else if (Lexer.is(AsmToken::LParen)) {
832 Lexer.Lex(); // eat (
834 parseIdentifier(VName);
835 if (Lexer.isNot(AsmToken::RParen)) {
836 return Error(Lexer.getTok().getLoc(),
837 "unexpected token in variant, expected ')'");
839 Lexer.Lex(); // eat )
840 Split = std::make_pair(Identifier, VName);
843 EndLoc = SMLoc::getFromPointer(Identifier.end());
845 // This is a symbol reference.
846 StringRef SymbolName = Identifier;
847 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
849 // Lookup the symbol variant if used.
850 if (Split.second.size()) {
851 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
852 if (Variant != MCSymbolRefExpr::VK_Invalid) {
853 SymbolName = Split.first;
854 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
855 Variant = MCSymbolRefExpr::VK_None;
857 return Error(SMLoc::getFromPointer(Split.second.begin()),
858 "invalid variant '" + Split.second + "'");
862 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
864 // If this is an absolute variable reference, substitute it now to preserve
865 // semantics in the face of reassignment.
866 if (Sym->isVariable() &&
867 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
869 return Error(EndLoc, "unexpected modifier on variable reference");
871 Res = Sym->getVariableValue(/*SetUsed*/ false);
875 // Otherwise create a symbol ref.
876 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
879 case AsmToken::BigNum:
880 return TokError("literal value out of range for directive");
881 case AsmToken::Integer: {
882 SMLoc Loc = getTok().getLoc();
883 int64_t IntVal = getTok().getIntVal();
884 Res = MCConstantExpr::create(IntVal, getContext());
885 EndLoc = Lexer.getTok().getEndLoc();
887 // Look for 'b' or 'f' following an Integer as a directional label
888 if (Lexer.getKind() == AsmToken::Identifier) {
889 StringRef IDVal = getTok().getString();
890 // Lookup the symbol variant if used.
891 std::pair<StringRef, StringRef> Split = IDVal.split('@');
892 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
893 if (Split.first.size() != IDVal.size()) {
894 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
895 if (Variant == MCSymbolRefExpr::VK_Invalid)
896 return TokError("invalid variant '" + Split.second + "'");
899 if (IDVal == "f" || IDVal == "b") {
901 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
902 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
903 if (IDVal == "b" && Sym->isUndefined())
904 return Error(Loc, "invalid reference to undefined symbol");
905 EndLoc = Lexer.getTok().getEndLoc();
906 Lex(); // Eat identifier.
911 case AsmToken::Real: {
912 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
913 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
914 Res = MCConstantExpr::create(IntVal, getContext());
915 EndLoc = Lexer.getTok().getEndLoc();
919 case AsmToken::Dot: {
920 // This is a '.' reference, which references the current PC. Emit a
921 // temporary label to the streamer and refer to it.
922 MCSymbol *Sym = Ctx.createTempSymbol();
924 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
925 EndLoc = Lexer.getTok().getEndLoc();
926 Lex(); // Eat identifier.
929 case AsmToken::LParen:
930 Lex(); // Eat the '('.
931 return parseParenExpr(Res, EndLoc);
932 case AsmToken::LBrac:
933 if (!PlatformParser->HasBracketExpressions())
934 return TokError("brackets expression not supported on this target");
935 Lex(); // Eat the '['.
936 return parseBracketExpr(Res, EndLoc);
937 case AsmToken::Minus:
938 Lex(); // Eat the operator.
939 if (parsePrimaryExpr(Res, EndLoc))
941 Res = MCUnaryExpr::createMinus(Res, getContext());
944 Lex(); // Eat the operator.
945 if (parsePrimaryExpr(Res, EndLoc))
947 Res = MCUnaryExpr::createPlus(Res, getContext());
949 case AsmToken::Tilde:
950 Lex(); // Eat the operator.
951 if (parsePrimaryExpr(Res, EndLoc))
953 Res = MCUnaryExpr::createNot(Res, getContext());
958 bool AsmParser::parseExpression(const MCExpr *&Res) {
960 return parseExpression(Res, EndLoc);
964 AsmParser::applyModifierToExpr(const MCExpr *E,
965 MCSymbolRefExpr::VariantKind Variant) {
966 // Ask the target implementation about this expression first.
967 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
970 // Recurse over the given expression, rebuilding it to apply the given variant
971 // if there is exactly one symbol.
972 switch (E->getKind()) {
974 case MCExpr::Constant:
977 case MCExpr::SymbolRef: {
978 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
980 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
981 TokError("invalid variant on expression '" + getTok().getIdentifier() +
982 "' (already modified)");
986 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
989 case MCExpr::Unary: {
990 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
991 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
994 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
997 case MCExpr::Binary: {
998 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
999 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1000 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1010 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1014 llvm_unreachable("Invalid expression kind!");
1017 /// \brief Parse an expression and return it.
1019 /// expr ::= expr &&,|| expr -> lowest.
1020 /// expr ::= expr |,^,&,! expr
1021 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1022 /// expr ::= expr <<,>> expr
1023 /// expr ::= expr +,- expr
1024 /// expr ::= expr *,/,% expr -> highest.
1025 /// expr ::= primaryexpr
1027 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1028 // Parse the expression.
1030 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1033 // As a special case, we support 'a op b @ modifier' by rewriting the
1034 // expression to include the modifier. This is inefficient, but in general we
1035 // expect users to use 'a@modifier op b'.
1036 if (Lexer.getKind() == AsmToken::At) {
1039 if (Lexer.isNot(AsmToken::Identifier))
1040 return TokError("unexpected symbol modifier following '@'");
1042 MCSymbolRefExpr::VariantKind Variant =
1043 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1044 if (Variant == MCSymbolRefExpr::VK_Invalid)
1045 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1047 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1049 return TokError("invalid modifier '" + getTok().getIdentifier() +
1050 "' (no symbols present)");
1057 // Try to constant fold it up front, if possible.
1059 if (Res->evaluateAsAbsolute(Value))
1060 Res = MCConstantExpr::create(Value, getContext());
1065 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1067 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1070 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1072 if (parseParenExpr(Res, EndLoc))
1075 for (; ParenDepth > 0; --ParenDepth) {
1076 if (parseBinOpRHS(1, Res, EndLoc))
1079 // We don't Lex() the last RParen.
1080 // This is the same behavior as parseParenExpression().
1081 if (ParenDepth - 1 > 0) {
1082 if (Lexer.isNot(AsmToken::RParen))
1083 return TokError("expected ')' in parentheses expression");
1084 EndLoc = Lexer.getTok().getEndLoc();
1091 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1094 SMLoc StartLoc = Lexer.getLoc();
1095 if (parseExpression(Expr))
1098 if (!Expr->evaluateAsAbsolute(Res))
1099 return Error(StartLoc, "expected absolute expression");
1104 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1105 MCBinaryExpr::Opcode &Kind,
1106 bool ShouldUseLogicalShr) {
1109 return 0; // not a binop.
1111 // Lowest Precedence: &&, ||
1112 case AsmToken::AmpAmp:
1113 Kind = MCBinaryExpr::LAnd;
1115 case AsmToken::PipePipe:
1116 Kind = MCBinaryExpr::LOr;
1119 // Low Precedence: |, &, ^
1121 // FIXME: gas seems to support '!' as an infix operator?
1122 case AsmToken::Pipe:
1123 Kind = MCBinaryExpr::Or;
1125 case AsmToken::Caret:
1126 Kind = MCBinaryExpr::Xor;
1129 Kind = MCBinaryExpr::And;
1132 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1133 case AsmToken::EqualEqual:
1134 Kind = MCBinaryExpr::EQ;
1136 case AsmToken::ExclaimEqual:
1137 case AsmToken::LessGreater:
1138 Kind = MCBinaryExpr::NE;
1140 case AsmToken::Less:
1141 Kind = MCBinaryExpr::LT;
1143 case AsmToken::LessEqual:
1144 Kind = MCBinaryExpr::LTE;
1146 case AsmToken::Greater:
1147 Kind = MCBinaryExpr::GT;
1149 case AsmToken::GreaterEqual:
1150 Kind = MCBinaryExpr::GTE;
1153 // Intermediate Precedence: <<, >>
1154 case AsmToken::LessLess:
1155 Kind = MCBinaryExpr::Shl;
1157 case AsmToken::GreaterGreater:
1158 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1161 // High Intermediate Precedence: +, -
1162 case AsmToken::Plus:
1163 Kind = MCBinaryExpr::Add;
1165 case AsmToken::Minus:
1166 Kind = MCBinaryExpr::Sub;
1169 // Highest Precedence: *, /, %
1170 case AsmToken::Star:
1171 Kind = MCBinaryExpr::Mul;
1173 case AsmToken::Slash:
1174 Kind = MCBinaryExpr::Div;
1176 case AsmToken::Percent:
1177 Kind = MCBinaryExpr::Mod;
1182 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1183 MCBinaryExpr::Opcode &Kind,
1184 bool ShouldUseLogicalShr) {
1187 return 0; // not a binop.
1189 // Lowest Precedence: &&, ||
1190 case AsmToken::AmpAmp:
1191 Kind = MCBinaryExpr::LAnd;
1193 case AsmToken::PipePipe:
1194 Kind = MCBinaryExpr::LOr;
1197 // Low Precedence: ==, !=, <>, <, <=, >, >=
1198 case AsmToken::EqualEqual:
1199 Kind = MCBinaryExpr::EQ;
1201 case AsmToken::ExclaimEqual:
1202 case AsmToken::LessGreater:
1203 Kind = MCBinaryExpr::NE;
1205 case AsmToken::Less:
1206 Kind = MCBinaryExpr::LT;
1208 case AsmToken::LessEqual:
1209 Kind = MCBinaryExpr::LTE;
1211 case AsmToken::Greater:
1212 Kind = MCBinaryExpr::GT;
1214 case AsmToken::GreaterEqual:
1215 Kind = MCBinaryExpr::GTE;
1218 // Low Intermediate Precedence: +, -
1219 case AsmToken::Plus:
1220 Kind = MCBinaryExpr::Add;
1222 case AsmToken::Minus:
1223 Kind = MCBinaryExpr::Sub;
1226 // High Intermediate Precedence: |, &, ^
1228 // FIXME: gas seems to support '!' as an infix operator?
1229 case AsmToken::Pipe:
1230 Kind = MCBinaryExpr::Or;
1232 case AsmToken::Caret:
1233 Kind = MCBinaryExpr::Xor;
1236 Kind = MCBinaryExpr::And;
1239 // Highest Precedence: *, /, %, <<, >>
1240 case AsmToken::Star:
1241 Kind = MCBinaryExpr::Mul;
1243 case AsmToken::Slash:
1244 Kind = MCBinaryExpr::Div;
1246 case AsmToken::Percent:
1247 Kind = MCBinaryExpr::Mod;
1249 case AsmToken::LessLess:
1250 Kind = MCBinaryExpr::Shl;
1252 case AsmToken::GreaterGreater:
1253 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1258 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1259 MCBinaryExpr::Opcode &Kind) {
1260 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1261 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1262 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1265 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1266 /// Res contains the LHS of the expression on input.
1267 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1270 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1271 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1273 // If the next token is lower precedence than we are allowed to eat, return
1274 // successfully with what we ate already.
1275 if (TokPrec < Precedence)
1280 // Eat the next primary expression.
1282 if (parsePrimaryExpr(RHS, EndLoc))
1285 // If BinOp binds less tightly with RHS than the operator after RHS, let
1286 // the pending operator take RHS as its LHS.
1287 MCBinaryExpr::Opcode Dummy;
1288 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1289 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1292 // Merge LHS and RHS according to operator.
1293 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1298 /// ::= EndOfStatement
1299 /// ::= Label* Directive ...Operands... EndOfStatement
1300 /// ::= Label* Identifier OperandList* EndOfStatement
1301 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1302 MCAsmParserSemaCallback *SI) {
1303 if (Lexer.is(AsmToken::EndOfStatement)) {
1309 // Statements always start with an identifier or are a full line comment.
1310 AsmToken ID = getTok();
1311 SMLoc IDLoc = ID.getLoc();
1313 int64_t LocalLabelVal = -1;
1314 // A full line comment is a '#' as the first token.
1315 if (Lexer.is(AsmToken::Hash))
1316 return parseCppHashLineFilenameComment(IDLoc);
1318 // Allow an integer followed by a ':' as a directional local label.
1319 if (Lexer.is(AsmToken::Integer)) {
1320 LocalLabelVal = getTok().getIntVal();
1321 if (LocalLabelVal < 0) {
1322 if (!TheCondState.Ignore)
1323 return TokError("unexpected token at start of statement");
1326 IDVal = getTok().getString();
1327 Lex(); // Consume the integer token to be used as an identifier token.
1328 if (Lexer.getKind() != AsmToken::Colon) {
1329 if (!TheCondState.Ignore)
1330 return TokError("unexpected token at start of statement");
1333 } else if (Lexer.is(AsmToken::Dot)) {
1334 // Treat '.' as a valid identifier in this context.
1337 } else if (parseIdentifier(IDVal)) {
1338 if (!TheCondState.Ignore)
1339 return TokError("unexpected token at start of statement");
1343 // Handle conditional assembly here before checking for skipping. We
1344 // have to do this so that .endif isn't skipped in a ".if 0" block for
1346 StringMap<DirectiveKind>::const_iterator DirKindIt =
1347 DirectiveKindMap.find(IDVal);
1348 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1350 : DirKindIt->getValue();
1361 return parseDirectiveIf(IDLoc, DirKind);
1363 return parseDirectiveIfb(IDLoc, true);
1365 return parseDirectiveIfb(IDLoc, false);
1367 return parseDirectiveIfc(IDLoc, true);
1369 return parseDirectiveIfeqs(IDLoc, true);
1371 return parseDirectiveIfc(IDLoc, false);
1373 return parseDirectiveIfeqs(IDLoc, false);
1375 return parseDirectiveIfdef(IDLoc, true);
1378 return parseDirectiveIfdef(IDLoc, false);
1380 return parseDirectiveElseIf(IDLoc);
1382 return parseDirectiveElse(IDLoc);
1384 return parseDirectiveEndIf(IDLoc);
1387 // Ignore the statement if in the middle of inactive conditional
1389 if (TheCondState.Ignore) {
1390 eatToEndOfStatement();
1394 // FIXME: Recurse on local labels?
1396 // See what kind of statement we have.
1397 switch (Lexer.getKind()) {
1398 case AsmToken::Colon: {
1399 checkForValidSection();
1401 // identifier ':' -> Label.
1404 // Diagnose attempt to use '.' as a label.
1406 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1408 // Diagnose attempt to use a variable as a label.
1410 // FIXME: Diagnostics. Note the location of the definition as a label.
1411 // FIXME: This doesn't diagnose assignment to a symbol which has been
1412 // implicitly marked as external.
1414 if (LocalLabelVal == -1) {
1415 if (ParsingInlineAsm && SI) {
1416 StringRef RewrittenLabel =
1417 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1418 assert(RewrittenLabel.size() &&
1419 "We should have an internal name here.");
1420 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1422 IDVal = RewrittenLabel;
1424 Sym = getContext().getOrCreateSymbol(IDVal);
1426 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1428 Sym->redefineIfPossible();
1430 if (!Sym->isUndefined() || Sym->isVariable())
1431 return Error(IDLoc, "invalid symbol redefinition");
1434 if (!ParsingInlineAsm)
1437 // If we are generating dwarf for assembly source files then gather the
1438 // info to make a dwarf label entry for this label if needed.
1439 if (getContext().getGenDwarfForAssembly())
1440 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1443 getTargetParser().onLabelParsed(Sym);
1445 // Consume any end of statement token, if present, to avoid spurious
1446 // AddBlankLine calls().
1447 if (Lexer.is(AsmToken::EndOfStatement)) {
1449 if (Lexer.is(AsmToken::Eof))
1456 case AsmToken::Equal:
1457 // identifier '=' ... -> assignment statement
1460 return parseAssignment(IDVal, true);
1462 default: // Normal instruction or directive.
1466 // If macros are enabled, check to see if this is a macro instantiation.
1467 if (areMacrosEnabled())
1468 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1469 return handleMacroEntry(M, IDLoc);
1472 // Otherwise, we have a normal instruction or directive.
1474 // Directives start with "."
1475 if (IDVal[0] == '.' && IDVal != ".") {
1476 // There are several entities interested in parsing directives:
1478 // 1. The target-specific assembly parser. Some directives are target
1479 // specific or may potentially behave differently on certain targets.
1480 // 2. Asm parser extensions. For example, platform-specific parsers
1481 // (like the ELF parser) register themselves as extensions.
1482 // 3. The generic directive parser implemented by this class. These are
1483 // all the directives that behave in a target and platform independent
1484 // manner, or at least have a default behavior that's shared between
1485 // all targets and platforms.
1487 // First query the target-specific parser. It will return 'true' if it
1488 // isn't interested in this directive.
1489 if (!getTargetParser().ParseDirective(ID))
1492 // Next, check the extension directive map to see if any extension has
1493 // registered itself to parse this directive.
1494 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1495 ExtensionDirectiveMap.lookup(IDVal);
1497 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1499 // Finally, if no one else is interested in this directive, it must be
1500 // generic and familiar to this class.
1506 return parseDirectiveSet(IDVal, true);
1508 return parseDirectiveSet(IDVal, false);
1510 return parseDirectiveAscii(IDVal, false);
1513 return parseDirectiveAscii(IDVal, true);
1515 return parseDirectiveValue(1);
1519 return parseDirectiveValue(2);
1523 return parseDirectiveValue(4);
1526 return parseDirectiveValue(8);
1528 return parseDirectiveOctaValue();
1531 return parseDirectiveRealValue(APFloat::IEEEsingle);
1533 return parseDirectiveRealValue(APFloat::IEEEdouble);
1535 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1536 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1539 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1540 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1543 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1545 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1547 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1549 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1551 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1553 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1555 return parseDirectiveOrg();
1557 return parseDirectiveFill();
1559 return parseDirectiveZero();
1561 eatToEndOfStatement(); // .extern is the default, ignore it.
1565 return parseDirectiveSymbolAttribute(MCSA_Global);
1566 case DK_LAZY_REFERENCE:
1567 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1568 case DK_NO_DEAD_STRIP:
1569 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1570 case DK_SYMBOL_RESOLVER:
1571 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1572 case DK_PRIVATE_EXTERN:
1573 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1575 return parseDirectiveSymbolAttribute(MCSA_Reference);
1576 case DK_WEAK_DEFINITION:
1577 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1578 case DK_WEAK_REFERENCE:
1579 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1580 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1581 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1584 return parseDirectiveComm(/*IsLocal=*/false);
1586 return parseDirectiveComm(/*IsLocal=*/true);
1588 return parseDirectiveAbort();
1590 return parseDirectiveInclude();
1592 return parseDirectiveIncbin();
1595 return TokError(Twine(IDVal) + " not supported yet");
1597 return parseDirectiveRept(IDLoc, IDVal);
1599 return parseDirectiveIrp(IDLoc);
1601 return parseDirectiveIrpc(IDLoc);
1603 return parseDirectiveEndr(IDLoc);
1604 case DK_BUNDLE_ALIGN_MODE:
1605 return parseDirectiveBundleAlignMode();
1606 case DK_BUNDLE_LOCK:
1607 return parseDirectiveBundleLock();
1608 case DK_BUNDLE_UNLOCK:
1609 return parseDirectiveBundleUnlock();
1611 return parseDirectiveLEB128(true);
1613 return parseDirectiveLEB128(false);
1616 return parseDirectiveSpace(IDVal);
1618 return parseDirectiveFile(IDLoc);
1620 return parseDirectiveLine();
1622 return parseDirectiveLoc();
1624 return parseDirectiveStabs();
1625 case DK_CFI_SECTIONS:
1626 return parseDirectiveCFISections();
1627 case DK_CFI_STARTPROC:
1628 return parseDirectiveCFIStartProc();
1629 case DK_CFI_ENDPROC:
1630 return parseDirectiveCFIEndProc();
1631 case DK_CFI_DEF_CFA:
1632 return parseDirectiveCFIDefCfa(IDLoc);
1633 case DK_CFI_DEF_CFA_OFFSET:
1634 return parseDirectiveCFIDefCfaOffset();
1635 case DK_CFI_ADJUST_CFA_OFFSET:
1636 return parseDirectiveCFIAdjustCfaOffset();
1637 case DK_CFI_DEF_CFA_REGISTER:
1638 return parseDirectiveCFIDefCfaRegister(IDLoc);
1640 return parseDirectiveCFIOffset(IDLoc);
1641 case DK_CFI_REL_OFFSET:
1642 return parseDirectiveCFIRelOffset(IDLoc);
1643 case DK_CFI_PERSONALITY:
1644 return parseDirectiveCFIPersonalityOrLsda(true);
1646 return parseDirectiveCFIPersonalityOrLsda(false);
1647 case DK_CFI_REMEMBER_STATE:
1648 return parseDirectiveCFIRememberState();
1649 case DK_CFI_RESTORE_STATE:
1650 return parseDirectiveCFIRestoreState();
1651 case DK_CFI_SAME_VALUE:
1652 return parseDirectiveCFISameValue(IDLoc);
1653 case DK_CFI_RESTORE:
1654 return parseDirectiveCFIRestore(IDLoc);
1656 return parseDirectiveCFIEscape();
1657 case DK_CFI_SIGNAL_FRAME:
1658 return parseDirectiveCFISignalFrame();
1659 case DK_CFI_UNDEFINED:
1660 return parseDirectiveCFIUndefined(IDLoc);
1661 case DK_CFI_REGISTER:
1662 return parseDirectiveCFIRegister(IDLoc);
1663 case DK_CFI_WINDOW_SAVE:
1664 return parseDirectiveCFIWindowSave();
1667 return parseDirectiveMacrosOnOff(IDVal);
1669 return parseDirectiveMacro(IDLoc);
1671 return parseDirectiveExitMacro(IDVal);
1674 return parseDirectiveEndMacro(IDVal);
1676 return parseDirectivePurgeMacro(IDLoc);
1678 return parseDirectiveEnd(IDLoc);
1680 return parseDirectiveError(IDLoc, false);
1682 return parseDirectiveError(IDLoc, true);
1684 return parseDirectiveWarning(IDLoc);
1687 return Error(IDLoc, "unknown directive");
1690 // __asm _emit or __asm __emit
1691 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1692 IDVal == "_EMIT" || IDVal == "__EMIT"))
1693 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1696 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1697 return parseDirectiveMSAlign(IDLoc, Info);
1699 checkForValidSection();
1701 // Canonicalize the opcode to lower case.
1702 std::string OpcodeStr = IDVal.lower();
1703 ParseInstructionInfo IInfo(Info.AsmRewrites);
1704 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1705 Info.ParsedOperands);
1706 Info.ParseError = HadError;
1708 // Dump the parsed representation, if requested.
1709 if (getShowParsedOperands()) {
1710 SmallString<256> Str;
1711 raw_svector_ostream OS(Str);
1712 OS << "parsed instruction: [";
1713 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1716 Info.ParsedOperands[i]->print(OS);
1720 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1723 // If we are generating dwarf for the current section then generate a .loc
1724 // directive for the instruction.
1725 if (!HadError && getContext().getGenDwarfForAssembly() &&
1726 getContext().getGenDwarfSectionSyms().count(
1727 getStreamer().getCurrentSection().first)) {
1729 if (ActiveMacros.empty())
1730 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1732 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1733 ActiveMacros.front()->ExitBuffer);
1735 // If we previously parsed a cpp hash file line comment then make sure the
1736 // current Dwarf File is for the CppHashFilename if not then emit the
1737 // Dwarf File table for it and adjust the line number for the .loc.
1738 if (CppHashFilename.size()) {
1739 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1740 0, StringRef(), CppHashFilename);
1741 getContext().setGenDwarfFileNumber(FileNumber);
1743 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1744 // cache with the different Loc from the call above we save the last
1745 // info we queried here with SrcMgr.FindLineNumber().
1746 unsigned CppHashLocLineNo;
1747 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1748 CppHashLocLineNo = LastQueryLine;
1750 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1751 LastQueryLine = CppHashLocLineNo;
1752 LastQueryIDLoc = CppHashLoc;
1753 LastQueryBuffer = CppHashBuf;
1755 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1758 getStreamer().EmitDwarfLocDirective(
1759 getContext().getGenDwarfFileNumber(), Line, 0,
1760 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1764 // If parsing succeeded, match the instruction.
1767 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1768 Info.ParsedOperands, Out,
1769 ErrorInfo, ParsingInlineAsm);
1772 // Don't skip the rest of the line, the instruction parser is responsible for
1777 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1778 /// since they may not be able to be tokenized to get to the end of line token.
1779 void AsmParser::eatToEndOfLine() {
1780 if (!Lexer.is(AsmToken::EndOfStatement))
1781 Lexer.LexUntilEndOfLine();
1786 /// parseCppHashLineFilenameComment as this:
1787 /// ::= # number "filename"
1788 /// or just as a full line comment if it doesn't have a number and a string.
1789 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1790 Lex(); // Eat the hash token.
1792 if (getLexer().isNot(AsmToken::Integer)) {
1793 // Consume the line since in cases it is not a well-formed line directive,
1794 // as if were simply a full line comment.
1799 int64_t LineNumber = getTok().getIntVal();
1802 if (getLexer().isNot(AsmToken::String)) {
1807 StringRef Filename = getTok().getString();
1808 // Get rid of the enclosing quotes.
1809 Filename = Filename.substr(1, Filename.size() - 2);
1811 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1813 CppHashFilename = Filename;
1814 CppHashLineNumber = LineNumber;
1815 CppHashBuf = CurBuffer;
1817 // Ignore any trailing characters, they're just comment.
1822 /// \brief will use the last parsed cpp hash line filename comment
1823 /// for the Filename and LineNo if any in the diagnostic.
1824 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1825 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1826 raw_ostream &OS = errs();
1828 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1829 SMLoc DiagLoc = Diag.getLoc();
1830 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1831 unsigned CppHashBuf =
1832 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1834 // Like SourceMgr::printMessage() we need to print the include stack if any
1835 // before printing the message.
1836 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1837 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1838 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1839 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1840 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1843 // If we have not parsed a cpp hash line filename comment or the source
1844 // manager changed or buffer changed (like in a nested include) then just
1845 // print the normal diagnostic using its Filename and LineNo.
1846 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1847 DiagBuf != CppHashBuf) {
1848 if (Parser->SavedDiagHandler)
1849 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1851 Diag.print(nullptr, OS);
1855 // Use the CppHashFilename and calculate a line number based on the
1856 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1858 const std::string &Filename = Parser->CppHashFilename;
1860 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1861 int CppHashLocLineNo =
1862 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1864 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1866 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1867 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1868 Diag.getLineContents(), Diag.getRanges());
1870 if (Parser->SavedDiagHandler)
1871 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1873 NewDiag.print(nullptr, OS);
1876 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1877 // difference being that that function accepts '@' as part of identifiers and
1878 // we can't do that. AsmLexer.cpp should probably be changed to handle
1879 // '@' as a special case when needed.
1880 static bool isIdentifierChar(char c) {
1881 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1885 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1886 ArrayRef<MCAsmMacroParameter> Parameters,
1887 ArrayRef<MCAsmMacroArgument> A,
1888 bool EnableAtPseudoVariable, SMLoc L) {
1889 unsigned NParameters = Parameters.size();
1890 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1891 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1892 return Error(L, "Wrong number of arguments");
1894 // A macro without parameters is handled differently on Darwin:
1895 // gas accepts no arguments and does no substitutions
1896 while (!Body.empty()) {
1897 // Scan for the next substitution.
1898 std::size_t End = Body.size(), Pos = 0;
1899 for (; Pos != End; ++Pos) {
1900 // Check for a substitution or escape.
1901 if (IsDarwin && !NParameters) {
1902 // This macro has no parameters, look for $0, $1, etc.
1903 if (Body[Pos] != '$' || Pos + 1 == End)
1906 char Next = Body[Pos + 1];
1907 if (Next == '$' || Next == 'n' ||
1908 isdigit(static_cast<unsigned char>(Next)))
1911 // This macro has parameters, look for \foo, \bar, etc.
1912 if (Body[Pos] == '\\' && Pos + 1 != End)
1918 OS << Body.slice(0, Pos);
1920 // Check if we reached the end.
1924 if (IsDarwin && !NParameters) {
1925 switch (Body[Pos + 1]) {
1931 // $n => number of arguments
1936 // $[0-9] => argument
1938 // Missing arguments are ignored.
1939 unsigned Index = Body[Pos + 1] - '0';
1940 if (Index >= A.size())
1943 // Otherwise substitute with the token values, with spaces eliminated.
1944 for (const AsmToken &Token : A[Index])
1945 OS << Token.getString();
1951 unsigned I = Pos + 1;
1953 // Check for the \@ pseudo-variable.
1954 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1957 while (isIdentifierChar(Body[I]) && I + 1 != End)
1960 const char *Begin = Body.data() + Pos + 1;
1961 StringRef Argument(Begin, I - (Pos + 1));
1964 if (Argument == "@") {
1965 OS << NumOfMacroInstantiations;
1968 for (; Index < NParameters; ++Index)
1969 if (Parameters[Index].Name == Argument)
1972 if (Index == NParameters) {
1973 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1976 OS << '\\' << Argument;
1980 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1981 for (const AsmToken &Token : A[Index])
1982 // We expect no quotes around the string's contents when
1983 // parsing for varargs.
1984 if (Token.getKind() != AsmToken::String || VarargParameter)
1985 OS << Token.getString();
1987 OS << Token.getStringContents();
1989 Pos += 1 + Argument.size();
1993 // Update the scan point.
1994 Body = Body.substr(Pos);
2000 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2001 size_t CondStackDepth)
2002 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2003 CondStackDepth(CondStackDepth) {}
2005 static bool isOperator(AsmToken::TokenKind kind) {
2009 case AsmToken::Plus:
2010 case AsmToken::Minus:
2011 case AsmToken::Tilde:
2012 case AsmToken::Slash:
2013 case AsmToken::Star:
2015 case AsmToken::Equal:
2016 case AsmToken::EqualEqual:
2017 case AsmToken::Pipe:
2018 case AsmToken::PipePipe:
2019 case AsmToken::Caret:
2021 case AsmToken::AmpAmp:
2022 case AsmToken::Exclaim:
2023 case AsmToken::ExclaimEqual:
2024 case AsmToken::Percent:
2025 case AsmToken::Less:
2026 case AsmToken::LessEqual:
2027 case AsmToken::LessLess:
2028 case AsmToken::LessGreater:
2029 case AsmToken::Greater:
2030 case AsmToken::GreaterEqual:
2031 case AsmToken::GreaterGreater:
2037 class AsmLexerSkipSpaceRAII {
2039 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2040 Lexer.setSkipSpace(SkipSpace);
2043 ~AsmLexerSkipSpaceRAII() {
2044 Lexer.setSkipSpace(true);
2052 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2055 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2056 StringRef Str = parseStringToEndOfStatement();
2057 MA.emplace_back(AsmToken::String, Str);
2062 unsigned ParenLevel = 0;
2063 unsigned AddTokens = 0;
2065 // Darwin doesn't use spaces to delmit arguments.
2066 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2069 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2070 return TokError("unexpected token in macro instantiation");
2072 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2075 if (Lexer.is(AsmToken::Space)) {
2076 Lex(); // Eat spaces
2078 // Spaces can delimit parameters, but could also be part an expression.
2079 // If the token after a space is an operator, add the token and the next
2080 // one into this argument
2082 if (isOperator(Lexer.getKind())) {
2083 // Check to see whether the token is used as an operator,
2084 // or part of an identifier
2085 const char *NextChar = getTok().getEndLoc().getPointer();
2086 if (*NextChar == ' ')
2090 if (!AddTokens && ParenLevel == 0) {
2096 // handleMacroEntry relies on not advancing the lexer here
2097 // to be able to fill in the remaining default parameter values
2098 if (Lexer.is(AsmToken::EndOfStatement))
2101 // Adjust the current parentheses level.
2102 if (Lexer.is(AsmToken::LParen))
2104 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2107 // Append the token to the current argument list.
2108 MA.push_back(getTok());
2114 if (ParenLevel != 0)
2115 return TokError("unbalanced parentheses in macro argument");
2119 // Parse the macro instantiation arguments.
2120 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2121 MCAsmMacroArguments &A) {
2122 const unsigned NParameters = M ? M->Parameters.size() : 0;
2123 bool NamedParametersFound = false;
2124 SmallVector<SMLoc, 4> FALocs;
2126 A.resize(NParameters);
2127 FALocs.resize(NParameters);
2129 // Parse two kinds of macro invocations:
2130 // - macros defined without any parameters accept an arbitrary number of them
2131 // - macros defined with parameters accept at most that many of them
2132 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2133 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2135 SMLoc IDLoc = Lexer.getLoc();
2136 MCAsmMacroParameter FA;
2138 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2139 if (parseIdentifier(FA.Name)) {
2140 Error(IDLoc, "invalid argument identifier for formal argument");
2141 eatToEndOfStatement();
2145 if (!Lexer.is(AsmToken::Equal)) {
2146 TokError("expected '=' after formal parameter identifier");
2147 eatToEndOfStatement();
2152 NamedParametersFound = true;
2155 if (NamedParametersFound && FA.Name.empty()) {
2156 Error(IDLoc, "cannot mix positional and keyword arguments");
2157 eatToEndOfStatement();
2161 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2162 if (parseMacroArgument(FA.Value, Vararg))
2165 unsigned PI = Parameter;
2166 if (!FA.Name.empty()) {
2168 for (FAI = 0; FAI < NParameters; ++FAI)
2169 if (M->Parameters[FAI].Name == FA.Name)
2172 if (FAI >= NParameters) {
2173 assert(M && "expected macro to be defined");
2175 "parameter named '" + FA.Name + "' does not exist for macro '" +
2182 if (!FA.Value.empty()) {
2187 if (FALocs.size() <= PI)
2188 FALocs.resize(PI + 1);
2190 FALocs[PI] = Lexer.getLoc();
2193 // At the end of the statement, fill in remaining arguments that have
2194 // default values. If there aren't any, then the next argument is
2195 // required but missing
2196 if (Lexer.is(AsmToken::EndOfStatement)) {
2197 bool Failure = false;
2198 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2199 if (A[FAI].empty()) {
2200 if (M->Parameters[FAI].Required) {
2201 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2202 "missing value for required parameter "
2203 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2207 if (!M->Parameters[FAI].Value.empty())
2208 A[FAI] = M->Parameters[FAI].Value;
2214 if (Lexer.is(AsmToken::Comma))
2218 return TokError("too many positional arguments");
2221 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2222 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2223 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2226 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2227 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2230 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2232 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2233 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2234 // this, although we should protect against infinite loops.
2235 if (ActiveMacros.size() == 20)
2236 return TokError("macros cannot be nested more than 20 levels deep");
2238 MCAsmMacroArguments A;
2239 if (parseMacroArguments(M, A))
2242 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2243 // to hold the macro body with substitutions.
2244 SmallString<256> Buf;
2245 StringRef Body = M->Body;
2246 raw_svector_ostream OS(Buf);
2248 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2251 // We include the .endmacro in the buffer as our cue to exit the macro
2253 OS << ".endmacro\n";
2255 std::unique_ptr<MemoryBuffer> Instantiation =
2256 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2258 // Create the macro instantiation object and add to the current macro
2259 // instantiation stack.
2260 MacroInstantiation *MI = new MacroInstantiation(
2261 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2262 ActiveMacros.push_back(MI);
2264 ++NumOfMacroInstantiations;
2266 // Jump to the macro instantiation and prime the lexer.
2267 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2268 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2274 void AsmParser::handleMacroExit() {
2275 // Jump to the EndOfStatement we should return to, and consume it.
2276 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2279 // Pop the instantiation entry.
2280 delete ActiveMacros.back();
2281 ActiveMacros.pop_back();
2284 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2287 const MCExpr *Value;
2288 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2293 // In the case where we parse an expression starting with a '.', we will
2294 // not generate an error, nor will we create a symbol. In this case we
2295 // should just return out.
2299 // Do the assignment.
2300 Out.EmitAssignment(Sym, Value);
2302 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2307 /// parseIdentifier:
2310 bool AsmParser::parseIdentifier(StringRef &Res) {
2311 // The assembler has relaxed rules for accepting identifiers, in particular we
2312 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2313 // separate tokens. At this level, we have already lexed so we cannot (currently)
2314 // handle this as a context dependent token, instead we detect adjacent tokens
2315 // and return the combined identifier.
2316 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2317 SMLoc PrefixLoc = getLexer().getLoc();
2319 // Consume the prefix character, and check for a following identifier.
2321 if (Lexer.isNot(AsmToken::Identifier))
2324 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2325 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2328 // Construct the joined identifier and consume the token.
2330 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2335 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2338 Res = getTok().getIdentifier();
2340 Lex(); // Consume the identifier token.
2345 /// parseDirectiveSet:
2346 /// ::= .equ identifier ',' expression
2347 /// ::= .equiv identifier ',' expression
2348 /// ::= .set identifier ',' expression
2349 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2352 if (parseIdentifier(Name))
2353 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2355 if (getLexer().isNot(AsmToken::Comma))
2356 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2359 return parseAssignment(Name, allow_redef, true);
2362 bool AsmParser::parseEscapedString(std::string &Data) {
2363 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2366 StringRef Str = getTok().getStringContents();
2367 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2368 if (Str[i] != '\\') {
2373 // Recognize escaped characters. Note that this escape semantics currently
2374 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2377 return TokError("unexpected backslash at end of string");
2379 // Recognize octal sequences.
2380 if ((unsigned)(Str[i] - '0') <= 7) {
2381 // Consume up to three octal characters.
2382 unsigned Value = Str[i] - '0';
2384 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2386 Value = Value * 8 + (Str[i] - '0');
2388 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2390 Value = Value * 8 + (Str[i] - '0');
2395 return TokError("invalid octal escape sequence (out of range)");
2397 Data += (unsigned char)Value;
2401 // Otherwise recognize individual escapes.
2404 // Just reject invalid escape sequences for now.
2405 return TokError("invalid escape sequence (unrecognized character)");
2407 case 'b': Data += '\b'; break;
2408 case 'f': Data += '\f'; break;
2409 case 'n': Data += '\n'; break;
2410 case 'r': Data += '\r'; break;
2411 case 't': Data += '\t'; break;
2412 case '"': Data += '"'; break;
2413 case '\\': Data += '\\'; break;
2420 /// parseDirectiveAscii:
2421 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2422 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2423 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2424 checkForValidSection();
2427 if (getLexer().isNot(AsmToken::String))
2428 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2431 if (parseEscapedString(Data))
2434 getStreamer().EmitBytes(Data);
2436 getStreamer().EmitBytes(StringRef("\0", 1));
2440 if (getLexer().is(AsmToken::EndOfStatement))
2443 if (getLexer().isNot(AsmToken::Comma))
2444 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2453 /// parseDirectiveValue
2454 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2455 bool AsmParser::parseDirectiveValue(unsigned Size) {
2456 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2457 checkForValidSection();
2460 const MCExpr *Value;
2461 SMLoc ExprLoc = getLexer().getLoc();
2462 if (parseExpression(Value))
2465 // Special case constant expressions to match code generator.
2466 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2467 assert(Size <= 8 && "Invalid size");
2468 uint64_t IntValue = MCE->getValue();
2469 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2470 return Error(ExprLoc, "literal value out of range for directive");
2471 getStreamer().EmitIntValue(IntValue, Size);
2473 getStreamer().EmitValue(Value, Size, ExprLoc);
2475 if (getLexer().is(AsmToken::EndOfStatement))
2478 // FIXME: Improve diagnostic.
2479 if (getLexer().isNot(AsmToken::Comma))
2480 return TokError("unexpected token in directive");
2489 /// ParseDirectiveOctaValue
2490 /// ::= .octa [ hexconstant (, hexconstant)* ]
2491 bool AsmParser::parseDirectiveOctaValue() {
2492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2493 checkForValidSection();
2496 if (Lexer.getKind() == AsmToken::Error)
2498 if (Lexer.getKind() != AsmToken::Integer &&
2499 Lexer.getKind() != AsmToken::BigNum)
2500 return TokError("unknown token in expression");
2502 SMLoc ExprLoc = getLexer().getLoc();
2503 APInt IntValue = getTok().getAPIntVal();
2507 if (IntValue.isIntN(64)) {
2509 lo = IntValue.getZExtValue();
2510 } else if (IntValue.isIntN(128)) {
2511 // It might actually have more than 128 bits, but the top ones are zero.
2512 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2513 lo = IntValue.getLoBits(64).getZExtValue();
2515 return Error(ExprLoc, "literal value out of range for directive");
2517 if (MAI.isLittleEndian()) {
2518 getStreamer().EmitIntValue(lo, 8);
2519 getStreamer().EmitIntValue(hi, 8);
2521 getStreamer().EmitIntValue(hi, 8);
2522 getStreamer().EmitIntValue(lo, 8);
2525 if (getLexer().is(AsmToken::EndOfStatement))
2528 // FIXME: Improve diagnostic.
2529 if (getLexer().isNot(AsmToken::Comma))
2530 return TokError("unexpected token in directive");
2539 /// parseDirectiveRealValue
2540 /// ::= (.single | .double) [ expression (, expression)* ]
2541 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2542 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2543 checkForValidSection();
2546 // We don't truly support arithmetic on floating point expressions, so we
2547 // have to manually parse unary prefixes.
2549 if (getLexer().is(AsmToken::Minus)) {
2552 } else if (getLexer().is(AsmToken::Plus))
2555 if (getLexer().isNot(AsmToken::Integer) &&
2556 getLexer().isNot(AsmToken::Real) &&
2557 getLexer().isNot(AsmToken::Identifier))
2558 return TokError("unexpected token in directive");
2560 // Convert to an APFloat.
2561 APFloat Value(Semantics);
2562 StringRef IDVal = getTok().getString();
2563 if (getLexer().is(AsmToken::Identifier)) {
2564 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2565 Value = APFloat::getInf(Semantics);
2566 else if (!IDVal.compare_lower("nan"))
2567 Value = APFloat::getNaN(Semantics, false, ~0);
2569 return TokError("invalid floating point literal");
2570 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2571 APFloat::opInvalidOp)
2572 return TokError("invalid floating point literal");
2576 // Consume the numeric token.
2579 // Emit the value as an integer.
2580 APInt AsInt = Value.bitcastToAPInt();
2581 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2582 AsInt.getBitWidth() / 8);
2584 if (getLexer().is(AsmToken::EndOfStatement))
2587 if (getLexer().isNot(AsmToken::Comma))
2588 return TokError("unexpected token in directive");
2597 /// parseDirectiveZero
2598 /// ::= .zero expression
2599 bool AsmParser::parseDirectiveZero() {
2600 checkForValidSection();
2603 if (parseAbsoluteExpression(NumBytes))
2607 if (getLexer().is(AsmToken::Comma)) {
2609 if (parseAbsoluteExpression(Val))
2613 if (getLexer().isNot(AsmToken::EndOfStatement))
2614 return TokError("unexpected token in '.zero' directive");
2618 getStreamer().EmitFill(NumBytes, Val);
2623 /// parseDirectiveFill
2624 /// ::= .fill expression [ , expression [ , expression ] ]
2625 bool AsmParser::parseDirectiveFill() {
2626 checkForValidSection();
2628 SMLoc RepeatLoc = getLexer().getLoc();
2630 if (parseAbsoluteExpression(NumValues))
2633 if (NumValues < 0) {
2635 "'.fill' directive with negative repeat count has no effect");
2639 int64_t FillSize = 1;
2640 int64_t FillExpr = 0;
2642 SMLoc SizeLoc, ExprLoc;
2643 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2644 if (getLexer().isNot(AsmToken::Comma))
2645 return TokError("unexpected token in '.fill' directive");
2648 SizeLoc = getLexer().getLoc();
2649 if (parseAbsoluteExpression(FillSize))
2652 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2653 if (getLexer().isNot(AsmToken::Comma))
2654 return TokError("unexpected token in '.fill' directive");
2657 ExprLoc = getLexer().getLoc();
2658 if (parseAbsoluteExpression(FillExpr))
2661 if (getLexer().isNot(AsmToken::EndOfStatement))
2662 return TokError("unexpected token in '.fill' directive");
2669 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2673 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2677 if (!isUInt<32>(FillExpr) && FillSize > 4)
2678 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2680 if (NumValues > 0) {
2681 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2682 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2683 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2684 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2685 if (NonZeroFillSize < FillSize)
2686 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2693 /// parseDirectiveOrg
2694 /// ::= .org expression [ , expression ]
2695 bool AsmParser::parseDirectiveOrg() {
2696 checkForValidSection();
2698 const MCExpr *Offset;
2699 SMLoc Loc = getTok().getLoc();
2700 if (parseExpression(Offset))
2703 // Parse optional fill expression.
2704 int64_t FillExpr = 0;
2705 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2706 if (getLexer().isNot(AsmToken::Comma))
2707 return TokError("unexpected token in '.org' directive");
2710 if (parseAbsoluteExpression(FillExpr))
2713 if (getLexer().isNot(AsmToken::EndOfStatement))
2714 return TokError("unexpected token in '.org' directive");
2719 // Only limited forms of relocatable expressions are accepted here, it
2720 // has to be relative to the current section. The streamer will return
2721 // 'true' if the expression wasn't evaluatable.
2722 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2723 return Error(Loc, "expected assembly-time absolute expression");
2728 /// parseDirectiveAlign
2729 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2730 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2731 checkForValidSection();
2733 SMLoc AlignmentLoc = getLexer().getLoc();
2735 if (parseAbsoluteExpression(Alignment))
2739 bool HasFillExpr = false;
2740 int64_t FillExpr = 0;
2741 int64_t MaxBytesToFill = 0;
2742 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2743 if (getLexer().isNot(AsmToken::Comma))
2744 return TokError("unexpected token in directive");
2747 // The fill expression can be omitted while specifying a maximum number of
2748 // alignment bytes, e.g:
2750 if (getLexer().isNot(AsmToken::Comma)) {
2752 if (parseAbsoluteExpression(FillExpr))
2756 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2757 if (getLexer().isNot(AsmToken::Comma))
2758 return TokError("unexpected token in directive");
2761 MaxBytesLoc = getLexer().getLoc();
2762 if (parseAbsoluteExpression(MaxBytesToFill))
2765 if (getLexer().isNot(AsmToken::EndOfStatement))
2766 return TokError("unexpected token in directive");
2775 // Compute alignment in bytes.
2777 // FIXME: Diagnose overflow.
2778 if (Alignment >= 32) {
2779 Error(AlignmentLoc, "invalid alignment value");
2783 Alignment = 1ULL << Alignment;
2785 // Reject alignments that aren't either a power of two or zero,
2786 // for gas compatibility. Alignment of zero is silently rounded
2790 if (!isPowerOf2_64(Alignment))
2791 Error(AlignmentLoc, "alignment must be a power of 2");
2794 // Diagnose non-sensical max bytes to align.
2795 if (MaxBytesLoc.isValid()) {
2796 if (MaxBytesToFill < 1) {
2797 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2798 "many bytes, ignoring maximum bytes expression");
2802 if (MaxBytesToFill >= Alignment) {
2803 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2809 // Check whether we should use optimal code alignment for this .align
2811 const MCSection *Section = getStreamer().getCurrentSection().first;
2812 assert(Section && "must have section to emit alignment");
2813 bool UseCodeAlign = Section->UseCodeAlign();
2814 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2815 ValueSize == 1 && UseCodeAlign) {
2816 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2818 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2819 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2826 /// parseDirectiveFile
2827 /// ::= .file [number] filename
2828 /// ::= .file number directory filename
2829 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2830 // FIXME: I'm not sure what this is.
2831 int64_t FileNumber = -1;
2832 SMLoc FileNumberLoc = getLexer().getLoc();
2833 if (getLexer().is(AsmToken::Integer)) {
2834 FileNumber = getTok().getIntVal();
2838 return TokError("file number less than one");
2841 if (getLexer().isNot(AsmToken::String))
2842 return TokError("unexpected token in '.file' directive");
2844 // Usually the directory and filename together, otherwise just the directory.
2845 // Allow the strings to have escaped octal character sequence.
2846 std::string Path = getTok().getString();
2847 if (parseEscapedString(Path))
2851 StringRef Directory;
2853 std::string FilenameData;
2854 if (getLexer().is(AsmToken::String)) {
2855 if (FileNumber == -1)
2856 return TokError("explicit path specified, but no file number");
2857 if (parseEscapedString(FilenameData))
2859 Filename = FilenameData;
2866 if (getLexer().isNot(AsmToken::EndOfStatement))
2867 return TokError("unexpected token in '.file' directive");
2869 if (FileNumber == -1)
2870 getStreamer().EmitFileDirective(Filename);
2872 if (getContext().getGenDwarfForAssembly())
2874 "input can't have .file dwarf directives when -g is "
2875 "used to generate dwarf debug info for assembly code");
2877 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2879 Error(FileNumberLoc, "file number already allocated");
2885 /// parseDirectiveLine
2886 /// ::= .line [number]
2887 bool AsmParser::parseDirectiveLine() {
2888 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2889 if (getLexer().isNot(AsmToken::Integer))
2890 return TokError("unexpected token in '.line' directive");
2892 int64_t LineNumber = getTok().getIntVal();
2896 // FIXME: Do something with the .line.
2899 if (getLexer().isNot(AsmToken::EndOfStatement))
2900 return TokError("unexpected token in '.line' directive");
2905 /// parseDirectiveLoc
2906 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2907 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2908 /// The first number is a file number, must have been previously assigned with
2909 /// a .file directive, the second number is the line number and optionally the
2910 /// third number is a column position (zero if not specified). The remaining
2911 /// optional items are .loc sub-directives.
2912 bool AsmParser::parseDirectiveLoc() {
2913 if (getLexer().isNot(AsmToken::Integer))
2914 return TokError("unexpected token in '.loc' directive");
2915 int64_t FileNumber = getTok().getIntVal();
2917 return TokError("file number less than one in '.loc' directive");
2918 if (!getContext().isValidDwarfFileNumber(FileNumber))
2919 return TokError("unassigned file number in '.loc' directive");
2922 int64_t LineNumber = 0;
2923 if (getLexer().is(AsmToken::Integer)) {
2924 LineNumber = getTok().getIntVal();
2926 return TokError("line number less than zero in '.loc' directive");
2930 int64_t ColumnPos = 0;
2931 if (getLexer().is(AsmToken::Integer)) {
2932 ColumnPos = getTok().getIntVal();
2934 return TokError("column position less than zero in '.loc' directive");
2938 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2940 int64_t Discriminator = 0;
2941 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2943 if (getLexer().is(AsmToken::EndOfStatement))
2947 SMLoc Loc = getTok().getLoc();
2948 if (parseIdentifier(Name))
2949 return TokError("unexpected token in '.loc' directive");
2951 if (Name == "basic_block")
2952 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2953 else if (Name == "prologue_end")
2954 Flags |= DWARF2_FLAG_PROLOGUE_END;
2955 else if (Name == "epilogue_begin")
2956 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2957 else if (Name == "is_stmt") {
2958 Loc = getTok().getLoc();
2959 const MCExpr *Value;
2960 if (parseExpression(Value))
2962 // The expression must be the constant 0 or 1.
2963 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2964 int Value = MCE->getValue();
2966 Flags &= ~DWARF2_FLAG_IS_STMT;
2967 else if (Value == 1)
2968 Flags |= DWARF2_FLAG_IS_STMT;
2970 return Error(Loc, "is_stmt value not 0 or 1");
2972 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2974 } else if (Name == "isa") {
2975 Loc = getTok().getLoc();
2976 const MCExpr *Value;
2977 if (parseExpression(Value))
2979 // The expression must be a constant greater or equal to 0.
2980 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2981 int Value = MCE->getValue();
2983 return Error(Loc, "isa number less than zero");
2986 return Error(Loc, "isa number not a constant value");
2988 } else if (Name == "discriminator") {
2989 if (parseAbsoluteExpression(Discriminator))
2992 return Error(Loc, "unknown sub-directive in '.loc' directive");
2995 if (getLexer().is(AsmToken::EndOfStatement))
3000 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3001 Isa, Discriminator, StringRef());
3006 /// parseDirectiveStabs
3007 /// ::= .stabs string, number, number, number
3008 bool AsmParser::parseDirectiveStabs() {
3009 return TokError("unsupported directive '.stabs'");
3012 /// parseDirectiveCFISections
3013 /// ::= .cfi_sections section [, section]
3014 bool AsmParser::parseDirectiveCFISections() {
3019 if (parseIdentifier(Name))
3020 return TokError("Expected an identifier");
3022 if (Name == ".eh_frame")
3024 else if (Name == ".debug_frame")
3027 if (getLexer().is(AsmToken::Comma)) {
3030 if (parseIdentifier(Name))
3031 return TokError("Expected an identifier");
3033 if (Name == ".eh_frame")
3035 else if (Name == ".debug_frame")
3039 getStreamer().EmitCFISections(EH, Debug);
3043 /// parseDirectiveCFIStartProc
3044 /// ::= .cfi_startproc [simple]
3045 bool AsmParser::parseDirectiveCFIStartProc() {
3047 if (getLexer().isNot(AsmToken::EndOfStatement))
3048 if (parseIdentifier(Simple) || Simple != "simple")
3049 return TokError("unexpected token in .cfi_startproc directive");
3051 getStreamer().EmitCFIStartProc(!Simple.empty());
3055 /// parseDirectiveCFIEndProc
3056 /// ::= .cfi_endproc
3057 bool AsmParser::parseDirectiveCFIEndProc() {
3058 getStreamer().EmitCFIEndProc();
3062 /// \brief parse register name or number.
3063 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3064 SMLoc DirectiveLoc) {
3067 if (getLexer().isNot(AsmToken::Integer)) {
3068 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3070 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3072 return parseAbsoluteExpression(Register);
3077 /// parseDirectiveCFIDefCfa
3078 /// ::= .cfi_def_cfa register, offset
3079 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3080 int64_t Register = 0;
3081 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3084 if (getLexer().isNot(AsmToken::Comma))
3085 return TokError("unexpected token in directive");
3089 if (parseAbsoluteExpression(Offset))
3092 getStreamer().EmitCFIDefCfa(Register, Offset);
3096 /// parseDirectiveCFIDefCfaOffset
3097 /// ::= .cfi_def_cfa_offset offset
3098 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3100 if (parseAbsoluteExpression(Offset))
3103 getStreamer().EmitCFIDefCfaOffset(Offset);
3107 /// parseDirectiveCFIRegister
3108 /// ::= .cfi_register register, register
3109 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3110 int64_t Register1 = 0;
3111 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3114 if (getLexer().isNot(AsmToken::Comma))
3115 return TokError("unexpected token in directive");
3118 int64_t Register2 = 0;
3119 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3122 getStreamer().EmitCFIRegister(Register1, Register2);
3126 /// parseDirectiveCFIWindowSave
3127 /// ::= .cfi_window_save
3128 bool AsmParser::parseDirectiveCFIWindowSave() {
3129 getStreamer().EmitCFIWindowSave();
3133 /// parseDirectiveCFIAdjustCfaOffset
3134 /// ::= .cfi_adjust_cfa_offset adjustment
3135 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3136 int64_t Adjustment = 0;
3137 if (parseAbsoluteExpression(Adjustment))
3140 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3144 /// parseDirectiveCFIDefCfaRegister
3145 /// ::= .cfi_def_cfa_register register
3146 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3147 int64_t Register = 0;
3148 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3151 getStreamer().EmitCFIDefCfaRegister(Register);
3155 /// parseDirectiveCFIOffset
3156 /// ::= .cfi_offset register, offset
3157 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3158 int64_t Register = 0;
3161 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3164 if (getLexer().isNot(AsmToken::Comma))
3165 return TokError("unexpected token in directive");
3168 if (parseAbsoluteExpression(Offset))
3171 getStreamer().EmitCFIOffset(Register, Offset);
3175 /// parseDirectiveCFIRelOffset
3176 /// ::= .cfi_rel_offset register, offset
3177 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3178 int64_t Register = 0;
3180 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3183 if (getLexer().isNot(AsmToken::Comma))
3184 return TokError("unexpected token in directive");
3188 if (parseAbsoluteExpression(Offset))
3191 getStreamer().EmitCFIRelOffset(Register, Offset);
3195 static bool isValidEncoding(int64_t Encoding) {
3196 if (Encoding & ~0xff)
3199 if (Encoding == dwarf::DW_EH_PE_omit)
3202 const unsigned Format = Encoding & 0xf;
3203 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3204 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3205 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3206 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3209 const unsigned Application = Encoding & 0x70;
3210 if (Application != dwarf::DW_EH_PE_absptr &&
3211 Application != dwarf::DW_EH_PE_pcrel)
3217 /// parseDirectiveCFIPersonalityOrLsda
3218 /// IsPersonality true for cfi_personality, false for cfi_lsda
3219 /// ::= .cfi_personality encoding, [symbol_name]
3220 /// ::= .cfi_lsda encoding, [symbol_name]
3221 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3222 int64_t Encoding = 0;
3223 if (parseAbsoluteExpression(Encoding))
3225 if (Encoding == dwarf::DW_EH_PE_omit)
3228 if (!isValidEncoding(Encoding))
3229 return TokError("unsupported encoding.");
3231 if (getLexer().isNot(AsmToken::Comma))
3232 return TokError("unexpected token in directive");
3236 if (parseIdentifier(Name))
3237 return TokError("expected identifier in directive");
3239 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3242 getStreamer().EmitCFIPersonality(Sym, Encoding);
3244 getStreamer().EmitCFILsda(Sym, Encoding);
3248 /// parseDirectiveCFIRememberState
3249 /// ::= .cfi_remember_state
3250 bool AsmParser::parseDirectiveCFIRememberState() {
3251 getStreamer().EmitCFIRememberState();
3255 /// parseDirectiveCFIRestoreState
3256 /// ::= .cfi_remember_state
3257 bool AsmParser::parseDirectiveCFIRestoreState() {
3258 getStreamer().EmitCFIRestoreState();
3262 /// parseDirectiveCFISameValue
3263 /// ::= .cfi_same_value register
3264 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3265 int64_t Register = 0;
3267 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3270 getStreamer().EmitCFISameValue(Register);
3274 /// parseDirectiveCFIRestore
3275 /// ::= .cfi_restore register
3276 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3277 int64_t Register = 0;
3278 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3281 getStreamer().EmitCFIRestore(Register);
3285 /// parseDirectiveCFIEscape
3286 /// ::= .cfi_escape expression[,...]
3287 bool AsmParser::parseDirectiveCFIEscape() {
3290 if (parseAbsoluteExpression(CurrValue))
3293 Values.push_back((uint8_t)CurrValue);
3295 while (getLexer().is(AsmToken::Comma)) {
3298 if (parseAbsoluteExpression(CurrValue))
3301 Values.push_back((uint8_t)CurrValue);
3304 getStreamer().EmitCFIEscape(Values);
3308 /// parseDirectiveCFISignalFrame
3309 /// ::= .cfi_signal_frame
3310 bool AsmParser::parseDirectiveCFISignalFrame() {
3311 if (getLexer().isNot(AsmToken::EndOfStatement))
3312 return Error(getLexer().getLoc(),
3313 "unexpected token in '.cfi_signal_frame'");
3315 getStreamer().EmitCFISignalFrame();
3319 /// parseDirectiveCFIUndefined
3320 /// ::= .cfi_undefined register
3321 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3322 int64_t Register = 0;
3324 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3327 getStreamer().EmitCFIUndefined(Register);
3331 /// parseDirectiveMacrosOnOff
3334 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3335 if (getLexer().isNot(AsmToken::EndOfStatement))
3336 return Error(getLexer().getLoc(),
3337 "unexpected token in '" + Directive + "' directive");
3339 setMacrosEnabled(Directive == ".macros_on");
3343 /// parseDirectiveMacro
3344 /// ::= .macro name[,] [parameters]
3345 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3347 if (parseIdentifier(Name))
3348 return TokError("expected identifier in '.macro' directive");
3350 if (getLexer().is(AsmToken::Comma))
3353 MCAsmMacroParameters Parameters;
3354 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3356 if (!Parameters.empty() && Parameters.back().Vararg)
3357 return Error(Lexer.getLoc(),
3358 "Vararg parameter '" + Parameters.back().Name +
3359 "' should be last one in the list of parameters.");
3361 MCAsmMacroParameter Parameter;
3362 if (parseIdentifier(Parameter.Name))
3363 return TokError("expected identifier in '.macro' directive");
3365 if (Lexer.is(AsmToken::Colon)) {
3366 Lex(); // consume ':'
3369 StringRef Qualifier;
3371 QualLoc = Lexer.getLoc();
3372 if (parseIdentifier(Qualifier))
3373 return Error(QualLoc, "missing parameter qualifier for "
3374 "'" + Parameter.Name + "' in macro '" + Name + "'");
3376 if (Qualifier == "req")
3377 Parameter.Required = true;
3378 else if (Qualifier == "vararg")
3379 Parameter.Vararg = true;
3381 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3382 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3385 if (getLexer().is(AsmToken::Equal)) {
3390 ParamLoc = Lexer.getLoc();
3391 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3394 if (Parameter.Required)
3395 Warning(ParamLoc, "pointless default value for required parameter "
3396 "'" + Parameter.Name + "' in macro '" + Name + "'");
3399 Parameters.push_back(std::move(Parameter));
3401 if (getLexer().is(AsmToken::Comma))
3405 // Eat the end of statement.
3408 AsmToken EndToken, StartToken = getTok();
3409 unsigned MacroDepth = 0;
3411 // Lex the macro definition.
3413 // Check whether we have reached the end of the file.
3414 if (getLexer().is(AsmToken::Eof))
3415 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3417 // Otherwise, check whether we have reach the .endmacro.
3418 if (getLexer().is(AsmToken::Identifier)) {
3419 if (getTok().getIdentifier() == ".endm" ||
3420 getTok().getIdentifier() == ".endmacro") {
3421 if (MacroDepth == 0) { // Outermost macro.
3422 EndToken = getTok();
3424 if (getLexer().isNot(AsmToken::EndOfStatement))
3425 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3429 // Otherwise we just found the end of an inner macro.
3432 } else if (getTok().getIdentifier() == ".macro") {
3433 // We allow nested macros. Those aren't instantiated until the outermost
3434 // macro is expanded so just ignore them for now.
3439 // Otherwise, scan til the end of the statement.
3440 eatToEndOfStatement();
3443 if (lookupMacro(Name)) {
3444 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3447 const char *BodyStart = StartToken.getLoc().getPointer();
3448 const char *BodyEnd = EndToken.getLoc().getPointer();
3449 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3450 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3451 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3455 /// checkForBadMacro
3457 /// With the support added for named parameters there may be code out there that
3458 /// is transitioning from positional parameters. In versions of gas that did
3459 /// not support named parameters they would be ignored on the macro definition.
3460 /// But to support both styles of parameters this is not possible so if a macro
3461 /// definition has named parameters but does not use them and has what appears
3462 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3463 /// warning that the positional parameter found in body which have no effect.
3464 /// Hoping the developer will either remove the named parameters from the macro
3465 /// definition so the positional parameters get used if that was what was
3466 /// intended or change the macro to use the named parameters. It is possible
3467 /// this warning will trigger when the none of the named parameters are used
3468 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3469 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3471 ArrayRef<MCAsmMacroParameter> Parameters) {
3472 // If this macro is not defined with named parameters the warning we are
3473 // checking for here doesn't apply.
3474 unsigned NParameters = Parameters.size();
3475 if (NParameters == 0)
3478 bool NamedParametersFound = false;
3479 bool PositionalParametersFound = false;
3481 // Look at the body of the macro for use of both the named parameters and what
3482 // are likely to be positional parameters. This is what expandMacro() is
3483 // doing when it finds the parameters in the body.
3484 while (!Body.empty()) {
3485 // Scan for the next possible parameter.
3486 std::size_t End = Body.size(), Pos = 0;
3487 for (; Pos != End; ++Pos) {
3488 // Check for a substitution or escape.
3489 // This macro is defined with parameters, look for \foo, \bar, etc.
3490 if (Body[Pos] == '\\' && Pos + 1 != End)
3493 // This macro should have parameters, but look for $0, $1, ..., $n too.
3494 if (Body[Pos] != '$' || Pos + 1 == End)
3496 char Next = Body[Pos + 1];
3497 if (Next == '$' || Next == 'n' ||
3498 isdigit(static_cast<unsigned char>(Next)))
3502 // Check if we reached the end.
3506 if (Body[Pos] == '$') {
3507 switch (Body[Pos + 1]) {
3512 // $n => number of arguments
3514 PositionalParametersFound = true;
3517 // $[0-9] => argument
3519 PositionalParametersFound = true;
3525 unsigned I = Pos + 1;
3526 while (isIdentifierChar(Body[I]) && I + 1 != End)
3529 const char *Begin = Body.data() + Pos + 1;
3530 StringRef Argument(Begin, I - (Pos + 1));
3532 for (; Index < NParameters; ++Index)
3533 if (Parameters[Index].Name == Argument)
3536 if (Index == NParameters) {
3537 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3543 NamedParametersFound = true;
3544 Pos += 1 + Argument.size();
3547 // Update the scan point.
3548 Body = Body.substr(Pos);
3551 if (!NamedParametersFound && PositionalParametersFound)
3552 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3553 "used in macro body, possible positional parameter "
3554 "found in body which will have no effect");
3557 /// parseDirectiveExitMacro
3559 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3560 if (getLexer().isNot(AsmToken::EndOfStatement))
3561 return TokError("unexpected token in '" + Directive + "' directive");
3563 if (!isInsideMacroInstantiation())
3564 return TokError("unexpected '" + Directive + "' in file, "
3565 "no current macro definition");
3567 // Exit all conditionals that are active in the current macro.
3568 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3569 TheCondState = TheCondStack.back();
3570 TheCondStack.pop_back();
3577 /// parseDirectiveEndMacro
3580 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3581 if (getLexer().isNot(AsmToken::EndOfStatement))
3582 return TokError("unexpected token in '" + Directive + "' directive");
3584 // If we are inside a macro instantiation, terminate the current
3586 if (isInsideMacroInstantiation()) {
3591 // Otherwise, this .endmacro is a stray entry in the file; well formed
3592 // .endmacro directives are handled during the macro definition parsing.
3593 return TokError("unexpected '" + Directive + "' in file, "
3594 "no current macro definition");
3597 /// parseDirectivePurgeMacro
3599 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3601 if (parseIdentifier(Name))
3602 return TokError("expected identifier in '.purgem' directive");
3604 if (getLexer().isNot(AsmToken::EndOfStatement))
3605 return TokError("unexpected token in '.purgem' directive");
3607 if (!lookupMacro(Name))
3608 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3610 undefineMacro(Name);
3614 /// parseDirectiveBundleAlignMode
3615 /// ::= {.bundle_align_mode} expression
3616 bool AsmParser::parseDirectiveBundleAlignMode() {
3617 checkForValidSection();
3619 // Expect a single argument: an expression that evaluates to a constant
3620 // in the inclusive range 0-30.
3621 SMLoc ExprLoc = getLexer().getLoc();
3622 int64_t AlignSizePow2;
3623 if (parseAbsoluteExpression(AlignSizePow2))
3625 else if (getLexer().isNot(AsmToken::EndOfStatement))
3626 return TokError("unexpected token after expression in"
3627 " '.bundle_align_mode' directive");
3628 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3629 return Error(ExprLoc,
3630 "invalid bundle alignment size (expected between 0 and 30)");
3634 // Because of AlignSizePow2's verified range we can safely truncate it to
3636 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3640 /// parseDirectiveBundleLock
3641 /// ::= {.bundle_lock} [align_to_end]
3642 bool AsmParser::parseDirectiveBundleLock() {
3643 checkForValidSection();
3644 bool AlignToEnd = false;
3646 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3648 SMLoc Loc = getTok().getLoc();
3649 const char *kInvalidOptionError =
3650 "invalid option for '.bundle_lock' directive";
3652 if (parseIdentifier(Option))
3653 return Error(Loc, kInvalidOptionError);
3655 if (Option != "align_to_end")
3656 return Error(Loc, kInvalidOptionError);
3657 else if (getLexer().isNot(AsmToken::EndOfStatement))
3659 "unexpected token after '.bundle_lock' directive option");
3665 getStreamer().EmitBundleLock(AlignToEnd);
3669 /// parseDirectiveBundleLock
3670 /// ::= {.bundle_lock}
3671 bool AsmParser::parseDirectiveBundleUnlock() {
3672 checkForValidSection();
3674 if (getLexer().isNot(AsmToken::EndOfStatement))
3675 return TokError("unexpected token in '.bundle_unlock' directive");
3678 getStreamer().EmitBundleUnlock();
3682 /// parseDirectiveSpace
3683 /// ::= (.skip | .space) expression [ , expression ]
3684 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3685 checkForValidSection();
3688 if (parseAbsoluteExpression(NumBytes))
3691 int64_t FillExpr = 0;
3692 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3693 if (getLexer().isNot(AsmToken::Comma))
3694 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3697 if (parseAbsoluteExpression(FillExpr))
3700 if (getLexer().isNot(AsmToken::EndOfStatement))
3701 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3707 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3710 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3711 getStreamer().EmitFill(NumBytes, FillExpr);
3716 /// parseDirectiveLEB128
3717 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3718 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3719 checkForValidSection();
3720 const MCExpr *Value;
3723 if (parseExpression(Value))
3727 getStreamer().EmitSLEB128Value(Value);
3729 getStreamer().EmitULEB128Value(Value);
3731 if (getLexer().is(AsmToken::EndOfStatement))
3734 if (getLexer().isNot(AsmToken::Comma))
3735 return TokError("unexpected token in directive");
3742 /// parseDirectiveSymbolAttribute
3743 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3744 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3745 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3748 SMLoc Loc = getTok().getLoc();
3750 if (parseIdentifier(Name))
3751 return Error(Loc, "expected identifier in directive");
3753 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3755 // Assembler local symbols don't make any sense here. Complain loudly.
3756 if (Sym->isTemporary())
3757 return Error(Loc, "non-local symbol required in directive");
3759 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3760 return Error(Loc, "unable to emit symbol attribute");
3762 if (getLexer().is(AsmToken::EndOfStatement))
3765 if (getLexer().isNot(AsmToken::Comma))
3766 return TokError("unexpected token in directive");
3775 /// parseDirectiveComm
3776 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3777 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3778 checkForValidSection();
3780 SMLoc IDLoc = getLexer().getLoc();
3782 if (parseIdentifier(Name))
3783 return TokError("expected identifier in directive");
3785 // Handle the identifier as the key symbol.
3786 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3788 if (getLexer().isNot(AsmToken::Comma))
3789 return TokError("unexpected token in directive");
3793 SMLoc SizeLoc = getLexer().getLoc();
3794 if (parseAbsoluteExpression(Size))
3797 int64_t Pow2Alignment = 0;
3798 SMLoc Pow2AlignmentLoc;
3799 if (getLexer().is(AsmToken::Comma)) {
3801 Pow2AlignmentLoc = getLexer().getLoc();
3802 if (parseAbsoluteExpression(Pow2Alignment))
3805 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3806 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3807 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3809 // If this target takes alignments in bytes (not log) validate and convert.
3810 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3811 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3812 if (!isPowerOf2_64(Pow2Alignment))
3813 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3814 Pow2Alignment = Log2_64(Pow2Alignment);
3818 if (getLexer().isNot(AsmToken::EndOfStatement))
3819 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3823 // NOTE: a size of zero for a .comm should create a undefined symbol
3824 // but a size of .lcomm creates a bss symbol of size zero.
3826 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3827 "be less than zero");
3829 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3830 // may internally end up wanting an alignment in bytes.
3831 // FIXME: Diagnose overflow.
3832 if (Pow2Alignment < 0)
3833 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3834 "alignment, can't be less than zero");
3836 if (!Sym->isUndefined())
3837 return Error(IDLoc, "invalid symbol redefinition");
3839 // Create the Symbol as a common or local common with Size and Pow2Alignment
3841 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3845 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3849 /// parseDirectiveAbort
3850 /// ::= .abort [... message ...]
3851 bool AsmParser::parseDirectiveAbort() {
3852 // FIXME: Use loc from directive.
3853 SMLoc Loc = getLexer().getLoc();
3855 StringRef Str = parseStringToEndOfStatement();
3856 if (getLexer().isNot(AsmToken::EndOfStatement))
3857 return TokError("unexpected token in '.abort' directive");
3862 Error(Loc, ".abort detected. Assembly stopping.");
3864 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3865 // FIXME: Actually abort assembly here.
3870 /// parseDirectiveInclude
3871 /// ::= .include "filename"
3872 bool AsmParser::parseDirectiveInclude() {
3873 if (getLexer().isNot(AsmToken::String))
3874 return TokError("expected string in '.include' directive");
3876 // Allow the strings to have escaped octal character sequence.
3877 std::string Filename;
3878 if (parseEscapedString(Filename))
3880 SMLoc IncludeLoc = getLexer().getLoc();
3883 if (getLexer().isNot(AsmToken::EndOfStatement))
3884 return TokError("unexpected token in '.include' directive");
3886 // Attempt to switch the lexer to the included file before consuming the end
3887 // of statement to avoid losing it when we switch.
3888 if (enterIncludeFile(Filename)) {
3889 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3896 /// parseDirectiveIncbin
3897 /// ::= .incbin "filename"
3898 bool AsmParser::parseDirectiveIncbin() {
3899 if (getLexer().isNot(AsmToken::String))
3900 return TokError("expected string in '.incbin' directive");
3902 // Allow the strings to have escaped octal character sequence.
3903 std::string Filename;
3904 if (parseEscapedString(Filename))
3906 SMLoc IncbinLoc = getLexer().getLoc();
3909 if (getLexer().isNot(AsmToken::EndOfStatement))
3910 return TokError("unexpected token in '.incbin' directive");
3912 // Attempt to process the included file.
3913 if (processIncbinFile(Filename)) {
3914 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3921 /// parseDirectiveIf
3922 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3923 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3924 TheCondStack.push_back(TheCondState);
3925 TheCondState.TheCond = AsmCond::IfCond;
3926 if (TheCondState.Ignore) {
3927 eatToEndOfStatement();
3930 if (parseAbsoluteExpression(ExprValue))
3933 if (getLexer().isNot(AsmToken::EndOfStatement))
3934 return TokError("unexpected token in '.if' directive");
3940 llvm_unreachable("unsupported directive");
3945 ExprValue = ExprValue == 0;
3948 ExprValue = ExprValue >= 0;
3951 ExprValue = ExprValue > 0;
3954 ExprValue = ExprValue <= 0;
3957 ExprValue = ExprValue < 0;
3961 TheCondState.CondMet = ExprValue;
3962 TheCondState.Ignore = !TheCondState.CondMet;
3968 /// parseDirectiveIfb
3970 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3971 TheCondStack.push_back(TheCondState);
3972 TheCondState.TheCond = AsmCond::IfCond;
3974 if (TheCondState.Ignore) {
3975 eatToEndOfStatement();
3977 StringRef Str = parseStringToEndOfStatement();
3979 if (getLexer().isNot(AsmToken::EndOfStatement))
3980 return TokError("unexpected token in '.ifb' directive");
3984 TheCondState.CondMet = ExpectBlank == Str.empty();
3985 TheCondState.Ignore = !TheCondState.CondMet;
3991 /// parseDirectiveIfc
3992 /// ::= .ifc string1, string2
3993 /// ::= .ifnc string1, string2
3994 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3995 TheCondStack.push_back(TheCondState);
3996 TheCondState.TheCond = AsmCond::IfCond;
3998 if (TheCondState.Ignore) {
3999 eatToEndOfStatement();
4001 StringRef Str1 = parseStringToComma();
4003 if (getLexer().isNot(AsmToken::Comma))
4004 return TokError("unexpected token in '.ifc' directive");
4008 StringRef Str2 = parseStringToEndOfStatement();
4010 if (getLexer().isNot(AsmToken::EndOfStatement))
4011 return TokError("unexpected token in '.ifc' directive");
4015 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4016 TheCondState.Ignore = !TheCondState.CondMet;
4022 /// parseDirectiveIfeqs
4023 /// ::= .ifeqs string1, string2
4024 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4025 if (Lexer.isNot(AsmToken::String)) {
4027 TokError("expected string parameter for '.ifeqs' directive");
4029 TokError("expected string parameter for '.ifnes' directive");
4030 eatToEndOfStatement();
4034 StringRef String1 = getTok().getStringContents();
4037 if (Lexer.isNot(AsmToken::Comma)) {
4039 TokError("expected comma after first string for '.ifeqs' directive");
4041 TokError("expected comma after first string for '.ifnes' directive");
4042 eatToEndOfStatement();
4048 if (Lexer.isNot(AsmToken::String)) {
4050 TokError("expected string parameter for '.ifeqs' directive");
4052 TokError("expected string parameter for '.ifnes' directive");
4053 eatToEndOfStatement();
4057 StringRef String2 = getTok().getStringContents();
4060 TheCondStack.push_back(TheCondState);
4061 TheCondState.TheCond = AsmCond::IfCond;
4062 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4063 TheCondState.Ignore = !TheCondState.CondMet;
4068 /// parseDirectiveIfdef
4069 /// ::= .ifdef symbol
4070 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4072 TheCondStack.push_back(TheCondState);
4073 TheCondState.TheCond = AsmCond::IfCond;
4075 if (TheCondState.Ignore) {
4076 eatToEndOfStatement();
4078 if (parseIdentifier(Name))
4079 return TokError("expected identifier after '.ifdef'");
4083 MCSymbol *Sym = getContext().lookupSymbol(Name);
4086 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4088 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4089 TheCondState.Ignore = !TheCondState.CondMet;
4095 /// parseDirectiveElseIf
4096 /// ::= .elseif expression
4097 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4098 if (TheCondState.TheCond != AsmCond::IfCond &&
4099 TheCondState.TheCond != AsmCond::ElseIfCond)
4100 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4102 TheCondState.TheCond = AsmCond::ElseIfCond;
4104 bool LastIgnoreState = false;
4105 if (!TheCondStack.empty())
4106 LastIgnoreState = TheCondStack.back().Ignore;
4107 if (LastIgnoreState || TheCondState.CondMet) {
4108 TheCondState.Ignore = true;
4109 eatToEndOfStatement();
4112 if (parseAbsoluteExpression(ExprValue))
4115 if (getLexer().isNot(AsmToken::EndOfStatement))
4116 return TokError("unexpected token in '.elseif' directive");
4119 TheCondState.CondMet = ExprValue;
4120 TheCondState.Ignore = !TheCondState.CondMet;
4126 /// parseDirectiveElse
4128 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4129 if (getLexer().isNot(AsmToken::EndOfStatement))
4130 return TokError("unexpected token in '.else' directive");
4134 if (TheCondState.TheCond != AsmCond::IfCond &&
4135 TheCondState.TheCond != AsmCond::ElseIfCond)
4136 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4138 TheCondState.TheCond = AsmCond::ElseCond;
4139 bool LastIgnoreState = false;
4140 if (!TheCondStack.empty())
4141 LastIgnoreState = TheCondStack.back().Ignore;
4142 if (LastIgnoreState || TheCondState.CondMet)
4143 TheCondState.Ignore = true;
4145 TheCondState.Ignore = false;
4150 /// parseDirectiveEnd
4152 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4153 if (getLexer().isNot(AsmToken::EndOfStatement))
4154 return TokError("unexpected token in '.end' directive");
4158 while (Lexer.isNot(AsmToken::Eof))
4164 /// parseDirectiveError
4166 /// ::= .error [string]
4167 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4168 if (!TheCondStack.empty()) {
4169 if (TheCondStack.back().Ignore) {
4170 eatToEndOfStatement();
4176 return Error(L, ".err encountered");
4178 StringRef Message = ".error directive invoked in source file";
4179 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4180 if (Lexer.isNot(AsmToken::String)) {
4181 TokError(".error argument must be a string");
4182 eatToEndOfStatement();
4186 Message = getTok().getStringContents();
4194 /// parseDirectiveWarning
4195 /// ::= .warning [string]
4196 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4197 if (!TheCondStack.empty()) {
4198 if (TheCondStack.back().Ignore) {
4199 eatToEndOfStatement();
4204 StringRef Message = ".warning directive invoked in source file";
4205 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4206 if (Lexer.isNot(AsmToken::String)) {
4207 TokError(".warning argument must be a string");
4208 eatToEndOfStatement();
4212 Message = getTok().getStringContents();
4216 Warning(L, Message);
4220 /// parseDirectiveEndIf
4222 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4223 if (getLexer().isNot(AsmToken::EndOfStatement))
4224 return TokError("unexpected token in '.endif' directive");
4228 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4229 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4231 if (!TheCondStack.empty()) {
4232 TheCondState = TheCondStack.back();
4233 TheCondStack.pop_back();
4239 void AsmParser::initializeDirectiveKindMap() {
4240 DirectiveKindMap[".set"] = DK_SET;
4241 DirectiveKindMap[".equ"] = DK_EQU;
4242 DirectiveKindMap[".equiv"] = DK_EQUIV;
4243 DirectiveKindMap[".ascii"] = DK_ASCII;
4244 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4245 DirectiveKindMap[".string"] = DK_STRING;
4246 DirectiveKindMap[".byte"] = DK_BYTE;
4247 DirectiveKindMap[".short"] = DK_SHORT;
4248 DirectiveKindMap[".value"] = DK_VALUE;
4249 DirectiveKindMap[".2byte"] = DK_2BYTE;
4250 DirectiveKindMap[".long"] = DK_LONG;
4251 DirectiveKindMap[".int"] = DK_INT;
4252 DirectiveKindMap[".4byte"] = DK_4BYTE;
4253 DirectiveKindMap[".quad"] = DK_QUAD;
4254 DirectiveKindMap[".8byte"] = DK_8BYTE;
4255 DirectiveKindMap[".octa"] = DK_OCTA;
4256 DirectiveKindMap[".single"] = DK_SINGLE;
4257 DirectiveKindMap[".float"] = DK_FLOAT;
4258 DirectiveKindMap[".double"] = DK_DOUBLE;
4259 DirectiveKindMap[".align"] = DK_ALIGN;
4260 DirectiveKindMap[".align32"] = DK_ALIGN32;
4261 DirectiveKindMap[".balign"] = DK_BALIGN;
4262 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4263 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4264 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4265 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4266 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4267 DirectiveKindMap[".org"] = DK_ORG;
4268 DirectiveKindMap[".fill"] = DK_FILL;
4269 DirectiveKindMap[".zero"] = DK_ZERO;
4270 DirectiveKindMap[".extern"] = DK_EXTERN;
4271 DirectiveKindMap[".globl"] = DK_GLOBL;
4272 DirectiveKindMap[".global"] = DK_GLOBAL;
4273 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4274 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4275 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4276 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4277 DirectiveKindMap[".reference"] = DK_REFERENCE;
4278 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4279 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4280 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4281 DirectiveKindMap[".comm"] = DK_COMM;
4282 DirectiveKindMap[".common"] = DK_COMMON;
4283 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4284 DirectiveKindMap[".abort"] = DK_ABORT;
4285 DirectiveKindMap[".include"] = DK_INCLUDE;
4286 DirectiveKindMap[".incbin"] = DK_INCBIN;
4287 DirectiveKindMap[".code16"] = DK_CODE16;
4288 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4289 DirectiveKindMap[".rept"] = DK_REPT;
4290 DirectiveKindMap[".rep"] = DK_REPT;
4291 DirectiveKindMap[".irp"] = DK_IRP;
4292 DirectiveKindMap[".irpc"] = DK_IRPC;
4293 DirectiveKindMap[".endr"] = DK_ENDR;
4294 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4295 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4296 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4297 DirectiveKindMap[".if"] = DK_IF;
4298 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4299 DirectiveKindMap[".ifge"] = DK_IFGE;
4300 DirectiveKindMap[".ifgt"] = DK_IFGT;
4301 DirectiveKindMap[".ifle"] = DK_IFLE;
4302 DirectiveKindMap[".iflt"] = DK_IFLT;
4303 DirectiveKindMap[".ifne"] = DK_IFNE;
4304 DirectiveKindMap[".ifb"] = DK_IFB;
4305 DirectiveKindMap[".ifnb"] = DK_IFNB;
4306 DirectiveKindMap[".ifc"] = DK_IFC;
4307 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4308 DirectiveKindMap[".ifnc"] = DK_IFNC;
4309 DirectiveKindMap[".ifnes"] = DK_IFNES;
4310 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4311 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4312 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4313 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4314 DirectiveKindMap[".else"] = DK_ELSE;
4315 DirectiveKindMap[".end"] = DK_END;
4316 DirectiveKindMap[".endif"] = DK_ENDIF;
4317 DirectiveKindMap[".skip"] = DK_SKIP;
4318 DirectiveKindMap[".space"] = DK_SPACE;
4319 DirectiveKindMap[".file"] = DK_FILE;
4320 DirectiveKindMap[".line"] = DK_LINE;
4321 DirectiveKindMap[".loc"] = DK_LOC;
4322 DirectiveKindMap[".stabs"] = DK_STABS;
4323 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4324 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4325 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4326 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4327 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4328 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4329 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4330 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4331 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4332 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4333 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4334 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4335 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4336 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4337 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4338 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4339 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4340 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4341 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4342 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4343 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4344 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4345 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4346 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4347 DirectiveKindMap[".macro"] = DK_MACRO;
4348 DirectiveKindMap[".exitm"] = DK_EXITM;
4349 DirectiveKindMap[".endm"] = DK_ENDM;
4350 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4351 DirectiveKindMap[".purgem"] = DK_PURGEM;
4352 DirectiveKindMap[".err"] = DK_ERR;
4353 DirectiveKindMap[".error"] = DK_ERROR;
4354 DirectiveKindMap[".warning"] = DK_WARNING;
4357 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4358 AsmToken EndToken, StartToken = getTok();
4360 unsigned NestLevel = 0;
4362 // Check whether we have reached the end of the file.
4363 if (getLexer().is(AsmToken::Eof)) {
4364 Error(DirectiveLoc, "no matching '.endr' in definition");
4368 if (Lexer.is(AsmToken::Identifier) &&
4369 (getTok().getIdentifier() == ".rept")) {
4373 // Otherwise, check whether we have reached the .endr.
4374 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4375 if (NestLevel == 0) {
4376 EndToken = getTok();
4378 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4379 TokError("unexpected token in '.endr' directive");
4387 // Otherwise, scan till the end of the statement.
4388 eatToEndOfStatement();
4391 const char *BodyStart = StartToken.getLoc().getPointer();
4392 const char *BodyEnd = EndToken.getLoc().getPointer();
4393 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4395 // We Are Anonymous.
4396 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4397 return &MacroLikeBodies.back();
4400 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4401 raw_svector_ostream &OS) {
4404 std::unique_ptr<MemoryBuffer> Instantiation =
4405 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4407 // Create the macro instantiation object and add to the current macro
4408 // instantiation stack.
4409 MacroInstantiation *MI = new MacroInstantiation(
4410 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4411 ActiveMacros.push_back(MI);
4413 // Jump to the macro instantiation and prime the lexer.
4414 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4415 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4419 /// parseDirectiveRept
4420 /// ::= .rep | .rept count
4421 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4422 const MCExpr *CountExpr;
4423 SMLoc CountLoc = getTok().getLoc();
4424 if (parseExpression(CountExpr))
4428 if (!CountExpr->evaluateAsAbsolute(Count)) {
4429 eatToEndOfStatement();
4430 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4434 return Error(CountLoc, "Count is negative");
4436 if (Lexer.isNot(AsmToken::EndOfStatement))
4437 return TokError("unexpected token in '" + Dir + "' directive");
4439 // Eat the end of statement.
4442 // Lex the rept definition.
4443 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4447 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4448 // to hold the macro body with substitutions.
4449 SmallString<256> Buf;
4450 raw_svector_ostream OS(Buf);
4452 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4453 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4456 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4461 /// parseDirectiveIrp
4462 /// ::= .irp symbol,values
4463 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4464 MCAsmMacroParameter Parameter;
4466 if (parseIdentifier(Parameter.Name))
4467 return TokError("expected identifier in '.irp' directive");
4469 if (Lexer.isNot(AsmToken::Comma))
4470 return TokError("expected comma in '.irp' directive");
4474 MCAsmMacroArguments A;
4475 if (parseMacroArguments(nullptr, A))
4478 // Eat the end of statement.
4481 // Lex the irp definition.
4482 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4486 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4487 // to hold the macro body with substitutions.
4488 SmallString<256> Buf;
4489 raw_svector_ostream OS(Buf);
4491 for (const MCAsmMacroArgument &Arg : A) {
4492 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4493 // This is undocumented, but GAS seems to support it.
4494 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4498 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4503 /// parseDirectiveIrpc
4504 /// ::= .irpc symbol,values
4505 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4506 MCAsmMacroParameter Parameter;
4508 if (parseIdentifier(Parameter.Name))
4509 return TokError("expected identifier in '.irpc' directive");
4511 if (Lexer.isNot(AsmToken::Comma))
4512 return TokError("expected comma in '.irpc' directive");
4516 MCAsmMacroArguments A;
4517 if (parseMacroArguments(nullptr, A))
4520 if (A.size() != 1 || A.front().size() != 1)
4521 return TokError("unexpected token in '.irpc' directive");
4523 // Eat the end of statement.
4526 // Lex the irpc definition.
4527 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4531 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4532 // to hold the macro body with substitutions.
4533 SmallString<256> Buf;
4534 raw_svector_ostream OS(Buf);
4536 StringRef Values = A.front().front().getString();
4537 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4538 MCAsmMacroArgument Arg;
4539 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4541 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4542 // This is undocumented, but GAS seems to support it.
4543 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4547 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4552 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4553 if (ActiveMacros.empty())
4554 return TokError("unmatched '.endr' directive");
4556 // The only .repl that should get here are the ones created by
4557 // instantiateMacroLikeBody.
4558 assert(getLexer().is(AsmToken::EndOfStatement));
4564 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4566 const MCExpr *Value;
4567 SMLoc ExprLoc = getLexer().getLoc();
4568 if (parseExpression(Value))
4570 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4572 return Error(ExprLoc, "unexpected expression in _emit");
4573 uint64_t IntValue = MCE->getValue();
4574 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
4575 return Error(ExprLoc, "literal value out of range for directive");
4577 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
4581 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4582 const MCExpr *Value;
4583 SMLoc ExprLoc = getLexer().getLoc();
4584 if (parseExpression(Value))
4586 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4588 return Error(ExprLoc, "unexpected expression in align");
4589 uint64_t IntValue = MCE->getValue();
4590 if (!isPowerOf2_64(IntValue))
4591 return Error(ExprLoc, "literal value not a power of two greater then zero");
4593 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
4597 // We are comparing pointers, but the pointers are relative to a single string.
4598 // Thus, this should always be deterministic.
4599 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4600 const AsmRewrite *AsmRewriteB) {
4601 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4603 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4606 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4607 // rewrite to the same location. Make sure the SizeDirective rewrite is
4608 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4609 // ensures the sort algorithm is stable.
4610 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4611 AsmRewritePrecedence[AsmRewriteB->Kind])
4614 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4615 AsmRewritePrecedence[AsmRewriteB->Kind])
4617 llvm_unreachable("Unstable rewrite sort.");
4620 bool AsmParser::parseMSInlineAsm(
4621 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4622 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4623 SmallVectorImpl<std::string> &Constraints,
4624 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4625 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4626 SmallVector<void *, 4> InputDecls;
4627 SmallVector<void *, 4> OutputDecls;
4628 SmallVector<bool, 4> InputDeclsAddressOf;
4629 SmallVector<bool, 4> OutputDeclsAddressOf;
4630 SmallVector<std::string, 4> InputConstraints;
4631 SmallVector<std::string, 4> OutputConstraints;
4632 SmallVector<unsigned, 4> ClobberRegs;
4634 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4639 // While we have input, parse each statement.
4640 unsigned InputIdx = 0;
4641 unsigned OutputIdx = 0;
4642 while (getLexer().isNot(AsmToken::Eof)) {
4643 ParseStatementInfo Info(&AsmStrRewrites);
4644 if (parseStatement(Info, &SI))
4647 if (Info.ParseError)
4650 if (Info.Opcode == ~0U)
4653 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4655 // Build the list of clobbers, outputs and inputs.
4656 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4657 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4660 if (Operand.isImm())
4663 // Register operand.
4664 if (Operand.isReg() && !Operand.needAddressOf() &&
4665 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4666 unsigned NumDefs = Desc.getNumDefs();
4668 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4669 ClobberRegs.push_back(Operand.getReg());
4673 // Expr/Input or Output.
4674 StringRef SymName = Operand.getSymName();
4675 if (SymName.empty())
4678 void *OpDecl = Operand.getOpDecl();
4682 bool isOutput = (i == 1) && Desc.mayStore();
4683 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4686 OutputDecls.push_back(OpDecl);
4687 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4688 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4689 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
4691 InputDecls.push_back(OpDecl);
4692 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4693 InputConstraints.push_back(Operand.getConstraint().str());
4694 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
4698 // Consider implicit defs to be clobbers. Think of cpuid and push.
4699 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4700 Desc.getNumImplicitDefs());
4701 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4704 // Set the number of Outputs and Inputs.
4705 NumOutputs = OutputDecls.size();
4706 NumInputs = InputDecls.size();
4708 // Set the unique clobbers.
4709 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4710 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4712 Clobbers.assign(ClobberRegs.size(), std::string());
4713 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4714 raw_string_ostream OS(Clobbers[I]);
4715 IP->printRegName(OS, ClobberRegs[I]);
4718 // Merge the various outputs and inputs. Output are expected first.
4719 if (NumOutputs || NumInputs) {
4720 unsigned NumExprs = NumOutputs + NumInputs;
4721 OpDecls.resize(NumExprs);
4722 Constraints.resize(NumExprs);
4723 for (unsigned i = 0; i < NumOutputs; ++i) {
4724 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4725 Constraints[i] = OutputConstraints[i];
4727 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4728 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4729 Constraints[j] = InputConstraints[i];
4733 // Build the IR assembly string.
4734 std::string AsmStringIR;
4735 raw_string_ostream OS(AsmStringIR);
4736 StringRef ASMString =
4737 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4738 const char *AsmStart = ASMString.begin();
4739 const char *AsmEnd = ASMString.end();
4740 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4741 for (const AsmRewrite &AR : AsmStrRewrites) {
4742 AsmRewriteKind Kind = AR.Kind;
4743 if (Kind == AOK_Delete)
4746 const char *Loc = AR.Loc.getPointer();
4747 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4749 // Emit everything up to the immediate/expression.
4750 if (unsigned Len = Loc - AsmStart)
4751 OS << StringRef(AsmStart, Len);
4753 // Skip the original expression.
4754 if (Kind == AOK_Skip) {
4755 AsmStart = Loc + AR.Len;
4759 unsigned AdditionalSkip = 0;
4760 // Rewrite expressions in $N notation.
4765 OS << "$$" << AR.Val;
4771 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4774 OS << '$' << InputIdx++;
4777 OS << '$' << OutputIdx++;
4779 case AOK_SizeDirective:
4782 case 8: OS << "byte ptr "; break;
4783 case 16: OS << "word ptr "; break;
4784 case 32: OS << "dword ptr "; break;
4785 case 64: OS << "qword ptr "; break;
4786 case 80: OS << "xword ptr "; break;
4787 case 128: OS << "xmmword ptr "; break;
4788 case 256: OS << "ymmword ptr "; break;
4795 unsigned Val = AR.Val;
4796 OS << ".align " << Val;
4798 // Skip the original immediate.
4799 assert(Val < 10 && "Expected alignment less then 2^10.");
4800 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4803 case AOK_DotOperator:
4804 // Insert the dot if the user omitted it.
4806 if (AsmStringIR.back() != '.')
4812 // Skip the original expression.
4813 AsmStart = Loc + AR.Len + AdditionalSkip;
4816 // Emit the remainder of the asm string.
4817 if (AsmStart != AsmEnd)
4818 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4820 AsmString = OS.str();
4825 namespace MCParserUtils {
4827 /// Returns whether the given symbol is used anywhere in the given expression,
4828 /// or subexpressions.
4829 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4830 switch (Value->getKind()) {
4831 case MCExpr::Binary: {
4832 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4833 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4834 isSymbolUsedInExpression(Sym, BE->getRHS());
4836 case MCExpr::Target:
4837 case MCExpr::Constant:
4839 case MCExpr::SymbolRef: {
4841 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4843 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4847 return isSymbolUsedInExpression(
4848 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4851 llvm_unreachable("Unknown expr kind!");
4854 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4855 MCAsmParser &Parser, MCSymbol *&Sym,
4856 const MCExpr *&Value) {
4857 MCAsmLexer &Lexer = Parser.getLexer();
4859 // FIXME: Use better location, we should use proper tokens.
4860 SMLoc EqualLoc = Lexer.getLoc();
4862 if (Parser.parseExpression(Value)) {
4863 Parser.TokError("missing expression");
4864 Parser.eatToEndOfStatement();
4868 // Note: we don't count b as used in "a = b". This is to allow
4872 if (Lexer.isNot(AsmToken::EndOfStatement))
4873 return Parser.TokError("unexpected token in assignment");
4875 // Eat the end of statement marker.
4878 // Validate that the LHS is allowed to be a variable (either it has not been
4879 // used as a symbol, or it is an absolute symbol).
4880 Sym = Parser.getContext().lookupSymbol(Name);
4882 // Diagnose assignment to a label.
4884 // FIXME: Diagnostics. Note the location of the definition as a label.
4885 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4886 if (isSymbolUsedInExpression(Sym, Value))
4887 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4888 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
4890 ; // Allow redefinitions of undefined symbols only used in directives.
4891 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4892 ; // Allow redefinitions of variables that haven't yet been used.
4893 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4894 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4895 else if (!Sym->isVariable())
4896 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4897 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4898 return Parser.Error(EqualLoc,
4899 "invalid reassignment of non-absolute variable '" +
4901 } else if (Name == ".") {
4902 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4903 Parser.Error(EqualLoc, "expected absolute expression");
4904 Parser.eatToEndOfStatement();
4909 Sym = Parser.getContext().getOrCreateSymbol(Name);
4911 Sym->setRedefinable(allow_redef);
4916 } // namespace MCParserUtils
4919 /// \brief Create an MCAsmParser instance.
4920 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4921 MCStreamer &Out, const MCAsmInfo &MAI) {
4922 return new AsmParser(SM, C, Out, MAI);