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/MCParser/MCTargetAsmParser.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSectionMachO.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCValue.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"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
156 /// The values from the last parsed cpp hash file line comment if any.
157 struct CppHashInfoTy {
159 int64_t LineNumber = 0;
163 CppHashInfoTy CppHashInfo;
165 /// \brief List of forward directional labels for diagnosis at the end.
166 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
168 /// When generating dwarf for assembly source files we need to calculate the
169 /// logical line number based on the last parsed cpp hash file line comment
170 /// and current line. Since this is slow and messes up the SourceMgr's
171 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
172 SMLoc LastQueryIDLoc;
173 unsigned LastQueryBuffer;
174 unsigned LastQueryLine;
176 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
177 unsigned AssemblerDialect;
179 /// \brief is Darwin compatibility enabled?
182 /// \brief Are we parsing ms-style inline assembly?
183 bool ParsingInlineAsm;
186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
187 const MCAsmInfo &MAI);
188 ~AsmParser() override;
190 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
192 void addDirectiveHandler(StringRef Directive,
193 ExtensionDirectiveHandler Handler) override {
194 ExtensionDirectiveMap[Directive] = Handler;
197 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
198 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
202 /// @name MCAsmParser Interface
205 SourceMgr &getSourceManager() override { return SrcMgr; }
206 MCAsmLexer &getLexer() override { return Lexer; }
207 MCContext &getContext() override { return Ctx; }
208 MCStreamer &getStreamer() override { return Out; }
209 unsigned getAssemblerDialect() override {
210 if (AssemblerDialect == ~0U)
211 return MAI.getAssemblerDialect();
213 return AssemblerDialect;
215 void setAssemblerDialect(unsigned i) override {
216 AssemblerDialect = i;
219 void Note(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None) override;
221 bool Warning(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None) override;
223 bool Error(SMLoc L, const Twine &Msg,
224 ArrayRef<SMRange> Ranges = None) override;
226 const AsmToken &Lex() override;
228 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
229 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
231 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
232 unsigned &NumOutputs, unsigned &NumInputs,
233 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
234 SmallVectorImpl<std::string> &Constraints,
235 SmallVectorImpl<std::string> &Clobbers,
236 const MCInstrInfo *MII, const MCInstPrinter *IP,
237 MCAsmParserSemaCallback &SI) override;
239 bool parseExpression(const MCExpr *&Res);
240 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
243 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
244 SMLoc &EndLoc) override;
245 bool parseAbsoluteExpression(int64_t &Res) override;
247 /// \brief Parse an identifier or string (as a quoted identifier)
248 /// and set \p Res to the identifier contents.
249 bool parseIdentifier(StringRef &Res) override;
250 void eatToEndOfStatement() override;
252 void checkForValidSection() override;
254 bool getTokenLoc(SMLoc &Loc) {
255 Loc = getTok().getLoc();
259 /// parseToken - If current token has the specified kind, eat it and
260 /// return success. Otherwise, emit the specified error and return failure.
261 bool parseToken(AsmToken::TokenKind T, const Twine &ErrMsg) {
262 if (getTok().getKind() != T)
263 return TokError(ErrMsg);
268 bool parseIntToken(int64_t &V, const Twine &ErrMsg) {
269 if (getTok().getKind() != AsmToken::Integer)
270 return TokError(ErrMsg);
271 V = getTok().getIntVal();
280 bool parseStatement(ParseStatementInfo &Info,
281 MCAsmParserSemaCallback *SI);
282 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
283 bool parseCppHashLineFilenameComment(SMLoc L);
285 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
286 ArrayRef<MCAsmMacroParameter> Parameters);
287 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
288 ArrayRef<MCAsmMacroParameter> Parameters,
289 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
292 /// \brief Are macros enabled in the parser?
293 bool areMacrosEnabled() {return MacrosEnabledFlag;}
295 /// \brief Control a flag in the parser that enables or disables macros.
296 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
298 /// \brief Lookup a previously defined macro.
299 /// \param Name Macro name.
300 /// \returns Pointer to macro. NULL if no such macro was defined.
301 const MCAsmMacro* lookupMacro(StringRef Name);
303 /// \brief Define a new macro with the given name and information.
304 void defineMacro(StringRef Name, MCAsmMacro Macro);
306 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
307 void undefineMacro(StringRef Name);
309 /// \brief Are we inside a macro instantiation?
310 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
312 /// \brief Handle entry to macro instantiation.
314 /// \param M The macro.
315 /// \param NameLoc Instantiation location.
316 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
318 /// \brief Handle exit from macro instantiation.
319 void handleMacroExit();
321 /// \brief Extract AsmTokens for a macro argument.
322 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
324 /// \brief Parse all macro arguments for a given macro.
325 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
327 void printMacroInstantiations();
328 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
329 ArrayRef<SMRange> Ranges = None) const {
330 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
332 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
334 bool check(bool P, SMLoc Loc, const Twine &Msg) {
336 return Error(Loc, Msg);
340 bool check(bool P, const Twine &Msg) {
342 return TokError(Msg);
346 /// \brief Enter the specified file. This returns true on failure.
347 bool enterIncludeFile(const std::string &Filename);
349 /// \brief Process the specified file for the .incbin directive.
350 /// This returns true on failure.
351 bool processIncbinFile(const std::string &Filename);
353 /// \brief Reset the current lexer position to that given by \p Loc. The
354 /// current token is not set; clients should ensure Lex() is called
357 /// \param InBuffer If not 0, should be the known buffer id that contains the
359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
364 StringRef parseStringToEndOfStatement() override;
366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
368 StringRef parseStringToComma();
370 bool parseAssignment(StringRef Name, bool allow_redef,
371 bool NoDeadStrip = false);
373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
382 // Generic (target and platform independent) directive parsing.
384 DK_NO_DIRECTIVE, // Placeholder
385 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
387 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
388 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
389 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
390 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
391 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
392 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
393 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
394 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
395 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
396 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
397 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
398 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
399 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
400 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
401 DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
402 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
403 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
404 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
405 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
406 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
407 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
408 DK_MACROS_ON, DK_MACROS_OFF,
409 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
410 DK_SLEB128, DK_ULEB128,
411 DK_ERR, DK_ERROR, DK_WARNING,
415 /// \brief Maps directive name --> DirectiveKind enum, for
416 /// directives parsed by this class.
417 StringMap<DirectiveKind> DirectiveKindMap;
419 // ".ascii", ".asciz", ".string"
420 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
421 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
422 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
423 bool parseDirectiveOctaValue(); // ".octa"
424 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
425 bool parseDirectiveFill(); // ".fill"
426 bool parseDirectiveZero(); // ".zero"
427 // ".set", ".equ", ".equiv"
428 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
429 bool parseDirectiveOrg(); // ".org"
430 // ".align{,32}", ".p2align{,w,l}"
431 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
433 // ".file", ".line", ".loc", ".stabs"
434 bool parseDirectiveFile(SMLoc DirectiveLoc);
435 bool parseDirectiveLine();
436 bool parseDirectiveLoc();
437 bool parseDirectiveStabs();
439 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
441 bool parseDirectiveCVFile();
442 bool parseDirectiveCVLoc();
443 bool parseDirectiveCVLinetable();
444 bool parseDirectiveCVInlineLinetable();
445 bool parseDirectiveCVDefRange();
446 bool parseDirectiveCVStringTable();
447 bool parseDirectiveCVFileChecksums();
450 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
451 bool parseDirectiveCFIWindowSave();
452 bool parseDirectiveCFISections();
453 bool parseDirectiveCFIStartProc();
454 bool parseDirectiveCFIEndProc();
455 bool parseDirectiveCFIDefCfaOffset();
456 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
457 bool parseDirectiveCFIAdjustCfaOffset();
458 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
459 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
460 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
461 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
462 bool parseDirectiveCFIRememberState();
463 bool parseDirectiveCFIRestoreState();
464 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
465 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
466 bool parseDirectiveCFIEscape();
467 bool parseDirectiveCFISignalFrame();
468 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
471 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
472 bool parseDirectiveExitMacro(StringRef Directive);
473 bool parseDirectiveEndMacro(StringRef Directive);
474 bool parseDirectiveMacro(SMLoc DirectiveLoc);
475 bool parseDirectiveMacrosOnOff(StringRef Directive);
477 // ".bundle_align_mode"
478 bool parseDirectiveBundleAlignMode();
480 bool parseDirectiveBundleLock();
482 bool parseDirectiveBundleUnlock();
485 bool parseDirectiveSpace(StringRef IDVal);
487 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
488 bool parseDirectiveLEB128(bool Signed);
490 /// \brief Parse a directive like ".globl" which
491 /// accepts a single symbol (which should be a label or an external).
492 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
494 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
496 bool parseDirectiveAbort(); // ".abort"
497 bool parseDirectiveInclude(); // ".include"
498 bool parseDirectiveIncbin(); // ".incbin"
500 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
501 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
502 // ".ifb" or ".ifnb", depending on ExpectBlank.
503 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
504 // ".ifc" or ".ifnc", depending on ExpectEqual.
505 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
506 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
507 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
508 // ".ifdef" or ".ifndef", depending on expect_defined
509 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
510 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
511 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
512 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
513 bool parseEscapedString(std::string &Data) override;
515 const MCExpr *applyModifierToExpr(const MCExpr *E,
516 MCSymbolRefExpr::VariantKind Variant);
518 // Macro-like directives
519 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
520 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
521 raw_svector_ostream &OS);
522 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
523 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
524 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
525 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
527 // "_emit" or "__emit"
528 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
532 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
535 bool parseDirectiveEnd(SMLoc DirectiveLoc);
537 // ".err" or ".error"
538 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
541 bool parseDirectiveWarning(SMLoc DirectiveLoc);
543 void initializeDirectiveKindMap();
549 extern MCAsmParserExtension *createDarwinAsmParser();
550 extern MCAsmParserExtension *createELFAsmParser();
551 extern MCAsmParserExtension *createCOFFAsmParser();
555 enum { DEFAULT_ADDRSPACE = 0 };
557 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
558 const MCAsmInfo &MAI)
559 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
560 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
561 MacrosEnabledFlag(true), HadError(false), CppHashInfo(),
562 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
563 // Save the old handler.
564 SavedDiagHandler = SrcMgr.getDiagHandler();
565 SavedDiagContext = SrcMgr.getDiagContext();
566 // Set our own handler which calls the saved handler.
567 SrcMgr.setDiagHandler(DiagHandler, this);
568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
570 // Initialize the platform / file format parser.
571 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
572 case MCObjectFileInfo::IsCOFF:
573 PlatformParser.reset(createCOFFAsmParser());
575 case MCObjectFileInfo::IsMachO:
576 PlatformParser.reset(createDarwinAsmParser());
579 case MCObjectFileInfo::IsELF:
580 PlatformParser.reset(createELFAsmParser());
584 PlatformParser->Initialize(*this);
585 initializeDirectiveKindMap();
587 NumOfMacroInstantiations = 0;
590 AsmParser::~AsmParser() {
591 assert((HadError || ActiveMacros.empty()) &&
592 "Unexpected active macro instantiation!");
595 void AsmParser::printMacroInstantiations() {
596 // Print the active macro instantiation stack.
597 for (std::vector<MacroInstantiation *>::const_reverse_iterator
598 it = ActiveMacros.rbegin(),
599 ie = ActiveMacros.rend();
601 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
602 "while in macro instantiation");
605 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
606 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
607 printMacroInstantiations();
610 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
611 if(getTargetParser().getTargetOptions().MCNoWarn)
613 if (getTargetParser().getTargetOptions().MCFatalWarnings)
614 return Error(L, Msg, Ranges);
615 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
616 printMacroInstantiations();
620 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
622 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
623 printMacroInstantiations();
627 bool AsmParser::enterIncludeFile(const std::string &Filename) {
628 std::string IncludedFile;
630 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
635 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
639 /// Process the specified .incbin file by searching for it in the include paths
640 /// then just emitting the byte contents of the file to the streamer. This
641 /// returns true on failure.
642 bool AsmParser::processIncbinFile(const std::string &Filename) {
643 std::string IncludedFile;
645 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
649 // Pick up the bytes from the file and emit them.
650 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
654 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
655 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
656 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
660 const AsmToken &AsmParser::Lex() {
661 if (Lexer.getTok().is(AsmToken::Error))
662 Error(Lexer.getErrLoc(), Lexer.getErr());
664 // if it's a end of statement with a comment in it
665 if (getTok().is(AsmToken::EndOfStatement)) {
666 // if this is a line comment output it.
667 if (getTok().getString().front() != '\n' &&
668 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
669 Out.addExplicitComment(Twine(getTok().getString()));
672 const AsmToken *tok = &Lexer.Lex();
674 // Parse comments here to be deferred until end of next statement.
675 while (tok->is(AsmToken::Comment)) {
676 if (MAI.preserveAsmComments())
677 Out.addExplicitComment(Twine(tok->getString()));
681 if (tok->is(AsmToken::Eof)) {
682 // If this is the end of an included file, pop the parent file off the
684 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
685 if (ParentIncludeLoc != SMLoc()) {
686 jumpToLoc(ParentIncludeLoc);
695 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
696 // Create the initial section, if requested.
697 if (!NoInitialTextSection)
698 Out.InitSections(false);
704 AsmCond StartingCondState = TheCondState;
706 // If we are generating dwarf for assembly source files save the initial text
707 // section and generate a .file directive.
708 if (getContext().getGenDwarfForAssembly()) {
709 MCSection *Sec = getStreamer().getCurrentSection().first;
710 if (!Sec->getBeginSymbol()) {
711 MCSymbol *SectionStartSym = getContext().createTempSymbol();
712 getStreamer().EmitLabel(SectionStartSym);
713 Sec->setBeginSymbol(SectionStartSym);
715 bool InsertResult = getContext().addGenDwarfSection(Sec);
716 assert(InsertResult && ".text section should not have debug info yet");
718 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
719 0, StringRef(), getContext().getMainFileName()));
722 // While we have input, parse each statement.
723 while (Lexer.isNot(AsmToken::Eof)) {
724 ParseStatementInfo Info;
725 if (!parseStatement(Info, nullptr))
728 // If we've failed, but on a Error Token, but did not consume it in
729 // favor of a better message, emit it now.
730 if (Lexer.getTok().is(AsmToken::Error)) {
734 // We had an error, validate that one was emitted and recover by skipping to
736 assert(HadError && "Parse statement returned an error, but none emitted!");
737 eatToEndOfStatement();
740 if (TheCondState.TheCond != StartingCondState.TheCond ||
741 TheCondState.Ignore != StartingCondState.Ignore)
742 return TokError("unmatched .ifs or .elses");
744 // Check to see there are no empty DwarfFile slots.
745 const auto &LineTables = getContext().getMCDwarfLineTables();
746 if (!LineTables.empty()) {
748 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
749 if (File.Name.empty() && Index != 0)
750 TokError("unassigned file number: " + Twine(Index) +
751 " for .file directives");
756 // Check to see that all assembler local symbols were actually defined.
757 // Targets that don't do subsections via symbols may not want this, though,
758 // so conservatively exclude them. Only do this if we're finalizing, though,
759 // as otherwise we won't necessarilly have seen everything yet.
761 if (MAI.hasSubsectionsViaSymbols()) {
762 for (const auto &TableEntry : getContext().getSymbols()) {
763 MCSymbol *Sym = TableEntry.getValue();
764 // Variable symbols may not be marked as defined, so check those
765 // explicitly. If we know it's a variable, we have a definition for
766 // the purposes of this check.
767 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
768 // FIXME: We would really like to refer back to where the symbol was
769 // first referenced for a source location. We need to add something
770 // to track that. Currently, we just point to the end of the file.
772 Error(getTok().getLoc(), "assembler local symbol '" +
773 Sym->getName() + "' not defined");
777 // Temporary symbols like the ones for directional jumps don't go in the
778 // symbol table. They also need to be diagnosed in all (final) cases.
779 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
780 if (std::get<2>(LocSym)->isUndefined()) {
781 // Reset the state of any "# line file" directives we've seen to the
782 // context as it was at the diagnostic site.
783 CppHashInfo = std::get<1>(LocSym);
784 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
789 // Finalize the output stream if there are no errors and if the client wants
791 if (!HadError && !NoFinalize)
794 return HadError || getContext().hadError();
797 void AsmParser::checkForValidSection() {
798 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
799 TokError("expected section directive before assembly directive");
800 Out.InitSections(false);
804 /// \brief Throw away the rest of the line for testing purposes.
805 void AsmParser::eatToEndOfStatement() {
806 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
810 if (Lexer.is(AsmToken::EndOfStatement))
814 StringRef AsmParser::parseStringToEndOfStatement() {
815 const char *Start = getTok().getLoc().getPointer();
817 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
820 const char *End = getTok().getLoc().getPointer();
821 return StringRef(Start, End - Start);
824 StringRef AsmParser::parseStringToComma() {
825 const char *Start = getTok().getLoc().getPointer();
827 while (Lexer.isNot(AsmToken::EndOfStatement) &&
828 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
831 const char *End = getTok().getLoc().getPointer();
832 return StringRef(Start, End - Start);
835 /// \brief Parse a paren expression and return it.
836 /// NOTE: This assumes the leading '(' has already been consumed.
838 /// parenexpr ::= expr)
840 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
841 if (parseExpression(Res))
843 if (Lexer.isNot(AsmToken::RParen))
844 return TokError("expected ')' in parentheses expression");
845 EndLoc = Lexer.getTok().getEndLoc();
850 /// \brief Parse a bracket expression and return it.
851 /// NOTE: This assumes the leading '[' has already been consumed.
853 /// bracketexpr ::= expr]
855 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
856 if (parseExpression(Res))
858 EndLoc = getTok().getEndLoc();
859 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
864 /// \brief Parse a primary expression and return it.
865 /// primaryexpr ::= (parenexpr
866 /// primaryexpr ::= symbol
867 /// primaryexpr ::= number
868 /// primaryexpr ::= '.'
869 /// primaryexpr ::= ~,+,- primaryexpr
870 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
871 SMLoc FirstTokenLoc = getLexer().getLoc();
872 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
873 switch (FirstTokenKind) {
875 return TokError("unknown token in expression");
876 // If we have an error assume that we've already handled it.
877 case AsmToken::Error:
879 case AsmToken::Exclaim:
880 Lex(); // Eat the operator.
881 if (parsePrimaryExpr(Res, EndLoc))
883 Res = MCUnaryExpr::createLNot(Res, getContext());
885 case AsmToken::Dollar:
887 case AsmToken::String:
888 case AsmToken::Identifier: {
889 StringRef Identifier;
890 if (parseIdentifier(Identifier)) {
891 if (FirstTokenKind == AsmToken::Dollar) {
892 if (Lexer.getMAI().getDollarIsPC()) {
893 // This is a '$' reference, which references the current PC. Emit a
894 // temporary label to the streamer and refer to it.
895 MCSymbol *Sym = Ctx.createTempSymbol();
897 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
899 EndLoc = FirstTokenLoc;
902 return Error(FirstTokenLoc, "invalid token in expression");
905 // Parse symbol variant
906 std::pair<StringRef, StringRef> Split;
907 if (!MAI.useParensForSymbolVariant()) {
908 if (FirstTokenKind == AsmToken::String) {
909 if (Lexer.is(AsmToken::At)) {
911 SMLoc AtLoc = getLexer().getLoc();
913 if (parseIdentifier(VName))
914 return Error(AtLoc, "expected symbol variant after '@'");
916 Split = std::make_pair(Identifier, VName);
919 Split = Identifier.split('@');
921 } else if (Lexer.is(AsmToken::LParen)) {
924 parseIdentifier(VName);
926 if (parseToken(AsmToken::RParen,
927 "unexpected token in variant, expected ')'"))
929 Split = std::make_pair(Identifier, VName);
932 EndLoc = SMLoc::getFromPointer(Identifier.end());
934 // This is a symbol reference.
935 StringRef SymbolName = Identifier;
936 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
938 // Lookup the symbol variant if used.
939 if (Split.second.size()) {
940 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
941 if (Variant != MCSymbolRefExpr::VK_Invalid) {
942 SymbolName = Split.first;
943 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
944 Variant = MCSymbolRefExpr::VK_None;
946 return Error(SMLoc::getFromPointer(Split.second.begin()),
947 "invalid variant '" + Split.second + "'");
951 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
953 // If this is an absolute variable reference, substitute it now to preserve
954 // semantics in the face of reassignment.
955 if (Sym->isVariable() &&
956 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
958 return Error(EndLoc, "unexpected modifier on variable reference");
960 Res = Sym->getVariableValue(/*SetUsed*/ false);
964 // Otherwise create a symbol ref.
965 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
968 case AsmToken::BigNum:
969 return TokError("literal value out of range for directive");
970 case AsmToken::Integer: {
971 SMLoc Loc = getTok().getLoc();
972 int64_t IntVal = getTok().getIntVal();
973 Res = MCConstantExpr::create(IntVal, getContext());
974 EndLoc = Lexer.getTok().getEndLoc();
976 // Look for 'b' or 'f' following an Integer as a directional label
977 if (Lexer.getKind() == AsmToken::Identifier) {
978 StringRef IDVal = getTok().getString();
979 // Lookup the symbol variant if used.
980 std::pair<StringRef, StringRef> Split = IDVal.split('@');
981 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
982 if (Split.first.size() != IDVal.size()) {
983 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
984 if (Variant == MCSymbolRefExpr::VK_Invalid)
985 return TokError("invalid variant '" + Split.second + "'");
988 if (IDVal == "f" || IDVal == "b") {
990 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
991 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
992 if (IDVal == "b" && Sym->isUndefined())
993 return Error(Loc, "directional label undefined");
994 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
995 EndLoc = Lexer.getTok().getEndLoc();
996 Lex(); // Eat identifier.
1001 case AsmToken::Real: {
1002 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
1003 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1004 Res = MCConstantExpr::create(IntVal, getContext());
1005 EndLoc = Lexer.getTok().getEndLoc();
1006 Lex(); // Eat token.
1009 case AsmToken::Dot: {
1010 // This is a '.' reference, which references the current PC. Emit a
1011 // temporary label to the streamer and refer to it.
1012 MCSymbol *Sym = Ctx.createTempSymbol();
1014 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1015 EndLoc = Lexer.getTok().getEndLoc();
1016 Lex(); // Eat identifier.
1019 case AsmToken::LParen:
1020 Lex(); // Eat the '('.
1021 return parseParenExpr(Res, EndLoc);
1022 case AsmToken::LBrac:
1023 if (!PlatformParser->HasBracketExpressions())
1024 return TokError("brackets expression not supported on this target");
1025 Lex(); // Eat the '['.
1026 return parseBracketExpr(Res, EndLoc);
1027 case AsmToken::Minus:
1028 Lex(); // Eat the operator.
1029 if (parsePrimaryExpr(Res, EndLoc))
1031 Res = MCUnaryExpr::createMinus(Res, getContext());
1033 case AsmToken::Plus:
1034 Lex(); // Eat the operator.
1035 if (parsePrimaryExpr(Res, EndLoc))
1037 Res = MCUnaryExpr::createPlus(Res, getContext());
1039 case AsmToken::Tilde:
1040 Lex(); // Eat the operator.
1041 if (parsePrimaryExpr(Res, EndLoc))
1043 Res = MCUnaryExpr::createNot(Res, getContext());
1048 bool AsmParser::parseExpression(const MCExpr *&Res) {
1050 return parseExpression(Res, EndLoc);
1054 AsmParser::applyModifierToExpr(const MCExpr *E,
1055 MCSymbolRefExpr::VariantKind Variant) {
1056 // Ask the target implementation about this expression first.
1057 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1060 // Recurse over the given expression, rebuilding it to apply the given variant
1061 // if there is exactly one symbol.
1062 switch (E->getKind()) {
1063 case MCExpr::Target:
1064 case MCExpr::Constant:
1067 case MCExpr::SymbolRef: {
1068 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1070 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1071 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1072 "' (already modified)");
1076 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1079 case MCExpr::Unary: {
1080 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1081 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1084 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1087 case MCExpr::Binary: {
1088 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1089 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1090 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1100 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1104 llvm_unreachable("Invalid expression kind!");
1107 /// \brief Parse an expression and return it.
1109 /// expr ::= expr &&,|| expr -> lowest.
1110 /// expr ::= expr |,^,&,! expr
1111 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1112 /// expr ::= expr <<,>> expr
1113 /// expr ::= expr +,- expr
1114 /// expr ::= expr *,/,% expr -> highest.
1115 /// expr ::= primaryexpr
1117 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1118 // Parse the expression.
1120 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1123 // As a special case, we support 'a op b @ modifier' by rewriting the
1124 // expression to include the modifier. This is inefficient, but in general we
1125 // expect users to use 'a@modifier op b'.
1126 if (Lexer.getKind() == AsmToken::At) {
1129 if (Lexer.isNot(AsmToken::Identifier))
1130 return TokError("unexpected symbol modifier following '@'");
1132 MCSymbolRefExpr::VariantKind Variant =
1133 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1134 if (Variant == MCSymbolRefExpr::VK_Invalid)
1135 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1137 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1139 return TokError("invalid modifier '" + getTok().getIdentifier() +
1140 "' (no symbols present)");
1147 // Try to constant fold it up front, if possible.
1149 if (Res->evaluateAsAbsolute(Value))
1150 Res = MCConstantExpr::create(Value, getContext());
1155 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1157 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1160 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1162 if (parseParenExpr(Res, EndLoc))
1165 for (; ParenDepth > 0; --ParenDepth) {
1166 if (parseBinOpRHS(1, Res, EndLoc))
1169 // We don't Lex() the last RParen.
1170 // This is the same behavior as parseParenExpression().
1171 if (ParenDepth - 1 > 0) {
1172 EndLoc = getTok().getEndLoc();
1173 if (parseToken(AsmToken::RParen,
1174 "expected ')' in parentheses expression"))
1181 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1184 SMLoc StartLoc = Lexer.getLoc();
1185 if (parseExpression(Expr))
1188 if (!Expr->evaluateAsAbsolute(Res))
1189 return Error(StartLoc, "expected absolute expression");
1194 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1195 MCBinaryExpr::Opcode &Kind,
1196 bool ShouldUseLogicalShr) {
1199 return 0; // not a binop.
1201 // Lowest Precedence: &&, ||
1202 case AsmToken::AmpAmp:
1203 Kind = MCBinaryExpr::LAnd;
1205 case AsmToken::PipePipe:
1206 Kind = MCBinaryExpr::LOr;
1209 // Low Precedence: |, &, ^
1211 // FIXME: gas seems to support '!' as an infix operator?
1212 case AsmToken::Pipe:
1213 Kind = MCBinaryExpr::Or;
1215 case AsmToken::Caret:
1216 Kind = MCBinaryExpr::Xor;
1219 Kind = MCBinaryExpr::And;
1222 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1223 case AsmToken::EqualEqual:
1224 Kind = MCBinaryExpr::EQ;
1226 case AsmToken::ExclaimEqual:
1227 case AsmToken::LessGreater:
1228 Kind = MCBinaryExpr::NE;
1230 case AsmToken::Less:
1231 Kind = MCBinaryExpr::LT;
1233 case AsmToken::LessEqual:
1234 Kind = MCBinaryExpr::LTE;
1236 case AsmToken::Greater:
1237 Kind = MCBinaryExpr::GT;
1239 case AsmToken::GreaterEqual:
1240 Kind = MCBinaryExpr::GTE;
1243 // Intermediate Precedence: <<, >>
1244 case AsmToken::LessLess:
1245 Kind = MCBinaryExpr::Shl;
1247 case AsmToken::GreaterGreater:
1248 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1251 // High Intermediate Precedence: +, -
1252 case AsmToken::Plus:
1253 Kind = MCBinaryExpr::Add;
1255 case AsmToken::Minus:
1256 Kind = MCBinaryExpr::Sub;
1259 // Highest Precedence: *, /, %
1260 case AsmToken::Star:
1261 Kind = MCBinaryExpr::Mul;
1263 case AsmToken::Slash:
1264 Kind = MCBinaryExpr::Div;
1266 case AsmToken::Percent:
1267 Kind = MCBinaryExpr::Mod;
1272 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1273 MCBinaryExpr::Opcode &Kind,
1274 bool ShouldUseLogicalShr) {
1277 return 0; // not a binop.
1279 // Lowest Precedence: &&, ||
1280 case AsmToken::AmpAmp:
1281 Kind = MCBinaryExpr::LAnd;
1283 case AsmToken::PipePipe:
1284 Kind = MCBinaryExpr::LOr;
1287 // Low Precedence: ==, !=, <>, <, <=, >, >=
1288 case AsmToken::EqualEqual:
1289 Kind = MCBinaryExpr::EQ;
1291 case AsmToken::ExclaimEqual:
1292 case AsmToken::LessGreater:
1293 Kind = MCBinaryExpr::NE;
1295 case AsmToken::Less:
1296 Kind = MCBinaryExpr::LT;
1298 case AsmToken::LessEqual:
1299 Kind = MCBinaryExpr::LTE;
1301 case AsmToken::Greater:
1302 Kind = MCBinaryExpr::GT;
1304 case AsmToken::GreaterEqual:
1305 Kind = MCBinaryExpr::GTE;
1308 // Low Intermediate Precedence: +, -
1309 case AsmToken::Plus:
1310 Kind = MCBinaryExpr::Add;
1312 case AsmToken::Minus:
1313 Kind = MCBinaryExpr::Sub;
1316 // High Intermediate Precedence: |, &, ^
1318 // FIXME: gas seems to support '!' as an infix operator?
1319 case AsmToken::Pipe:
1320 Kind = MCBinaryExpr::Or;
1322 case AsmToken::Caret:
1323 Kind = MCBinaryExpr::Xor;
1326 Kind = MCBinaryExpr::And;
1329 // Highest Precedence: *, /, %, <<, >>
1330 case AsmToken::Star:
1331 Kind = MCBinaryExpr::Mul;
1333 case AsmToken::Slash:
1334 Kind = MCBinaryExpr::Div;
1336 case AsmToken::Percent:
1337 Kind = MCBinaryExpr::Mod;
1339 case AsmToken::LessLess:
1340 Kind = MCBinaryExpr::Shl;
1342 case AsmToken::GreaterGreater:
1343 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1348 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1349 MCBinaryExpr::Opcode &Kind) {
1350 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1351 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1352 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1355 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1356 /// Res contains the LHS of the expression on input.
1357 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1360 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1361 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1363 // If the next token is lower precedence than we are allowed to eat, return
1364 // successfully with what we ate already.
1365 if (TokPrec < Precedence)
1370 // Eat the next primary expression.
1372 if (parsePrimaryExpr(RHS, EndLoc))
1375 // If BinOp binds less tightly with RHS than the operator after RHS, let
1376 // the pending operator take RHS as its LHS.
1377 MCBinaryExpr::Opcode Dummy;
1378 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1379 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1382 // Merge LHS and RHS according to operator.
1383 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1388 /// ::= EndOfStatement
1389 /// ::= Label* Directive ...Operands... EndOfStatement
1390 /// ::= Label* Identifier OperandList* EndOfStatement
1391 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1392 MCAsmParserSemaCallback *SI) {
1393 // Eat initial spaces and comments
1394 while (Lexer.is(AsmToken::Space))
1396 if (Lexer.is(AsmToken::EndOfStatement)) {
1397 // if this is a line comment we can drop it safely
1398 if (getTok().getString().front() == '\r' ||
1399 getTok().getString().front() == '\n')
1404 // Statements always start with an identifier.
1405 AsmToken ID = getTok();
1406 SMLoc IDLoc = ID.getLoc();
1408 int64_t LocalLabelVal = -1;
1409 if (Lexer.is(AsmToken::HashDirective))
1410 return parseCppHashLineFilenameComment(IDLoc);
1411 // Allow an integer followed by a ':' as a directional local label.
1412 if (Lexer.is(AsmToken::Integer)) {
1413 LocalLabelVal = getTok().getIntVal();
1414 if (LocalLabelVal < 0) {
1415 if (!TheCondState.Ignore)
1416 return TokError("unexpected token at start of statement");
1419 IDVal = getTok().getString();
1420 Lex(); // Consume the integer token to be used as an identifier token.
1421 if (Lexer.getKind() != AsmToken::Colon) {
1422 if (!TheCondState.Ignore)
1423 return TokError("unexpected token at start of statement");
1426 } else if (Lexer.is(AsmToken::Dot)) {
1427 // Treat '.' as a valid identifier in this context.
1430 } else if (Lexer.is(AsmToken::LCurly)) {
1431 // Treat '{' as a valid identifier in this context.
1435 } else if (Lexer.is(AsmToken::RCurly)) {
1436 // Treat '}' as a valid identifier in this context.
1439 } else if (parseIdentifier(IDVal)) {
1440 if (!TheCondState.Ignore)
1441 return TokError("unexpected token at start of statement");
1445 // Handle conditional assembly here before checking for skipping. We
1446 // have to do this so that .endif isn't skipped in a ".if 0" block for
1448 StringMap<DirectiveKind>::const_iterator DirKindIt =
1449 DirectiveKindMap.find(IDVal);
1450 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1452 : DirKindIt->getValue();
1463 return parseDirectiveIf(IDLoc, DirKind);
1465 return parseDirectiveIfb(IDLoc, true);
1467 return parseDirectiveIfb(IDLoc, false);
1469 return parseDirectiveIfc(IDLoc, true);
1471 return parseDirectiveIfeqs(IDLoc, true);
1473 return parseDirectiveIfc(IDLoc, false);
1475 return parseDirectiveIfeqs(IDLoc, false);
1477 return parseDirectiveIfdef(IDLoc, true);
1480 return parseDirectiveIfdef(IDLoc, false);
1482 return parseDirectiveElseIf(IDLoc);
1484 return parseDirectiveElse(IDLoc);
1486 return parseDirectiveEndIf(IDLoc);
1489 // Ignore the statement if in the middle of inactive conditional
1491 if (TheCondState.Ignore) {
1492 eatToEndOfStatement();
1496 // FIXME: Recurse on local labels?
1498 // See what kind of statement we have.
1499 switch (Lexer.getKind()) {
1500 case AsmToken::Colon: {
1501 if (!getTargetParser().isLabel(ID))
1503 checkForValidSection();
1505 // identifier ':' -> Label.
1508 // Diagnose attempt to use '.' as a label.
1510 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1512 // Diagnose attempt to use a variable as a label.
1514 // FIXME: Diagnostics. Note the location of the definition as a label.
1515 // FIXME: This doesn't diagnose assignment to a symbol which has been
1516 // implicitly marked as external.
1518 if (LocalLabelVal == -1) {
1519 if (ParsingInlineAsm && SI) {
1520 StringRef RewrittenLabel =
1521 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1522 assert(RewrittenLabel.size() &&
1523 "We should have an internal name here.");
1524 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1526 IDVal = RewrittenLabel;
1528 Sym = getContext().getOrCreateSymbol(IDVal);
1530 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1532 Sym->redefineIfPossible();
1534 if (!Sym->isUndefined() || Sym->isVariable())
1535 return Error(IDLoc, "invalid symbol redefinition");
1537 // Consume any end of statement token, if present, to avoid spurious
1538 // AddBlankLine calls().
1539 if (getTok().is(AsmToken::EndOfStatement)) {
1544 if (!ParsingInlineAsm)
1547 // If we are generating dwarf for assembly source files then gather the
1548 // info to make a dwarf label entry for this label if needed.
1549 if (getContext().getGenDwarfForAssembly())
1550 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1553 getTargetParser().onLabelParsed(Sym);
1560 case AsmToken::Equal:
1561 if (!getTargetParser().equalIsAsmAssignment())
1563 // identifier '=' ... -> assignment statement
1566 return parseAssignment(IDVal, true);
1568 default: // Normal instruction or directive.
1572 // If macros are enabled, check to see if this is a macro instantiation.
1573 if (areMacrosEnabled())
1574 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1575 return handleMacroEntry(M, IDLoc);
1578 // Otherwise, we have a normal instruction or directive.
1580 // Directives start with "."
1581 if (IDVal[0] == '.' && IDVal != ".") {
1582 // There are several entities interested in parsing directives:
1584 // 1. The target-specific assembly parser. Some directives are target
1585 // specific or may potentially behave differently on certain targets.
1586 // 2. Asm parser extensions. For example, platform-specific parsers
1587 // (like the ELF parser) register themselves as extensions.
1588 // 3. The generic directive parser implemented by this class. These are
1589 // all the directives that behave in a target and platform independent
1590 // manner, or at least have a default behavior that's shared between
1591 // all targets and platforms.
1593 // First query the target-specific parser. It will return 'true' if it
1594 // isn't interested in this directive.
1595 if (!getTargetParser().ParseDirective(ID))
1598 // Next, check the extension directive map to see if any extension has
1599 // registered itself to parse this directive.
1600 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1601 ExtensionDirectiveMap.lookup(IDVal);
1603 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1605 // Finally, if no one else is interested in this directive, it must be
1606 // generic and familiar to this class.
1612 return parseDirectiveSet(IDVal, true);
1614 return parseDirectiveSet(IDVal, false);
1616 return parseDirectiveAscii(IDVal, false);
1619 return parseDirectiveAscii(IDVal, true);
1621 return parseDirectiveValue(1);
1625 return parseDirectiveValue(2);
1629 return parseDirectiveValue(4);
1632 return parseDirectiveValue(8);
1634 return parseDirectiveOctaValue();
1637 return parseDirectiveRealValue(APFloat::IEEEsingle);
1639 return parseDirectiveRealValue(APFloat::IEEEdouble);
1641 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1642 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1645 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1646 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1649 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1651 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1653 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1655 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1657 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1659 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1661 return parseDirectiveOrg();
1663 return parseDirectiveFill();
1665 return parseDirectiveZero();
1667 eatToEndOfStatement(); // .extern is the default, ignore it.
1671 return parseDirectiveSymbolAttribute(MCSA_Global);
1672 case DK_LAZY_REFERENCE:
1673 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1674 case DK_NO_DEAD_STRIP:
1675 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1676 case DK_SYMBOL_RESOLVER:
1677 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1678 case DK_PRIVATE_EXTERN:
1679 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1681 return parseDirectiveSymbolAttribute(MCSA_Reference);
1682 case DK_WEAK_DEFINITION:
1683 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1684 case DK_WEAK_REFERENCE:
1685 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1686 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1687 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1690 return parseDirectiveComm(/*IsLocal=*/false);
1692 return parseDirectiveComm(/*IsLocal=*/true);
1694 return parseDirectiveAbort();
1696 return parseDirectiveInclude();
1698 return parseDirectiveIncbin();
1701 return TokError(Twine(IDVal) +
1702 " not currently supported for this target");
1704 return parseDirectiveRept(IDLoc, IDVal);
1706 return parseDirectiveIrp(IDLoc);
1708 return parseDirectiveIrpc(IDLoc);
1710 return parseDirectiveEndr(IDLoc);
1711 case DK_BUNDLE_ALIGN_MODE:
1712 return parseDirectiveBundleAlignMode();
1713 case DK_BUNDLE_LOCK:
1714 return parseDirectiveBundleLock();
1715 case DK_BUNDLE_UNLOCK:
1716 return parseDirectiveBundleUnlock();
1718 return parseDirectiveLEB128(true);
1720 return parseDirectiveLEB128(false);
1723 return parseDirectiveSpace(IDVal);
1725 return parseDirectiveFile(IDLoc);
1727 return parseDirectiveLine();
1729 return parseDirectiveLoc();
1731 return parseDirectiveStabs();
1733 return parseDirectiveCVFile();
1735 return parseDirectiveCVLoc();
1736 case DK_CV_LINETABLE:
1737 return parseDirectiveCVLinetable();
1738 case DK_CV_INLINE_LINETABLE:
1739 return parseDirectiveCVInlineLinetable();
1740 case DK_CV_DEF_RANGE:
1741 return parseDirectiveCVDefRange();
1742 case DK_CV_STRINGTABLE:
1743 return parseDirectiveCVStringTable();
1744 case DK_CV_FILECHECKSUMS:
1745 return parseDirectiveCVFileChecksums();
1746 case DK_CFI_SECTIONS:
1747 return parseDirectiveCFISections();
1748 case DK_CFI_STARTPROC:
1749 return parseDirectiveCFIStartProc();
1750 case DK_CFI_ENDPROC:
1751 return parseDirectiveCFIEndProc();
1752 case DK_CFI_DEF_CFA:
1753 return parseDirectiveCFIDefCfa(IDLoc);
1754 case DK_CFI_DEF_CFA_OFFSET:
1755 return parseDirectiveCFIDefCfaOffset();
1756 case DK_CFI_ADJUST_CFA_OFFSET:
1757 return parseDirectiveCFIAdjustCfaOffset();
1758 case DK_CFI_DEF_CFA_REGISTER:
1759 return parseDirectiveCFIDefCfaRegister(IDLoc);
1761 return parseDirectiveCFIOffset(IDLoc);
1762 case DK_CFI_REL_OFFSET:
1763 return parseDirectiveCFIRelOffset(IDLoc);
1764 case DK_CFI_PERSONALITY:
1765 return parseDirectiveCFIPersonalityOrLsda(true);
1767 return parseDirectiveCFIPersonalityOrLsda(false);
1768 case DK_CFI_REMEMBER_STATE:
1769 return parseDirectiveCFIRememberState();
1770 case DK_CFI_RESTORE_STATE:
1771 return parseDirectiveCFIRestoreState();
1772 case DK_CFI_SAME_VALUE:
1773 return parseDirectiveCFISameValue(IDLoc);
1774 case DK_CFI_RESTORE:
1775 return parseDirectiveCFIRestore(IDLoc);
1777 return parseDirectiveCFIEscape();
1778 case DK_CFI_SIGNAL_FRAME:
1779 return parseDirectiveCFISignalFrame();
1780 case DK_CFI_UNDEFINED:
1781 return parseDirectiveCFIUndefined(IDLoc);
1782 case DK_CFI_REGISTER:
1783 return parseDirectiveCFIRegister(IDLoc);
1784 case DK_CFI_WINDOW_SAVE:
1785 return parseDirectiveCFIWindowSave();
1788 return parseDirectiveMacrosOnOff(IDVal);
1790 return parseDirectiveMacro(IDLoc);
1792 return parseDirectiveExitMacro(IDVal);
1795 return parseDirectiveEndMacro(IDVal);
1797 return parseDirectivePurgeMacro(IDLoc);
1799 return parseDirectiveEnd(IDLoc);
1801 return parseDirectiveError(IDLoc, false);
1803 return parseDirectiveError(IDLoc, true);
1805 return parseDirectiveWarning(IDLoc);
1807 return parseDirectiveReloc(IDLoc);
1810 return Error(IDLoc, "unknown directive");
1813 // __asm _emit or __asm __emit
1814 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1815 IDVal == "_EMIT" || IDVal == "__EMIT"))
1816 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1819 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1820 return parseDirectiveMSAlign(IDLoc, Info);
1822 if (ParsingInlineAsm && (IDVal == "even"))
1823 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1824 checkForValidSection();
1826 // Canonicalize the opcode to lower case.
1827 std::string OpcodeStr = IDVal.lower();
1828 ParseInstructionInfo IInfo(Info.AsmRewrites);
1829 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1830 Info.ParsedOperands);
1831 Info.ParseError = HadError;
1833 // Dump the parsed representation, if requested.
1834 if (getShowParsedOperands()) {
1835 SmallString<256> Str;
1836 raw_svector_ostream OS(Str);
1837 OS << "parsed instruction: [";
1838 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1841 Info.ParsedOperands[i]->print(OS);
1845 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1848 // If we are generating dwarf for the current section then generate a .loc
1849 // directive for the instruction.
1850 if (!HadError && getContext().getGenDwarfForAssembly() &&
1851 getContext().getGenDwarfSectionSyms().count(
1852 getStreamer().getCurrentSection().first)) {
1854 if (ActiveMacros.empty())
1855 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1857 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1858 ActiveMacros.front()->ExitBuffer);
1860 // If we previously parsed a cpp hash file line comment then make sure the
1861 // current Dwarf File is for the CppHashFilename if not then emit the
1862 // Dwarf File table for it and adjust the line number for the .loc.
1863 if (CppHashInfo.Filename.size()) {
1864 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1865 0, StringRef(), CppHashInfo.Filename);
1866 getContext().setGenDwarfFileNumber(FileNumber);
1868 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1869 // cache with the different Loc from the call above we save the last
1870 // info we queried here with SrcMgr.FindLineNumber().
1871 unsigned CppHashLocLineNo;
1872 if (LastQueryIDLoc == CppHashInfo.Loc &&
1873 LastQueryBuffer == CppHashInfo.Buf)
1874 CppHashLocLineNo = LastQueryLine;
1877 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
1878 LastQueryLine = CppHashLocLineNo;
1879 LastQueryIDLoc = CppHashInfo.Loc;
1880 LastQueryBuffer = CppHashInfo.Buf;
1882 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
1885 getStreamer().EmitDwarfLocDirective(
1886 getContext().getGenDwarfFileNumber(), Line, 0,
1887 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1891 // If parsing succeeded, match the instruction.
1894 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1895 Info.ParsedOperands, Out,
1896 ErrorInfo, ParsingInlineAsm);
1899 // Don't skip the rest of the line, the instruction parser is responsible for
1904 // Parse and erase curly braces marking block start/end
1906 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
1907 // Identify curly brace marking block start/end
1908 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
1911 SMLoc StartLoc = Lexer.getLoc();
1912 Lex(); // Eat the brace
1913 if (Lexer.is(AsmToken::EndOfStatement))
1914 Lex(); // Eat EndOfStatement following the brace
1916 // Erase the block start/end brace from the output asm string
1917 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
1918 StartLoc.getPointer());
1922 /// parseCppHashLineFilenameComment as this:
1923 /// ::= # number "filename"
1924 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1925 Lex(); // Eat the hash token.
1926 // Lexer only ever emits HashDirective if it fully formed if it's
1927 // done the checking already so this is an internal error.
1928 assert(getTok().is(AsmToken::Integer) &&
1929 "Lexing Cpp line comment: Expected Integer");
1930 int64_t LineNumber = getTok().getIntVal();
1932 assert(getTok().is(AsmToken::String) &&
1933 "Lexing Cpp line comment: Expected String");
1934 StringRef Filename = getTok().getString();
1936 // Get rid of the enclosing quotes.
1937 Filename = Filename.substr(1, Filename.size() - 2);
1939 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1940 CppHashInfo.Loc = L;
1941 CppHashInfo.Filename = Filename;
1942 CppHashInfo.LineNumber = LineNumber;
1943 CppHashInfo.Buf = CurBuffer;
1947 /// \brief will use the last parsed cpp hash line filename comment
1948 /// for the Filename and LineNo if any in the diagnostic.
1949 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1950 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1951 raw_ostream &OS = errs();
1953 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1954 SMLoc DiagLoc = Diag.getLoc();
1955 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1956 unsigned CppHashBuf =
1957 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
1959 // Like SourceMgr::printMessage() we need to print the include stack if any
1960 // before printing the message.
1961 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1962 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1963 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1964 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1965 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1968 // If we have not parsed a cpp hash line filename comment or the source
1969 // manager changed or buffer changed (like in a nested include) then just
1970 // print the normal diagnostic using its Filename and LineNo.
1971 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1972 DiagBuf != CppHashBuf) {
1973 if (Parser->SavedDiagHandler)
1974 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1976 Diag.print(nullptr, OS);
1980 // Use the CppHashFilename and calculate a line number based on the
1981 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
1982 // for the diagnostic.
1983 const std::string &Filename = Parser->CppHashInfo.Filename;
1985 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1986 int CppHashLocLineNo =
1987 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
1989 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1991 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1992 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1993 Diag.getLineContents(), Diag.getRanges());
1995 if (Parser->SavedDiagHandler)
1996 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1998 NewDiag.print(nullptr, OS);
2001 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2002 // difference being that that function accepts '@' as part of identifiers and
2003 // we can't do that. AsmLexer.cpp should probably be changed to handle
2004 // '@' as a special case when needed.
2005 static bool isIdentifierChar(char c) {
2006 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2010 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2011 ArrayRef<MCAsmMacroParameter> Parameters,
2012 ArrayRef<MCAsmMacroArgument> A,
2013 bool EnableAtPseudoVariable, SMLoc L) {
2014 unsigned NParameters = Parameters.size();
2015 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2016 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2017 return Error(L, "Wrong number of arguments");
2019 // A macro without parameters is handled differently on Darwin:
2020 // gas accepts no arguments and does no substitutions
2021 while (!Body.empty()) {
2022 // Scan for the next substitution.
2023 std::size_t End = Body.size(), Pos = 0;
2024 for (; Pos != End; ++Pos) {
2025 // Check for a substitution or escape.
2026 if (IsDarwin && !NParameters) {
2027 // This macro has no parameters, look for $0, $1, etc.
2028 if (Body[Pos] != '$' || Pos + 1 == End)
2031 char Next = Body[Pos + 1];
2032 if (Next == '$' || Next == 'n' ||
2033 isdigit(static_cast<unsigned char>(Next)))
2036 // This macro has parameters, look for \foo, \bar, etc.
2037 if (Body[Pos] == '\\' && Pos + 1 != End)
2043 OS << Body.slice(0, Pos);
2045 // Check if we reached the end.
2049 if (IsDarwin && !NParameters) {
2050 switch (Body[Pos + 1]) {
2056 // $n => number of arguments
2061 // $[0-9] => argument
2063 // Missing arguments are ignored.
2064 unsigned Index = Body[Pos + 1] - '0';
2065 if (Index >= A.size())
2068 // Otherwise substitute with the token values, with spaces eliminated.
2069 for (const AsmToken &Token : A[Index])
2070 OS << Token.getString();
2076 unsigned I = Pos + 1;
2078 // Check for the \@ pseudo-variable.
2079 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2082 while (isIdentifierChar(Body[I]) && I + 1 != End)
2085 const char *Begin = Body.data() + Pos + 1;
2086 StringRef Argument(Begin, I - (Pos + 1));
2089 if (Argument == "@") {
2090 OS << NumOfMacroInstantiations;
2093 for (; Index < NParameters; ++Index)
2094 if (Parameters[Index].Name == Argument)
2097 if (Index == NParameters) {
2098 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2101 OS << '\\' << Argument;
2105 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2106 for (const AsmToken &Token : A[Index])
2107 // We expect no quotes around the string's contents when
2108 // parsing for varargs.
2109 if (Token.getKind() != AsmToken::String || VarargParameter)
2110 OS << Token.getString();
2112 OS << Token.getStringContents();
2114 Pos += 1 + Argument.size();
2118 // Update the scan point.
2119 Body = Body.substr(Pos);
2125 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2126 size_t CondStackDepth)
2127 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2128 CondStackDepth(CondStackDepth) {}
2130 static bool isOperator(AsmToken::TokenKind kind) {
2134 case AsmToken::Plus:
2135 case AsmToken::Minus:
2136 case AsmToken::Tilde:
2137 case AsmToken::Slash:
2138 case AsmToken::Star:
2140 case AsmToken::Equal:
2141 case AsmToken::EqualEqual:
2142 case AsmToken::Pipe:
2143 case AsmToken::PipePipe:
2144 case AsmToken::Caret:
2146 case AsmToken::AmpAmp:
2147 case AsmToken::Exclaim:
2148 case AsmToken::ExclaimEqual:
2149 case AsmToken::Less:
2150 case AsmToken::LessEqual:
2151 case AsmToken::LessLess:
2152 case AsmToken::LessGreater:
2153 case AsmToken::Greater:
2154 case AsmToken::GreaterEqual:
2155 case AsmToken::GreaterGreater:
2161 class AsmLexerSkipSpaceRAII {
2163 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2164 Lexer.setSkipSpace(SkipSpace);
2167 ~AsmLexerSkipSpaceRAII() {
2168 Lexer.setSkipSpace(true);
2176 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2179 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2180 StringRef Str = parseStringToEndOfStatement();
2181 MA.emplace_back(AsmToken::String, Str);
2186 unsigned ParenLevel = 0;
2188 // Darwin doesn't use spaces to delmit arguments.
2189 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2195 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2196 return TokError("unexpected token in macro instantiation");
2198 if (ParenLevel == 0) {
2200 if (Lexer.is(AsmToken::Comma))
2203 if (Lexer.is(AsmToken::Space)) {
2205 Lexer.Lex(); // Eat spaces
2208 // Spaces can delimit parameters, but could also be part an expression.
2209 // If the token after a space is an operator, add the token and the next
2210 // one into this argument
2212 if (isOperator(Lexer.getKind())) {
2213 MA.push_back(getTok());
2216 // Whitespace after an operator can be ignored.
2217 if (Lexer.is(AsmToken::Space))
2227 // handleMacroEntry relies on not advancing the lexer here
2228 // to be able to fill in the remaining default parameter values
2229 if (Lexer.is(AsmToken::EndOfStatement))
2232 // Adjust the current parentheses level.
2233 if (Lexer.is(AsmToken::LParen))
2235 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2238 // Append the token to the current argument list.
2239 MA.push_back(getTok());
2243 if (ParenLevel != 0)
2244 return TokError("unbalanced parentheses in macro argument");
2248 // Parse the macro instantiation arguments.
2249 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2250 MCAsmMacroArguments &A) {
2251 const unsigned NParameters = M ? M->Parameters.size() : 0;
2252 bool NamedParametersFound = false;
2253 SmallVector<SMLoc, 4> FALocs;
2255 A.resize(NParameters);
2256 FALocs.resize(NParameters);
2258 // Parse two kinds of macro invocations:
2259 // - macros defined without any parameters accept an arbitrary number of them
2260 // - macros defined with parameters accept at most that many of them
2261 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2262 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2264 SMLoc IDLoc = Lexer.getLoc();
2265 MCAsmMacroParameter FA;
2267 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2268 if (parseIdentifier(FA.Name)) {
2269 Error(IDLoc, "invalid argument identifier for formal argument");
2270 eatToEndOfStatement();
2274 if (Lexer.isNot(AsmToken::Equal)) {
2275 TokError("expected '=' after formal parameter identifier");
2276 eatToEndOfStatement();
2281 NamedParametersFound = true;
2284 if (NamedParametersFound && FA.Name.empty()) {
2285 Error(IDLoc, "cannot mix positional and keyword arguments");
2286 eatToEndOfStatement();
2290 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2291 if (parseMacroArgument(FA.Value, Vararg))
2294 unsigned PI = Parameter;
2295 if (!FA.Name.empty()) {
2297 for (FAI = 0; FAI < NParameters; ++FAI)
2298 if (M->Parameters[FAI].Name == FA.Name)
2301 if (FAI >= NParameters) {
2302 assert(M && "expected macro to be defined");
2304 "parameter named '" + FA.Name + "' does not exist for macro '" +
2311 if (!FA.Value.empty()) {
2316 if (FALocs.size() <= PI)
2317 FALocs.resize(PI + 1);
2319 FALocs[PI] = Lexer.getLoc();
2322 // At the end of the statement, fill in remaining arguments that have
2323 // default values. If there aren't any, then the next argument is
2324 // required but missing
2325 if (Lexer.is(AsmToken::EndOfStatement)) {
2326 bool Failure = false;
2327 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2328 if (A[FAI].empty()) {
2329 if (M->Parameters[FAI].Required) {
2330 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2331 "missing value for required parameter "
2332 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2336 if (!M->Parameters[FAI].Value.empty())
2337 A[FAI] = M->Parameters[FAI].Value;
2343 if (Lexer.is(AsmToken::Comma))
2347 return TokError("too many positional arguments");
2350 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2351 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2352 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2355 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2356 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2359 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2361 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2362 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2363 // this, although we should protect against infinite loops.
2364 if (ActiveMacros.size() == 20)
2365 return TokError("macros cannot be nested more than 20 levels deep");
2367 MCAsmMacroArguments A;
2368 if (parseMacroArguments(M, A))
2371 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2372 // to hold the macro body with substitutions.
2373 SmallString<256> Buf;
2374 StringRef Body = M->Body;
2375 raw_svector_ostream OS(Buf);
2377 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2380 // We include the .endmacro in the buffer as our cue to exit the macro
2382 OS << ".endmacro\n";
2384 std::unique_ptr<MemoryBuffer> Instantiation =
2385 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2387 // Create the macro instantiation object and add to the current macro
2388 // instantiation stack.
2389 MacroInstantiation *MI = new MacroInstantiation(
2390 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2391 ActiveMacros.push_back(MI);
2393 ++NumOfMacroInstantiations;
2395 // Jump to the macro instantiation and prime the lexer.
2396 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2397 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2403 void AsmParser::handleMacroExit() {
2404 // Jump to the EndOfStatement we should return to, and consume it.
2405 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2408 // Pop the instantiation entry.
2409 delete ActiveMacros.back();
2410 ActiveMacros.pop_back();
2413 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2416 const MCExpr *Value;
2417 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2422 // In the case where we parse an expression starting with a '.', we will
2423 // not generate an error, nor will we create a symbol. In this case we
2424 // should just return out.
2428 // Do the assignment.
2429 Out.EmitAssignment(Sym, Value);
2431 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2436 /// parseIdentifier:
2439 bool AsmParser::parseIdentifier(StringRef &Res) {
2440 // The assembler has relaxed rules for accepting identifiers, in particular we
2441 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2442 // separate tokens. At this level, we have already lexed so we cannot (currently)
2443 // handle this as a context dependent token, instead we detect adjacent tokens
2444 // and return the combined identifier.
2445 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2446 SMLoc PrefixLoc = getLexer().getLoc();
2448 // Consume the prefix character, and check for a following identifier.
2449 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2450 if (Lexer.isNot(AsmToken::Identifier))
2453 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2454 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2457 // Construct the joined identifier and consume the token.
2459 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2460 Lex(); // Parser Lex to maintain invariants.
2464 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2467 Res = getTok().getIdentifier();
2469 Lex(); // Consume the identifier token.
2474 /// parseDirectiveSet:
2475 /// ::= .equ identifier ',' expression
2476 /// ::= .equiv identifier ',' expression
2477 /// ::= .set identifier ',' expression
2478 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2481 if (check(parseIdentifier(Name),
2482 "expected identifier after '" + Twine(IDVal) + "'") ||
2483 parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "'"))
2486 return parseAssignment(Name, allow_redef, true);
2489 bool AsmParser::parseEscapedString(std::string &Data) {
2490 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2493 StringRef Str = getTok().getStringContents();
2494 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2495 if (Str[i] != '\\') {
2500 // Recognize escaped characters. Note that this escape semantics currently
2501 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2504 return TokError("unexpected backslash at end of string");
2506 // Recognize octal sequences.
2507 if ((unsigned)(Str[i] - '0') <= 7) {
2508 // Consume up to three octal characters.
2509 unsigned Value = Str[i] - '0';
2511 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2513 Value = Value * 8 + (Str[i] - '0');
2515 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2517 Value = Value * 8 + (Str[i] - '0');
2522 return TokError("invalid octal escape sequence (out of range)");
2524 Data += (unsigned char)Value;
2528 // Otherwise recognize individual escapes.
2531 // Just reject invalid escape sequences for now.
2532 return TokError("invalid escape sequence (unrecognized character)");
2534 case 'b': Data += '\b'; break;
2535 case 'f': Data += '\f'; break;
2536 case 'n': Data += '\n'; break;
2537 case 'r': Data += '\r'; break;
2538 case 't': Data += '\t'; break;
2539 case '"': Data += '"'; break;
2540 case '\\': Data += '\\'; break;
2548 /// parseDirectiveAscii:
2549 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2550 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2551 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2552 checkForValidSection();
2556 if (check(getTok().isNot(AsmToken::String),
2557 "expected string in '" + Twine(IDVal) + "' directive") ||
2558 parseEscapedString(Data))
2561 getStreamer().EmitBytes(Data);
2563 getStreamer().EmitBytes(StringRef("\0", 1));
2565 if (getLexer().is(AsmToken::EndOfStatement))
2568 if (parseToken(AsmToken::Comma,
2569 "unexpected token in '" + Twine(IDVal) + "' directive"))
2578 /// parseDirectiveReloc
2579 /// ::= .reloc expression , identifier [ , expression ]
2580 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2581 const MCExpr *Offset;
2582 const MCExpr *Expr = nullptr;
2584 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2585 if (parseExpression(Offset))
2588 // We can only deal with constant expressions at the moment.
2589 int64_t OffsetValue;
2590 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2591 "expression is not a constant value") ||
2592 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2593 parseToken(AsmToken::Comma, "expected comma") ||
2594 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2597 SMLoc NameLoc = Lexer.getTok().getLoc();
2598 StringRef Name = Lexer.getTok().getIdentifier();
2601 if (Lexer.is(AsmToken::Comma)) {
2603 SMLoc ExprLoc = Lexer.getLoc();
2604 if (parseExpression(Expr))
2608 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2609 return Error(ExprLoc, "expression must be relocatable");
2612 if (parseToken(AsmToken::EndOfStatement,
2613 "unexpected token in .reloc directive") ||
2614 check(getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc),
2615 NameLoc, "unknown relocation name"))
2620 /// parseDirectiveValue
2621 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2622 bool AsmParser::parseDirectiveValue(unsigned Size) {
2623 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2624 checkForValidSection();
2627 const MCExpr *Value;
2628 SMLoc ExprLoc = getLexer().getLoc();
2629 if (parseExpression(Value))
2632 // Special case constant expressions to match code generator.
2633 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2634 assert(Size <= 8 && "Invalid size");
2635 uint64_t IntValue = MCE->getValue();
2636 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2637 return Error(ExprLoc, "literal value out of range for directive");
2638 getStreamer().EmitIntValue(IntValue, Size);
2640 getStreamer().EmitValue(Value, Size, ExprLoc);
2642 if (getLexer().is(AsmToken::EndOfStatement))
2645 // FIXME: Improve diagnostic.
2646 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2655 /// ParseDirectiveOctaValue
2656 /// ::= .octa [ hexconstant (, hexconstant)* ]
2657 bool AsmParser::parseDirectiveOctaValue() {
2658 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2659 checkForValidSection();
2662 if (getTok().is(AsmToken::Error))
2664 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2665 return TokError("unknown token in expression");
2667 SMLoc ExprLoc = getLexer().getLoc();
2668 APInt IntValue = getTok().getAPIntVal();
2672 if (IntValue.isIntN(64)) {
2674 lo = IntValue.getZExtValue();
2675 } else if (IntValue.isIntN(128)) {
2676 // It might actually have more than 128 bits, but the top ones are zero.
2677 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2678 lo = IntValue.getLoBits(64).getZExtValue();
2680 return Error(ExprLoc, "literal value out of range for directive");
2682 if (MAI.isLittleEndian()) {
2683 getStreamer().EmitIntValue(lo, 8);
2684 getStreamer().EmitIntValue(hi, 8);
2686 getStreamer().EmitIntValue(hi, 8);
2687 getStreamer().EmitIntValue(lo, 8);
2690 if (getLexer().is(AsmToken::EndOfStatement))
2693 // FIXME: Improve diagnostic.
2694 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2703 /// parseDirectiveRealValue
2704 /// ::= (.single | .double) [ expression (, expression)* ]
2705 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2707 checkForValidSection();
2710 // We don't truly support arithmetic on floating point expressions, so we
2711 // have to manually parse unary prefixes.
2713 if (getLexer().is(AsmToken::Minus)) {
2716 } else if (getLexer().is(AsmToken::Plus))
2719 if (Lexer.is(AsmToken::Error))
2720 return TokError(Lexer.getErr());
2721 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2722 Lexer.isNot(AsmToken::Identifier))
2723 return TokError("unexpected token in directive");
2725 // Convert to an APFloat.
2726 APFloat Value(Semantics);
2727 StringRef IDVal = getTok().getString();
2728 if (getLexer().is(AsmToken::Identifier)) {
2729 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2730 Value = APFloat::getInf(Semantics);
2731 else if (!IDVal.compare_lower("nan"))
2732 Value = APFloat::getNaN(Semantics, false, ~0);
2734 return TokError("invalid floating point literal");
2735 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2736 APFloat::opInvalidOp)
2737 return TokError("invalid floating point literal");
2741 // Consume the numeric token.
2744 // Emit the value as an integer.
2745 APInt AsInt = Value.bitcastToAPInt();
2746 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2747 AsInt.getBitWidth() / 8);
2749 if (Lexer.is(AsmToken::EndOfStatement))
2752 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2761 /// parseDirectiveZero
2762 /// ::= .zero expression
2763 bool AsmParser::parseDirectiveZero() {
2764 checkForValidSection();
2766 SMLoc NumBytesLoc = Lexer.getLoc();
2767 const MCExpr *NumBytes;
2768 if (parseExpression(NumBytes))
2772 if (getLexer().is(AsmToken::Comma)) {
2774 if (parseAbsoluteExpression(Val))
2778 if (parseToken(AsmToken::EndOfStatement,
2779 "unexpected token in '.zero' directive"))
2781 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
2786 /// parseDirectiveFill
2787 /// ::= .fill expression [ , expression [ , expression ] ]
2788 bool AsmParser::parseDirectiveFill() {
2789 checkForValidSection();
2791 SMLoc NumValuesLoc = Lexer.getLoc();
2792 const MCExpr *NumValues;
2793 if (parseExpression(NumValues))
2796 int64_t FillSize = 1;
2797 int64_t FillExpr = 0;
2799 SMLoc SizeLoc, ExprLoc;
2800 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2802 if (parseToken(AsmToken::Comma, "unexpected token in '.fill' directive") ||
2803 getTokenLoc(SizeLoc) || parseAbsoluteExpression(FillSize))
2806 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2807 if (parseToken(AsmToken::Comma,
2808 "unexpected token in '.fill' directive") ||
2809 getTokenLoc(ExprLoc) || parseAbsoluteExpression(FillExpr) ||
2810 parseToken(AsmToken::EndOfStatement,
2811 "unexpected token in '.fill' directive"))
2817 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2821 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2825 if (!isUInt<32>(FillExpr) && FillSize > 4)
2826 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2828 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
2833 /// parseDirectiveOrg
2834 /// ::= .org expression [ , expression ]
2835 bool AsmParser::parseDirectiveOrg() {
2836 checkForValidSection();
2838 const MCExpr *Offset;
2839 if (parseExpression(Offset))
2842 // Parse optional fill expression.
2843 int64_t FillExpr = 0;
2844 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2845 if (parseToken(AsmToken::Comma, "unexpected token in '.org' directive") ||
2846 parseAbsoluteExpression(FillExpr))
2850 if (parseToken(AsmToken::EndOfStatement,
2851 "unexpected token in '.org' directive"))
2854 getStreamer().emitValueToOffset(Offset, FillExpr);
2858 /// parseDirectiveAlign
2859 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2860 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2861 checkForValidSection();
2863 SMLoc AlignmentLoc = getLexer().getLoc();
2865 if (parseAbsoluteExpression(Alignment))
2869 bool HasFillExpr = false;
2870 int64_t FillExpr = 0;
2871 int64_t MaxBytesToFill = 0;
2872 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2873 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2876 // The fill expression can be omitted while specifying a maximum number of
2877 // alignment bytes, e.g:
2879 if (getTok().isNot(AsmToken::Comma)) {
2881 if (parseAbsoluteExpression(FillExpr))
2885 if (getTok().isNot(AsmToken::EndOfStatement)) {
2886 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
2887 getTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill))
2892 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
2898 // Compute alignment in bytes.
2900 // FIXME: Diagnose overflow.
2901 if (Alignment >= 32) {
2902 Error(AlignmentLoc, "invalid alignment value");
2906 Alignment = 1ULL << Alignment;
2908 // Reject alignments that aren't either a power of two or zero,
2909 // for gas compatibility. Alignment of zero is silently rounded
2913 if (!isPowerOf2_64(Alignment))
2914 Error(AlignmentLoc, "alignment must be a power of 2");
2917 // Diagnose non-sensical max bytes to align.
2918 if (MaxBytesLoc.isValid()) {
2919 if (MaxBytesToFill < 1) {
2920 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2921 "many bytes, ignoring maximum bytes expression");
2925 if (MaxBytesToFill >= Alignment) {
2926 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2932 // Check whether we should use optimal code alignment for this .align
2934 const MCSection *Section = getStreamer().getCurrentSection().first;
2935 assert(Section && "must have section to emit alignment");
2936 bool UseCodeAlign = Section->UseCodeAlign();
2937 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2938 ValueSize == 1 && UseCodeAlign) {
2939 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2941 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2942 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2949 /// parseDirectiveFile
2950 /// ::= .file [number] filename
2951 /// ::= .file number directory filename
2952 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2953 // FIXME: I'm not sure what this is.
2954 int64_t FileNumber = -1;
2955 SMLoc FileNumberLoc = getLexer().getLoc();
2956 if (getLexer().is(AsmToken::Integer)) {
2957 FileNumber = getTok().getIntVal();
2961 return TokError("file number less than one");
2964 std::string Path = getTok().getString();
2966 // Usually the directory and filename together, otherwise just the directory.
2967 // Allow the strings to have escaped octal character sequence.
2968 if (check(getTok().isNot(AsmToken::String),
2969 "unexpected token in '.file' directive") ||
2970 parseEscapedString(Path))
2973 StringRef Directory;
2975 std::string FilenameData;
2976 if (getLexer().is(AsmToken::String)) {
2977 if (check(FileNumber == -1,
2978 "explicit path specified, but no file number") ||
2979 parseEscapedString(FilenameData))
2981 Filename = FilenameData;
2987 if (parseToken(AsmToken::EndOfStatement,
2988 "unexpected token in '.file' directive"))
2991 if (FileNumber == -1)
2992 getStreamer().EmitFileDirective(Filename);
2994 // If there is -g option as well as debug info from directive file,
2995 // we turn off -g option, directly use the existing debug info instead.
2996 if (getContext().getGenDwarfForAssembly())
2997 getContext().setGenDwarfForAssembly(false);
2998 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3000 Error(FileNumberLoc, "file number already allocated");
3006 /// parseDirectiveLine
3007 /// ::= .line [number]
3008 bool AsmParser::parseDirectiveLine() {
3010 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3011 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3014 // FIXME: Do something with the .line.
3016 if (parseToken(AsmToken::EndOfStatement,
3017 "unexpected token in '.line' directive"))
3023 /// parseDirectiveLoc
3024 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3025 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3026 /// The first number is a file number, must have been previously assigned with
3027 /// a .file directive, the second number is the line number and optionally the
3028 /// third number is a column position (zero if not specified). The remaining
3029 /// optional items are .loc sub-directives.
3030 bool AsmParser::parseDirectiveLoc() {
3031 int64_t FileNumber = 0, LineNumber = 0;
3032 SMLoc Loc = getTok().getLoc();
3033 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3034 check(FileNumber < 1, Loc,
3035 "file number less than one in '.loc' directive") ||
3036 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3037 "unassigned file number in '.loc' directive"))
3041 if (getLexer().is(AsmToken::Integer)) {
3042 LineNumber = getTok().getIntVal();
3044 return TokError("line number less than zero in '.loc' directive");
3048 int64_t ColumnPos = 0;
3049 if (getLexer().is(AsmToken::Integer)) {
3050 ColumnPos = getTok().getIntVal();
3052 return TokError("column position less than zero in '.loc' directive");
3056 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3058 int64_t Discriminator = 0;
3059 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3061 if (getLexer().is(AsmToken::EndOfStatement))
3065 SMLoc Loc = getTok().getLoc();
3066 if (parseIdentifier(Name))
3067 return TokError("unexpected token in '.loc' directive");
3069 if (Name == "basic_block")
3070 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3071 else if (Name == "prologue_end")
3072 Flags |= DWARF2_FLAG_PROLOGUE_END;
3073 else if (Name == "epilogue_begin")
3074 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3075 else if (Name == "is_stmt") {
3076 Loc = getTok().getLoc();
3077 const MCExpr *Value;
3078 if (parseExpression(Value))
3080 // The expression must be the constant 0 or 1.
3081 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3082 int Value = MCE->getValue();
3084 Flags &= ~DWARF2_FLAG_IS_STMT;
3085 else if (Value == 1)
3086 Flags |= DWARF2_FLAG_IS_STMT;
3088 return Error(Loc, "is_stmt value not 0 or 1");
3090 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3092 } else if (Name == "isa") {
3093 Loc = getTok().getLoc();
3094 const MCExpr *Value;
3095 if (parseExpression(Value))
3097 // The expression must be a constant greater or equal to 0.
3098 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3099 int Value = MCE->getValue();
3101 return Error(Loc, "isa number less than zero");
3104 return Error(Loc, "isa number not a constant value");
3106 } else if (Name == "discriminator") {
3107 if (parseAbsoluteExpression(Discriminator))
3110 return Error(Loc, "unknown sub-directive in '.loc' directive");
3113 if (getLexer().is(AsmToken::EndOfStatement))
3119 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3120 Isa, Discriminator, StringRef());
3125 /// parseDirectiveStabs
3126 /// ::= .stabs string, number, number, number
3127 bool AsmParser::parseDirectiveStabs() {
3128 return TokError("unsupported directive '.stabs'");
3131 /// parseDirectiveCVFile
3132 /// ::= .cv_file number filename
3133 bool AsmParser::parseDirectiveCVFile() {
3134 SMLoc FileNumberLoc = getTok().getLoc();
3136 std::string Filename;
3138 if (parseIntToken(FileNumber,
3139 "expected file number in '.cv_file' directive") ||
3140 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3141 check(getTok().isNot(AsmToken::String),
3142 "unexpected token in '.cv_file' directive") ||
3143 // Usually directory and filename are together, otherwise just
3144 // directory. Allow the strings to have escaped octal character sequence.
3145 parseEscapedString(Filename) ||
3146 parseToken(AsmToken::EndOfStatement,
3147 "unexpected token in '.cv_file' directive") ||
3148 check(getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0,
3149 FileNumberLoc, "file number already allocated"))
3155 /// parseDirectiveCVLoc
3156 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3158 /// The first number is a file number, must have been previously assigned with
3159 /// a .file directive, the second number is the line number and optionally the
3160 /// third number is a column position (zero if not specified). The remaining
3161 /// optional items are .loc sub-directives.
3162 bool AsmParser::parseDirectiveCVLoc() {
3164 int64_t FunctionId, FileNumber;
3165 if (getTokenLoc(Loc) ||
3166 parseIntToken(FunctionId, "unexpected token in '.cv_loc' directive") ||
3167 check(FunctionId < 0, Loc,
3168 "function id less than zero in '.cv_loc' directive") ||
3170 parseIntToken(FileNumber, "expected integer in '.cv_loc' directive") ||
3171 check(FileNumber < 1, Loc,
3172 "file number less than one in '.cv_loc' directive") ||
3173 check(!getContext().isValidCVFileNumber(FileNumber), Loc,
3174 "unassigned file number in '.cv_loc' directive"))
3177 int64_t LineNumber = 0;
3178 if (getLexer().is(AsmToken::Integer)) {
3179 LineNumber = getTok().getIntVal();
3181 return TokError("line number less than zero in '.cv_loc' directive");
3185 int64_t ColumnPos = 0;
3186 if (getLexer().is(AsmToken::Integer)) {
3187 ColumnPos = getTok().getIntVal();
3189 return TokError("column position less than zero in '.cv_loc' directive");
3193 bool PrologueEnd = false;
3194 uint64_t IsStmt = 0;
3195 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3197 SMLoc Loc = getTok().getLoc();
3198 if (parseIdentifier(Name))
3199 return TokError("unexpected token in '.cv_loc' directive");
3201 if (Name == "prologue_end")
3203 else if (Name == "is_stmt") {
3204 Loc = getTok().getLoc();
3205 const MCExpr *Value;
3206 if (parseExpression(Value))
3208 // The expression must be the constant 0 or 1.
3210 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3211 IsStmt = MCE->getValue();
3214 return Error(Loc, "is_stmt value not 0 or 1");
3216 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3221 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3222 ColumnPos, PrologueEnd, IsStmt, StringRef());
3226 /// parseDirectiveCVLinetable
3227 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3228 bool AsmParser::parseDirectiveCVLinetable() {
3230 StringRef FnStartName, FnEndName;
3231 SMLoc Loc = getTok().getLoc();
3232 if (parseIntToken(FunctionId,
3233 "expected Integer in '.cv_linetable' directive") ||
3234 check(FunctionId < 0, Loc,
3235 "function id less than zero in '.cv_linetable' directive") ||
3236 parseToken(AsmToken::Comma,
3237 "unexpected token in '.cv_linetable' directive") ||
3238 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3239 "expected identifier in directive") ||
3240 parseToken(AsmToken::Comma,
3241 "unexpected token in '.cv_linetable' directive") ||
3242 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3243 "expected identifier in directive"))
3246 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3247 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3249 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3253 /// parseDirectiveCVInlineLinetable
3254 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3255 /// ("contains" SecondaryFunctionId+)?
3256 bool AsmParser::parseDirectiveCVInlineLinetable() {
3257 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3258 StringRef FnStartName, FnEndName;
3259 SMLoc Loc = getTok().getLoc();
3262 "expected PrimaryFunctionId in '.cv_inline_linetable' directive") ||
3263 check(PrimaryFunctionId < 0, Loc,
3264 "function id less than zero in '.cv_inline_linetable' directive") ||
3268 "expected SourceField in '.cv_inline_linetable' directive") ||
3269 check(SourceFileId <= 0, Loc,
3270 "File id less than zero in '.cv_inline_linetable' directive") ||
3274 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3275 check(SourceLineNum < 0, Loc,
3276 "Line number less than zero in '.cv_inline_linetable' directive") ||
3277 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3278 "expected identifier in directive") ||
3279 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3280 "expected identifier in directive"))
3283 SmallVector<unsigned, 8> SecondaryFunctionIds;
3284 if (getLexer().is(AsmToken::Identifier)) {
3285 if (getTok().getIdentifier() != "contains")
3287 "unexpected identifier in '.cv_inline_linetable' directive");
3290 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3291 int64_t SecondaryFunctionId = getTok().getIntVal();
3292 if (SecondaryFunctionId < 0)
3294 "function id less than zero in '.cv_inline_linetable' directive");
3297 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3301 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3304 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3305 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3306 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3307 SourceLineNum, FnStartSym,
3308 FnEndSym, SecondaryFunctionIds);
3312 /// parseDirectiveCVDefRange
3313 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3314 bool AsmParser::parseDirectiveCVDefRange() {
3316 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3317 while (getLexer().is(AsmToken::Identifier)) {
3318 Loc = getLexer().getLoc();
3319 StringRef GapStartName;
3320 if (parseIdentifier(GapStartName))
3321 return Error(Loc, "expected identifier in directive");
3322 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3324 Loc = getLexer().getLoc();
3325 StringRef GapEndName;
3326 if (parseIdentifier(GapEndName))
3327 return Error(Loc, "expected identifier in directive");
3328 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3330 Ranges.push_back({GapStartSym, GapEndSym});
3333 std::string FixedSizePortion;
3334 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3335 parseEscapedString(FixedSizePortion))
3338 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3342 /// parseDirectiveCVStringTable
3343 /// ::= .cv_stringtable
3344 bool AsmParser::parseDirectiveCVStringTable() {
3345 getStreamer().EmitCVStringTableDirective();
3349 /// parseDirectiveCVFileChecksums
3350 /// ::= .cv_filechecksums
3351 bool AsmParser::parseDirectiveCVFileChecksums() {
3352 getStreamer().EmitCVFileChecksumsDirective();
3356 /// parseDirectiveCFISections
3357 /// ::= .cfi_sections section [, section]
3358 bool AsmParser::parseDirectiveCFISections() {
3363 if (parseIdentifier(Name))
3364 return TokError("Expected an identifier");
3366 if (Name == ".eh_frame")
3368 else if (Name == ".debug_frame")
3371 if (getLexer().is(AsmToken::Comma)) {
3374 if (parseIdentifier(Name))
3375 return TokError("Expected an identifier");
3377 if (Name == ".eh_frame")
3379 else if (Name == ".debug_frame")
3383 getStreamer().EmitCFISections(EH, Debug);
3387 /// parseDirectiveCFIStartProc
3388 /// ::= .cfi_startproc [simple]
3389 bool AsmParser::parseDirectiveCFIStartProc() {
3391 if (getLexer().isNot(AsmToken::EndOfStatement))
3392 if (parseIdentifier(Simple) || Simple != "simple")
3393 return TokError("unexpected token in .cfi_startproc directive");
3395 if (parseToken(AsmToken::EndOfStatement, "Expected end of statement"))
3398 getStreamer().EmitCFIStartProc(!Simple.empty());
3402 /// parseDirectiveCFIEndProc
3403 /// ::= .cfi_endproc
3404 bool AsmParser::parseDirectiveCFIEndProc() {
3405 getStreamer().EmitCFIEndProc();
3409 /// \brief parse register name or number.
3410 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3411 SMLoc DirectiveLoc) {
3414 if (getLexer().isNot(AsmToken::Integer)) {
3415 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3417 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3419 return parseAbsoluteExpression(Register);
3424 /// parseDirectiveCFIDefCfa
3425 /// ::= .cfi_def_cfa register, offset
3426 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3427 int64_t Register = 0, Offset = 0;
3428 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3429 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3430 parseAbsoluteExpression(Offset))
3433 getStreamer().EmitCFIDefCfa(Register, Offset);
3437 /// parseDirectiveCFIDefCfaOffset
3438 /// ::= .cfi_def_cfa_offset offset
3439 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3441 if (parseAbsoluteExpression(Offset))
3444 getStreamer().EmitCFIDefCfaOffset(Offset);
3448 /// parseDirectiveCFIRegister
3449 /// ::= .cfi_register register, register
3450 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3451 int64_t Register1 = 0, Register2 = 0;
3452 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3453 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3454 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3457 getStreamer().EmitCFIRegister(Register1, Register2);
3461 /// parseDirectiveCFIWindowSave
3462 /// ::= .cfi_window_save
3463 bool AsmParser::parseDirectiveCFIWindowSave() {
3464 getStreamer().EmitCFIWindowSave();
3468 /// parseDirectiveCFIAdjustCfaOffset
3469 /// ::= .cfi_adjust_cfa_offset adjustment
3470 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3471 int64_t Adjustment = 0;
3472 if (parseAbsoluteExpression(Adjustment))
3475 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3479 /// parseDirectiveCFIDefCfaRegister
3480 /// ::= .cfi_def_cfa_register register
3481 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3482 int64_t Register = 0;
3483 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3486 getStreamer().EmitCFIDefCfaRegister(Register);
3490 /// parseDirectiveCFIOffset
3491 /// ::= .cfi_offset register, offset
3492 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3493 int64_t Register = 0;
3496 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3497 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3498 parseAbsoluteExpression(Offset))
3501 getStreamer().EmitCFIOffset(Register, Offset);
3505 /// parseDirectiveCFIRelOffset
3506 /// ::= .cfi_rel_offset register, offset
3507 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3508 int64_t Register = 0, Offset = 0;
3510 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3511 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3512 parseAbsoluteExpression(Offset))
3515 getStreamer().EmitCFIRelOffset(Register, Offset);
3519 static bool isValidEncoding(int64_t Encoding) {
3520 if (Encoding & ~0xff)
3523 if (Encoding == dwarf::DW_EH_PE_omit)
3526 const unsigned Format = Encoding & 0xf;
3527 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3528 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3529 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3530 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3533 const unsigned Application = Encoding & 0x70;
3534 if (Application != dwarf::DW_EH_PE_absptr &&
3535 Application != dwarf::DW_EH_PE_pcrel)
3541 /// parseDirectiveCFIPersonalityOrLsda
3542 /// IsPersonality true for cfi_personality, false for cfi_lsda
3543 /// ::= .cfi_personality encoding, [symbol_name]
3544 /// ::= .cfi_lsda encoding, [symbol_name]
3545 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3546 int64_t Encoding = 0;
3547 if (parseAbsoluteExpression(Encoding))
3549 if (Encoding == dwarf::DW_EH_PE_omit)
3553 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3554 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3555 check(parseIdentifier(Name), "expected identifier in directive"))
3558 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3561 getStreamer().EmitCFIPersonality(Sym, Encoding);
3563 getStreamer().EmitCFILsda(Sym, Encoding);
3567 /// parseDirectiveCFIRememberState
3568 /// ::= .cfi_remember_state
3569 bool AsmParser::parseDirectiveCFIRememberState() {
3570 getStreamer().EmitCFIRememberState();
3574 /// parseDirectiveCFIRestoreState
3575 /// ::= .cfi_remember_state
3576 bool AsmParser::parseDirectiveCFIRestoreState() {
3577 getStreamer().EmitCFIRestoreState();
3581 /// parseDirectiveCFISameValue
3582 /// ::= .cfi_same_value register
3583 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3584 int64_t Register = 0;
3586 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3589 getStreamer().EmitCFISameValue(Register);
3593 /// parseDirectiveCFIRestore
3594 /// ::= .cfi_restore register
3595 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3596 int64_t Register = 0;
3597 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3600 getStreamer().EmitCFIRestore(Register);
3604 /// parseDirectiveCFIEscape
3605 /// ::= .cfi_escape expression[,...]
3606 bool AsmParser::parseDirectiveCFIEscape() {
3609 if (parseAbsoluteExpression(CurrValue))
3612 Values.push_back((uint8_t)CurrValue);
3614 while (getLexer().is(AsmToken::Comma)) {
3617 if (parseAbsoluteExpression(CurrValue))
3620 Values.push_back((uint8_t)CurrValue);
3623 getStreamer().EmitCFIEscape(Values);
3627 /// parseDirectiveCFISignalFrame
3628 /// ::= .cfi_signal_frame
3629 bool AsmParser::parseDirectiveCFISignalFrame() {
3630 if (parseToken(AsmToken::EndOfStatement,
3631 "unexpected token in '.cfi_signal_frame'"))
3634 getStreamer().EmitCFISignalFrame();
3638 /// parseDirectiveCFIUndefined
3639 /// ::= .cfi_undefined register
3640 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3641 int64_t Register = 0;
3643 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3646 getStreamer().EmitCFIUndefined(Register);
3650 /// parseDirectiveMacrosOnOff
3653 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3654 if (parseToken(AsmToken::EndOfStatement,
3655 "unexpected token in '" + Directive + "' directive"))
3658 setMacrosEnabled(Directive == ".macros_on");
3662 /// parseDirectiveMacro
3663 /// ::= .macro name[,] [parameters]
3664 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3666 if (parseIdentifier(Name))
3667 return TokError("expected identifier in '.macro' directive");
3669 if (getLexer().is(AsmToken::Comma))
3672 MCAsmMacroParameters Parameters;
3673 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3675 if (!Parameters.empty() && Parameters.back().Vararg)
3676 return Error(Lexer.getLoc(),
3677 "Vararg parameter '" + Parameters.back().Name +
3678 "' should be last one in the list of parameters.");
3680 MCAsmMacroParameter Parameter;
3681 if (parseIdentifier(Parameter.Name))
3682 return TokError("expected identifier in '.macro' directive");
3684 if (Lexer.is(AsmToken::Colon)) {
3685 Lex(); // consume ':'
3688 StringRef Qualifier;
3690 QualLoc = Lexer.getLoc();
3691 if (parseIdentifier(Qualifier))
3692 return Error(QualLoc, "missing parameter qualifier for "
3693 "'" + Parameter.Name + "' in macro '" + Name + "'");
3695 if (Qualifier == "req")
3696 Parameter.Required = true;
3697 else if (Qualifier == "vararg")
3698 Parameter.Vararg = true;
3700 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3701 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3704 if (getLexer().is(AsmToken::Equal)) {
3709 ParamLoc = Lexer.getLoc();
3710 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3713 if (Parameter.Required)
3714 Warning(ParamLoc, "pointless default value for required parameter "
3715 "'" + Parameter.Name + "' in macro '" + Name + "'");
3718 Parameters.push_back(std::move(Parameter));
3720 if (getLexer().is(AsmToken::Comma))
3724 // Eat just the end of statement.
3727 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
3728 AsmToken EndToken, StartToken = getTok();
3729 unsigned MacroDepth = 0;
3730 // Lex the macro definition.
3732 // Ignore Lexing errors in macros.
3733 while (Lexer.is(AsmToken::Error)) {
3737 // Check whether we have reached the end of the file.
3738 if (getLexer().is(AsmToken::Eof))
3739 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3741 // Otherwise, check whether we have reach the .endmacro.
3742 if (getLexer().is(AsmToken::Identifier)) {
3743 if (getTok().getIdentifier() == ".endm" ||
3744 getTok().getIdentifier() == ".endmacro") {
3745 if (MacroDepth == 0) { // Outermost macro.
3746 EndToken = getTok();
3748 if (getLexer().isNot(AsmToken::EndOfStatement))
3749 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3753 // Otherwise we just found the end of an inner macro.
3756 } else if (getTok().getIdentifier() == ".macro") {
3757 // We allow nested macros. Those aren't instantiated until the outermost
3758 // macro is expanded so just ignore them for now.
3763 // Otherwise, scan til the end of the statement.
3764 eatToEndOfStatement();
3767 if (lookupMacro(Name)) {
3768 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3771 const char *BodyStart = StartToken.getLoc().getPointer();
3772 const char *BodyEnd = EndToken.getLoc().getPointer();
3773 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3774 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3775 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3779 /// checkForBadMacro
3781 /// With the support added for named parameters there may be code out there that
3782 /// is transitioning from positional parameters. In versions of gas that did
3783 /// not support named parameters they would be ignored on the macro definition.
3784 /// But to support both styles of parameters this is not possible so if a macro
3785 /// definition has named parameters but does not use them and has what appears
3786 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3787 /// warning that the positional parameter found in body which have no effect.
3788 /// Hoping the developer will either remove the named parameters from the macro
3789 /// definition so the positional parameters get used if that was what was
3790 /// intended or change the macro to use the named parameters. It is possible
3791 /// this warning will trigger when the none of the named parameters are used
3792 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3793 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3795 ArrayRef<MCAsmMacroParameter> Parameters) {
3796 // If this macro is not defined with named parameters the warning we are
3797 // checking for here doesn't apply.
3798 unsigned NParameters = Parameters.size();
3799 if (NParameters == 0)
3802 bool NamedParametersFound = false;
3803 bool PositionalParametersFound = false;
3805 // Look at the body of the macro for use of both the named parameters and what
3806 // are likely to be positional parameters. This is what expandMacro() is
3807 // doing when it finds the parameters in the body.
3808 while (!Body.empty()) {
3809 // Scan for the next possible parameter.
3810 std::size_t End = Body.size(), Pos = 0;
3811 for (; Pos != End; ++Pos) {
3812 // Check for a substitution or escape.
3813 // This macro is defined with parameters, look for \foo, \bar, etc.
3814 if (Body[Pos] == '\\' && Pos + 1 != End)
3817 // This macro should have parameters, but look for $0, $1, ..., $n too.
3818 if (Body[Pos] != '$' || Pos + 1 == End)
3820 char Next = Body[Pos + 1];
3821 if (Next == '$' || Next == 'n' ||
3822 isdigit(static_cast<unsigned char>(Next)))
3826 // Check if we reached the end.
3830 if (Body[Pos] == '$') {
3831 switch (Body[Pos + 1]) {
3836 // $n => number of arguments
3838 PositionalParametersFound = true;
3841 // $[0-9] => argument
3843 PositionalParametersFound = true;
3849 unsigned I = Pos + 1;
3850 while (isIdentifierChar(Body[I]) && I + 1 != End)
3853 const char *Begin = Body.data() + Pos + 1;
3854 StringRef Argument(Begin, I - (Pos + 1));
3856 for (; Index < NParameters; ++Index)
3857 if (Parameters[Index].Name == Argument)
3860 if (Index == NParameters) {
3861 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3867 NamedParametersFound = true;
3868 Pos += 1 + Argument.size();
3871 // Update the scan point.
3872 Body = Body.substr(Pos);
3875 if (!NamedParametersFound && PositionalParametersFound)
3876 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3877 "used in macro body, possible positional parameter "
3878 "found in body which will have no effect");
3881 /// parseDirectiveExitMacro
3883 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3884 if (parseToken(AsmToken::EndOfStatement,
3885 "unexpected token in '" + Directive + "' directive"))
3888 if (!isInsideMacroInstantiation())
3889 return TokError("unexpected '" + Directive + "' in file, "
3890 "no current macro definition");
3892 // Exit all conditionals that are active in the current macro.
3893 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3894 TheCondState = TheCondStack.back();
3895 TheCondStack.pop_back();
3902 /// parseDirectiveEndMacro
3905 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3906 if (getLexer().isNot(AsmToken::EndOfStatement))
3907 return TokError("unexpected token in '" + Directive + "' directive");
3909 // If we are inside a macro instantiation, terminate the current
3911 if (isInsideMacroInstantiation()) {
3916 // Otherwise, this .endmacro is a stray entry in the file; well formed
3917 // .endmacro directives are handled during the macro definition parsing.
3918 return TokError("unexpected '" + Directive + "' in file, "
3919 "no current macro definition");
3922 /// parseDirectivePurgeMacro
3924 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3927 if (getTokenLoc(Loc) || check(parseIdentifier(Name), Loc,
3928 "expected identifier in '.purgem' directive") ||
3929 parseToken(AsmToken::EndOfStatement,
3930 "unexpected token in '.purgem' directive") ||
3931 check(!lookupMacro(Name), DirectiveLoc,
3932 "macro '" + Name + "' is not defined"))
3935 undefineMacro(Name);
3939 /// parseDirectiveBundleAlignMode
3940 /// ::= {.bundle_align_mode} expression
3941 bool AsmParser::parseDirectiveBundleAlignMode() {
3942 checkForValidSection();
3944 // Expect a single argument: an expression that evaluates to a constant
3945 // in the inclusive range 0-30.
3946 SMLoc ExprLoc = getLexer().getLoc();
3947 int64_t AlignSizePow2;
3948 if (parseAbsoluteExpression(AlignSizePow2) ||
3949 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
3950 "in '.bundle_align_mode' "
3952 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
3953 "invalid bundle alignment size (expected between 0 and 30)"))
3956 // Because of AlignSizePow2's verified range we can safely truncate it to
3958 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3962 /// parseDirectiveBundleLock
3963 /// ::= {.bundle_lock} [align_to_end]
3964 bool AsmParser::parseDirectiveBundleLock() {
3965 checkForValidSection();
3966 bool AlignToEnd = false;
3968 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3970 SMLoc Loc = getTok().getLoc();
3971 const char *kInvalidOptionError =
3972 "invalid option for '.bundle_lock' directive";
3974 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
3975 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
3976 check(getTok().isNot(AsmToken::EndOfStatement), Loc,
3977 "unexpected token after '.bundle_lock' directive option"))
3984 getStreamer().EmitBundleLock(AlignToEnd);
3988 /// parseDirectiveBundleLock
3989 /// ::= {.bundle_lock}
3990 bool AsmParser::parseDirectiveBundleUnlock() {
3991 checkForValidSection();
3993 if (parseToken(AsmToken::EndOfStatement,
3994 "unexpected token in '.bundle_unlock' directive"))
3997 getStreamer().EmitBundleUnlock();
4001 /// parseDirectiveSpace
4002 /// ::= (.skip | .space) expression [ , expression ]
4003 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4004 checkForValidSection();
4006 SMLoc NumBytesLoc = Lexer.getLoc();
4007 const MCExpr *NumBytes;
4008 if (parseExpression(NumBytes))
4011 int64_t FillExpr = 0;
4012 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4014 if (parseToken(AsmToken::Comma,
4015 "unexpected token in '" + Twine(IDVal) + "' directive") ||
4016 parseAbsoluteExpression(FillExpr))
4020 if (parseToken(AsmToken::EndOfStatement,
4021 "unexpected token in '" + Twine(IDVal) + "' directive"))
4024 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4025 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4030 /// parseDirectiveLEB128
4031 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4032 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4033 checkForValidSection();
4034 const MCExpr *Value;
4037 if (parseExpression(Value))
4041 getStreamer().EmitSLEB128Value(Value);
4043 getStreamer().EmitULEB128Value(Value);
4045 if (getLexer().is(AsmToken::EndOfStatement))
4048 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4056 /// parseDirectiveSymbolAttribute
4057 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4058 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4059 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4062 SMLoc Loc = getTok().getLoc();
4064 if (parseIdentifier(Name))
4065 return Error(Loc, "expected identifier in directive");
4067 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4069 // Assembler local symbols don't make any sense here. Complain loudly.
4070 if (Sym->isTemporary())
4071 return Error(Loc, "non-local symbol required in directive");
4073 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4074 return Error(Loc, "unable to emit symbol attribute");
4076 if (getLexer().is(AsmToken::EndOfStatement))
4079 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4088 /// parseDirectiveComm
4089 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4090 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4091 checkForValidSection();
4093 SMLoc IDLoc = getLexer().getLoc();
4095 if (parseIdentifier(Name))
4096 return TokError("expected identifier in directive");
4098 // Handle the identifier as the key symbol.
4099 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4101 if (getLexer().isNot(AsmToken::Comma))
4102 return TokError("unexpected token in directive");
4106 SMLoc SizeLoc = getLexer().getLoc();
4107 if (parseAbsoluteExpression(Size))
4110 int64_t Pow2Alignment = 0;
4111 SMLoc Pow2AlignmentLoc;
4112 if (getLexer().is(AsmToken::Comma)) {
4114 Pow2AlignmentLoc = getLexer().getLoc();
4115 if (parseAbsoluteExpression(Pow2Alignment))
4118 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4119 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4120 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4122 // If this target takes alignments in bytes (not log) validate and convert.
4123 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4124 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4125 if (!isPowerOf2_64(Pow2Alignment))
4126 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4127 Pow2Alignment = Log2_64(Pow2Alignment);
4131 if (getLexer().isNot(AsmToken::EndOfStatement))
4132 return TokError("unexpected token in '.comm' or '.lcomm' directive");
4136 // NOTE: a size of zero for a .comm should create a undefined symbol
4137 // but a size of .lcomm creates a bss symbol of size zero.
4139 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4140 "be less than zero");
4142 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4143 // may internally end up wanting an alignment in bytes.
4144 // FIXME: Diagnose overflow.
4145 if (Pow2Alignment < 0)
4146 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4147 "alignment, can't be less than zero");
4149 if (!Sym->isUndefined())
4150 return Error(IDLoc, "invalid symbol redefinition");
4152 // Create the Symbol as a common or local common with Size and Pow2Alignment
4154 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4158 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4162 /// parseDirectiveAbort
4163 /// ::= .abort [... message ...]
4164 bool AsmParser::parseDirectiveAbort() {
4165 // FIXME: Use loc from directive.
4166 SMLoc Loc = getLexer().getLoc();
4168 StringRef Str = parseStringToEndOfStatement();
4169 if (parseToken(AsmToken::EndOfStatement,
4170 "unexpected token in '.abort' directive"))
4174 Error(Loc, ".abort detected. Assembly stopping.");
4176 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4177 // FIXME: Actually abort assembly here.
4182 /// parseDirectiveInclude
4183 /// ::= .include "filename"
4184 bool AsmParser::parseDirectiveInclude() {
4185 // Allow the strings to have escaped octal character sequence.
4186 std::string Filename;
4187 SMLoc IncludeLoc = getTok().getLoc();
4189 if (check(getTok().isNot(AsmToken::String),
4190 "expected string in '.include' directive") ||
4191 parseEscapedString(Filename) ||
4192 check(getTok().isNot(AsmToken::EndOfStatement),
4193 "unexpected token in '.include' directive") ||
4194 // Attempt to switch the lexer to the included file before consuming the
4195 // end of statement to avoid losing it when we switch.
4196 check(enterIncludeFile(Filename), IncludeLoc,
4197 "Could not find include file '" + Filename + "'"))
4203 /// parseDirectiveIncbin
4204 /// ::= .incbin "filename"
4205 bool AsmParser::parseDirectiveIncbin() {
4206 // Allow the strings to have escaped octal character sequence.
4207 std::string Filename;
4208 SMLoc IncbinLoc = getTok().getLoc();
4209 if (check(getTok().isNot(AsmToken::String),
4210 "expected string in '.incbin' directive") ||
4211 parseEscapedString(Filename) ||
4212 parseToken(AsmToken::EndOfStatement,
4213 "unexpected token in '.incbin' directive") ||
4214 // Attempt to process the included file.
4215 check(processIncbinFile(Filename), IncbinLoc,
4216 "Could not find incbin file '" + Filename + "'"))
4221 /// parseDirectiveIf
4222 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4223 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4224 TheCondStack.push_back(TheCondState);
4225 TheCondState.TheCond = AsmCond::IfCond;
4226 if (TheCondState.Ignore) {
4227 eatToEndOfStatement();
4230 if (parseAbsoluteExpression(ExprValue) ||
4231 parseToken(AsmToken::EndOfStatement,
4232 "unexpected token in '.if' directive"))
4237 llvm_unreachable("unsupported directive");
4242 ExprValue = ExprValue == 0;
4245 ExprValue = ExprValue >= 0;
4248 ExprValue = ExprValue > 0;
4251 ExprValue = ExprValue <= 0;
4254 ExprValue = ExprValue < 0;
4258 TheCondState.CondMet = ExprValue;
4259 TheCondState.Ignore = !TheCondState.CondMet;
4265 /// parseDirectiveIfb
4267 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4268 TheCondStack.push_back(TheCondState);
4269 TheCondState.TheCond = AsmCond::IfCond;
4271 if (TheCondState.Ignore) {
4272 eatToEndOfStatement();
4274 StringRef Str = parseStringToEndOfStatement();
4276 if (parseToken(AsmToken::EndOfStatement,
4277 "unexpected token in '.ifb' directive"))
4280 TheCondState.CondMet = ExpectBlank == Str.empty();
4281 TheCondState.Ignore = !TheCondState.CondMet;
4287 /// parseDirectiveIfc
4288 /// ::= .ifc string1, string2
4289 /// ::= .ifnc string1, string2
4290 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4291 TheCondStack.push_back(TheCondState);
4292 TheCondState.TheCond = AsmCond::IfCond;
4294 if (TheCondState.Ignore) {
4295 eatToEndOfStatement();
4297 StringRef Str1 = parseStringToComma();
4299 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4302 StringRef Str2 = parseStringToEndOfStatement();
4304 if (parseToken(AsmToken::EndOfStatement,
4305 "unexpected token in '.ifc' directive"))
4308 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4309 TheCondState.Ignore = !TheCondState.CondMet;
4315 /// parseDirectiveIfeqs
4316 /// ::= .ifeqs string1, string2
4317 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4318 if (Lexer.isNot(AsmToken::String)) {
4320 TokError("expected string parameter for '.ifeqs' directive");
4322 TokError("expected string parameter for '.ifnes' directive");
4323 eatToEndOfStatement();
4327 StringRef String1 = getTok().getStringContents();
4330 if (Lexer.isNot(AsmToken::Comma)) {
4332 TokError("expected comma after first string for '.ifeqs' directive");
4334 TokError("expected comma after first string for '.ifnes' directive");
4335 eatToEndOfStatement();
4341 if (Lexer.isNot(AsmToken::String)) {
4343 TokError("expected string parameter for '.ifeqs' directive");
4345 TokError("expected string parameter for '.ifnes' directive");
4346 eatToEndOfStatement();
4350 StringRef String2 = getTok().getStringContents();
4353 TheCondStack.push_back(TheCondState);
4354 TheCondState.TheCond = AsmCond::IfCond;
4355 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4356 TheCondState.Ignore = !TheCondState.CondMet;
4361 /// parseDirectiveIfdef
4362 /// ::= .ifdef symbol
4363 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4365 TheCondStack.push_back(TheCondState);
4366 TheCondState.TheCond = AsmCond::IfCond;
4368 if (TheCondState.Ignore) {
4369 eatToEndOfStatement();
4371 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4372 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4375 MCSymbol *Sym = getContext().lookupSymbol(Name);
4378 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4380 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4381 TheCondState.Ignore = !TheCondState.CondMet;
4387 /// parseDirectiveElseIf
4388 /// ::= .elseif expression
4389 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4390 if (TheCondState.TheCond != AsmCond::IfCond &&
4391 TheCondState.TheCond != AsmCond::ElseIfCond)
4392 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4394 TheCondState.TheCond = AsmCond::ElseIfCond;
4396 bool LastIgnoreState = false;
4397 if (!TheCondStack.empty())
4398 LastIgnoreState = TheCondStack.back().Ignore;
4399 if (LastIgnoreState || TheCondState.CondMet) {
4400 TheCondState.Ignore = true;
4401 eatToEndOfStatement();
4404 if (parseAbsoluteExpression(ExprValue))
4407 if (getLexer().isNot(AsmToken::EndOfStatement))
4408 return TokError("unexpected token in '.elseif' directive");
4411 TheCondState.CondMet = ExprValue;
4412 TheCondState.Ignore = !TheCondState.CondMet;
4418 /// parseDirectiveElse
4420 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4421 if (parseToken(AsmToken::EndOfStatement,
4422 "unexpected token in '.else' directive"))
4425 if (TheCondState.TheCond != AsmCond::IfCond &&
4426 TheCondState.TheCond != AsmCond::ElseIfCond)
4427 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4429 TheCondState.TheCond = AsmCond::ElseCond;
4430 bool LastIgnoreState = false;
4431 if (!TheCondStack.empty())
4432 LastIgnoreState = TheCondStack.back().Ignore;
4433 if (LastIgnoreState || TheCondState.CondMet)
4434 TheCondState.Ignore = true;
4436 TheCondState.Ignore = false;
4441 /// parseDirectiveEnd
4443 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4444 if (parseToken(AsmToken::EndOfStatement,
4445 "unexpected token in '.end' directive"))
4448 while (Lexer.isNot(AsmToken::Eof))
4454 /// parseDirectiveError
4456 /// ::= .error [string]
4457 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4458 if (!TheCondStack.empty()) {
4459 if (TheCondStack.back().Ignore) {
4460 eatToEndOfStatement();
4466 return Error(L, ".err encountered");
4468 StringRef Message = ".error directive invoked in source file";
4469 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4470 if (Lexer.isNot(AsmToken::String)) {
4471 TokError(".error argument must be a string");
4472 eatToEndOfStatement();
4476 Message = getTok().getStringContents();
4484 /// parseDirectiveWarning
4485 /// ::= .warning [string]
4486 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4487 if (!TheCondStack.empty()) {
4488 if (TheCondStack.back().Ignore) {
4489 eatToEndOfStatement();
4494 StringRef Message = ".warning directive invoked in source file";
4495 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4496 if (Lexer.isNot(AsmToken::String)) {
4497 TokError(".warning argument must be a string");
4498 eatToEndOfStatement();
4502 Message = getTok().getStringContents();
4506 Warning(L, Message);
4510 /// parseDirectiveEndIf
4512 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4513 if (parseToken(AsmToken::EndOfStatement,
4514 "unexpected token in '.endif' directive"))
4517 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4518 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4520 if (!TheCondStack.empty()) {
4521 TheCondState = TheCondStack.back();
4522 TheCondStack.pop_back();
4528 void AsmParser::initializeDirectiveKindMap() {
4529 DirectiveKindMap[".set"] = DK_SET;
4530 DirectiveKindMap[".equ"] = DK_EQU;
4531 DirectiveKindMap[".equiv"] = DK_EQUIV;
4532 DirectiveKindMap[".ascii"] = DK_ASCII;
4533 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4534 DirectiveKindMap[".string"] = DK_STRING;
4535 DirectiveKindMap[".byte"] = DK_BYTE;
4536 DirectiveKindMap[".short"] = DK_SHORT;
4537 DirectiveKindMap[".value"] = DK_VALUE;
4538 DirectiveKindMap[".2byte"] = DK_2BYTE;
4539 DirectiveKindMap[".long"] = DK_LONG;
4540 DirectiveKindMap[".int"] = DK_INT;
4541 DirectiveKindMap[".4byte"] = DK_4BYTE;
4542 DirectiveKindMap[".quad"] = DK_QUAD;
4543 DirectiveKindMap[".8byte"] = DK_8BYTE;
4544 DirectiveKindMap[".octa"] = DK_OCTA;
4545 DirectiveKindMap[".single"] = DK_SINGLE;
4546 DirectiveKindMap[".float"] = DK_FLOAT;
4547 DirectiveKindMap[".double"] = DK_DOUBLE;
4548 DirectiveKindMap[".align"] = DK_ALIGN;
4549 DirectiveKindMap[".align32"] = DK_ALIGN32;
4550 DirectiveKindMap[".balign"] = DK_BALIGN;
4551 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4552 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4553 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4554 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4555 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4556 DirectiveKindMap[".org"] = DK_ORG;
4557 DirectiveKindMap[".fill"] = DK_FILL;
4558 DirectiveKindMap[".zero"] = DK_ZERO;
4559 DirectiveKindMap[".extern"] = DK_EXTERN;
4560 DirectiveKindMap[".globl"] = DK_GLOBL;
4561 DirectiveKindMap[".global"] = DK_GLOBAL;
4562 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4563 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4564 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4565 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4566 DirectiveKindMap[".reference"] = DK_REFERENCE;
4567 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4568 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4569 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4570 DirectiveKindMap[".comm"] = DK_COMM;
4571 DirectiveKindMap[".common"] = DK_COMMON;
4572 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4573 DirectiveKindMap[".abort"] = DK_ABORT;
4574 DirectiveKindMap[".include"] = DK_INCLUDE;
4575 DirectiveKindMap[".incbin"] = DK_INCBIN;
4576 DirectiveKindMap[".code16"] = DK_CODE16;
4577 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4578 DirectiveKindMap[".rept"] = DK_REPT;
4579 DirectiveKindMap[".rep"] = DK_REPT;
4580 DirectiveKindMap[".irp"] = DK_IRP;
4581 DirectiveKindMap[".irpc"] = DK_IRPC;
4582 DirectiveKindMap[".endr"] = DK_ENDR;
4583 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4584 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4585 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4586 DirectiveKindMap[".if"] = DK_IF;
4587 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4588 DirectiveKindMap[".ifge"] = DK_IFGE;
4589 DirectiveKindMap[".ifgt"] = DK_IFGT;
4590 DirectiveKindMap[".ifle"] = DK_IFLE;
4591 DirectiveKindMap[".iflt"] = DK_IFLT;
4592 DirectiveKindMap[".ifne"] = DK_IFNE;
4593 DirectiveKindMap[".ifb"] = DK_IFB;
4594 DirectiveKindMap[".ifnb"] = DK_IFNB;
4595 DirectiveKindMap[".ifc"] = DK_IFC;
4596 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4597 DirectiveKindMap[".ifnc"] = DK_IFNC;
4598 DirectiveKindMap[".ifnes"] = DK_IFNES;
4599 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4600 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4601 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4602 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4603 DirectiveKindMap[".else"] = DK_ELSE;
4604 DirectiveKindMap[".end"] = DK_END;
4605 DirectiveKindMap[".endif"] = DK_ENDIF;
4606 DirectiveKindMap[".skip"] = DK_SKIP;
4607 DirectiveKindMap[".space"] = DK_SPACE;
4608 DirectiveKindMap[".file"] = DK_FILE;
4609 DirectiveKindMap[".line"] = DK_LINE;
4610 DirectiveKindMap[".loc"] = DK_LOC;
4611 DirectiveKindMap[".stabs"] = DK_STABS;
4612 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4613 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4614 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4615 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
4616 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
4617 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4618 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
4619 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4620 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4621 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4622 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4623 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4624 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4625 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4626 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4627 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4628 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4629 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4630 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4631 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4632 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4633 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4634 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4635 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4636 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4637 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4638 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4639 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4640 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4641 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4642 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4643 DirectiveKindMap[".macro"] = DK_MACRO;
4644 DirectiveKindMap[".exitm"] = DK_EXITM;
4645 DirectiveKindMap[".endm"] = DK_ENDM;
4646 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4647 DirectiveKindMap[".purgem"] = DK_PURGEM;
4648 DirectiveKindMap[".err"] = DK_ERR;
4649 DirectiveKindMap[".error"] = DK_ERROR;
4650 DirectiveKindMap[".warning"] = DK_WARNING;
4651 DirectiveKindMap[".reloc"] = DK_RELOC;
4654 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4655 AsmToken EndToken, StartToken = getTok();
4657 unsigned NestLevel = 0;
4659 // Check whether we have reached the end of the file.
4660 if (getLexer().is(AsmToken::Eof)) {
4661 Error(DirectiveLoc, "no matching '.endr' in definition");
4665 if (Lexer.is(AsmToken::Identifier) &&
4666 (getTok().getIdentifier() == ".rept" ||
4667 getTok().getIdentifier() == ".irp" ||
4668 getTok().getIdentifier() == ".irpc")) {
4672 // Otherwise, check whether we have reached the .endr.
4673 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4674 if (NestLevel == 0) {
4675 EndToken = getTok();
4677 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4678 TokError("unexpected token in '.endr' directive");
4686 // Otherwise, scan till the end of the statement.
4687 eatToEndOfStatement();
4690 const char *BodyStart = StartToken.getLoc().getPointer();
4691 const char *BodyEnd = EndToken.getLoc().getPointer();
4692 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4694 // We Are Anonymous.
4695 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4696 return &MacroLikeBodies.back();
4699 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4700 raw_svector_ostream &OS) {
4703 std::unique_ptr<MemoryBuffer> Instantiation =
4704 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4706 // Create the macro instantiation object and add to the current macro
4707 // instantiation stack.
4708 MacroInstantiation *MI = new MacroInstantiation(
4709 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4710 ActiveMacros.push_back(MI);
4712 // Jump to the macro instantiation and prime the lexer.
4713 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4714 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4718 /// parseDirectiveRept
4719 /// ::= .rep | .rept count
4720 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4721 const MCExpr *CountExpr;
4722 SMLoc CountLoc = getTok().getLoc();
4723 if (parseExpression(CountExpr))
4727 if (!CountExpr->evaluateAsAbsolute(Count)) {
4728 eatToEndOfStatement();
4729 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4732 if (check(Count < 0, CountLoc, "Count is negative") ||
4733 parseToken(AsmToken::EndOfStatement,
4734 "unexpected token in '" + Dir + "' directive"))
4737 // Lex the rept definition.
4738 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4742 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4743 // to hold the macro body with substitutions.
4744 SmallString<256> Buf;
4745 raw_svector_ostream OS(Buf);
4747 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4748 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4751 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4756 /// parseDirectiveIrp
4757 /// ::= .irp symbol,values
4758 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4759 MCAsmMacroParameter Parameter;
4760 MCAsmMacroArguments A;
4761 if (check(parseIdentifier(Parameter.Name),
4762 "expected identifier in '.irp' directive") ||
4763 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
4764 parseMacroArguments(nullptr, A) ||
4765 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
4768 // Lex the irp definition.
4769 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4773 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4774 // to hold the macro body with substitutions.
4775 SmallString<256> Buf;
4776 raw_svector_ostream OS(Buf);
4778 for (const MCAsmMacroArgument &Arg : A) {
4779 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4780 // This is undocumented, but GAS seems to support it.
4781 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4785 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4790 /// parseDirectiveIrpc
4791 /// ::= .irpc symbol,values
4792 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4793 MCAsmMacroParameter Parameter;
4794 MCAsmMacroArguments A;
4796 if (check(parseIdentifier(Parameter.Name),
4797 "expected identifier in '.irpc' directive") ||
4798 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
4799 parseMacroArguments(nullptr, A))
4802 if (A.size() != 1 || A.front().size() != 1)
4803 return TokError("unexpected token in '.irpc' directive");
4805 // Eat the end of statement.
4806 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
4809 // Lex the irpc definition.
4810 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4814 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4815 // to hold the macro body with substitutions.
4816 SmallString<256> Buf;
4817 raw_svector_ostream OS(Buf);
4819 StringRef Values = A.front().front().getString();
4820 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4821 MCAsmMacroArgument Arg;
4822 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4824 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4825 // This is undocumented, but GAS seems to support it.
4826 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4830 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4835 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4836 if (ActiveMacros.empty())
4837 return TokError("unmatched '.endr' directive");
4839 // The only .repl that should get here are the ones created by
4840 // instantiateMacroLikeBody.
4841 assert(getLexer().is(AsmToken::EndOfStatement));
4847 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4849 const MCExpr *Value;
4850 SMLoc ExprLoc = getLexer().getLoc();
4851 if (parseExpression(Value))
4853 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4855 return Error(ExprLoc, "unexpected expression in _emit");
4856 uint64_t IntValue = MCE->getValue();
4857 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
4858 return Error(ExprLoc, "literal value out of range for directive");
4860 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
4864 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4865 const MCExpr *Value;
4866 SMLoc ExprLoc = getLexer().getLoc();
4867 if (parseExpression(Value))
4869 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4871 return Error(ExprLoc, "unexpected expression in align");
4872 uint64_t IntValue = MCE->getValue();
4873 if (!isPowerOf2_64(IntValue))
4874 return Error(ExprLoc, "literal value not a power of two greater then zero");
4876 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
4880 // We are comparing pointers, but the pointers are relative to a single string.
4881 // Thus, this should always be deterministic.
4882 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4883 const AsmRewrite *AsmRewriteB) {
4884 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4886 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4889 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4890 // rewrite to the same location. Make sure the SizeDirective rewrite is
4891 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4892 // ensures the sort algorithm is stable.
4893 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4894 AsmRewritePrecedence[AsmRewriteB->Kind])
4897 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4898 AsmRewritePrecedence[AsmRewriteB->Kind])
4900 llvm_unreachable("Unstable rewrite sort.");
4903 bool AsmParser::parseMSInlineAsm(
4904 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4905 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4906 SmallVectorImpl<std::string> &Constraints,
4907 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4908 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4909 SmallVector<void *, 4> InputDecls;
4910 SmallVector<void *, 4> OutputDecls;
4911 SmallVector<bool, 4> InputDeclsAddressOf;
4912 SmallVector<bool, 4> OutputDeclsAddressOf;
4913 SmallVector<std::string, 4> InputConstraints;
4914 SmallVector<std::string, 4> OutputConstraints;
4915 SmallVector<unsigned, 4> ClobberRegs;
4917 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4922 // While we have input, parse each statement.
4923 unsigned InputIdx = 0;
4924 unsigned OutputIdx = 0;
4925 while (getLexer().isNot(AsmToken::Eof)) {
4926 // Parse curly braces marking block start/end
4927 if (parseCurlyBlockScope(AsmStrRewrites))
4930 ParseStatementInfo Info(&AsmStrRewrites);
4931 if (parseStatement(Info, &SI))
4934 if (Info.ParseError)
4937 if (Info.Opcode == ~0U)
4940 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4942 // Build the list of clobbers, outputs and inputs.
4943 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4944 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4947 if (Operand.isImm())
4950 // Register operand.
4951 if (Operand.isReg() && !Operand.needAddressOf() &&
4952 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4953 unsigned NumDefs = Desc.getNumDefs();
4955 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4956 ClobberRegs.push_back(Operand.getReg());
4960 // Expr/Input or Output.
4961 StringRef SymName = Operand.getSymName();
4962 if (SymName.empty())
4965 void *OpDecl = Operand.getOpDecl();
4969 bool isOutput = (i == 1) && Desc.mayStore();
4970 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4973 OutputDecls.push_back(OpDecl);
4974 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4975 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4976 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
4978 InputDecls.push_back(OpDecl);
4979 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4980 InputConstraints.push_back(Operand.getConstraint().str());
4981 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
4985 // Consider implicit defs to be clobbers. Think of cpuid and push.
4986 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4987 Desc.getNumImplicitDefs());
4988 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4991 // Set the number of Outputs and Inputs.
4992 NumOutputs = OutputDecls.size();
4993 NumInputs = InputDecls.size();
4995 // Set the unique clobbers.
4996 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4997 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4999 Clobbers.assign(ClobberRegs.size(), std::string());
5000 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5001 raw_string_ostream OS(Clobbers[I]);
5002 IP->printRegName(OS, ClobberRegs[I]);
5005 // Merge the various outputs and inputs. Output are expected first.
5006 if (NumOutputs || NumInputs) {
5007 unsigned NumExprs = NumOutputs + NumInputs;
5008 OpDecls.resize(NumExprs);
5009 Constraints.resize(NumExprs);
5010 for (unsigned i = 0; i < NumOutputs; ++i) {
5011 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5012 Constraints[i] = OutputConstraints[i];
5014 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5015 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5016 Constraints[j] = InputConstraints[i];
5020 // Build the IR assembly string.
5021 std::string AsmStringIR;
5022 raw_string_ostream OS(AsmStringIR);
5023 StringRef ASMString =
5024 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5025 const char *AsmStart = ASMString.begin();
5026 const char *AsmEnd = ASMString.end();
5027 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5028 for (const AsmRewrite &AR : AsmStrRewrites) {
5029 AsmRewriteKind Kind = AR.Kind;
5030 if (Kind == AOK_Delete)
5033 const char *Loc = AR.Loc.getPointer();
5034 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5036 // Emit everything up to the immediate/expression.
5037 if (unsigned Len = Loc - AsmStart)
5038 OS << StringRef(AsmStart, Len);
5040 // Skip the original expression.
5041 if (Kind == AOK_Skip) {
5042 AsmStart = Loc + AR.Len;
5046 unsigned AdditionalSkip = 0;
5047 // Rewrite expressions in $N notation.
5052 OS << "$$" << AR.Val;
5058 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5061 OS << '$' << InputIdx++;
5064 OS << '$' << OutputIdx++;
5066 case AOK_SizeDirective:
5069 case 8: OS << "byte ptr "; break;
5070 case 16: OS << "word ptr "; break;
5071 case 32: OS << "dword ptr "; break;
5072 case 64: OS << "qword ptr "; break;
5073 case 80: OS << "xword ptr "; break;
5074 case 128: OS << "xmmword ptr "; break;
5075 case 256: OS << "ymmword ptr "; break;
5082 // MS alignment directives are measured in bytes. If the native assembler
5083 // measures alignment in bytes, we can pass it straight through.
5085 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5088 // Alignment is in log2 form, so print that instead and skip the original
5090 unsigned Val = AR.Val;
5092 assert(Val < 10 && "Expected alignment less then 2^10.");
5093 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5099 case AOK_DotOperator:
5100 // Insert the dot if the user omitted it.
5102 if (AsmStringIR.back() != '.')
5106 case AOK_EndOfStatement:
5111 // Skip the original expression.
5112 AsmStart = Loc + AR.Len + AdditionalSkip;
5115 // Emit the remainder of the asm string.
5116 if (AsmStart != AsmEnd)
5117 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5119 AsmString = OS.str();
5124 namespace MCParserUtils {
5126 /// Returns whether the given symbol is used anywhere in the given expression,
5127 /// or subexpressions.
5128 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5129 switch (Value->getKind()) {
5130 case MCExpr::Binary: {
5131 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5132 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5133 isSymbolUsedInExpression(Sym, BE->getRHS());
5135 case MCExpr::Target:
5136 case MCExpr::Constant:
5138 case MCExpr::SymbolRef: {
5140 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5142 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5146 return isSymbolUsedInExpression(
5147 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5150 llvm_unreachable("Unknown expr kind!");
5153 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5154 MCAsmParser &Parser, MCSymbol *&Sym,
5155 const MCExpr *&Value) {
5157 // FIXME: Use better location, we should use proper tokens.
5158 SMLoc EqualLoc = Parser.getTok().getLoc();
5160 if (Parser.parseExpression(Value)) {
5161 Parser.TokError("missing expression");
5162 Parser.eatToEndOfStatement();
5166 // Note: we don't count b as used in "a = b". This is to allow
5170 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
5171 return Parser.TokError("unexpected token in assignment");
5173 // Eat the end of statement marker.
5176 // Validate that the LHS is allowed to be a variable (either it has not been
5177 // used as a symbol, or it is an absolute symbol).
5178 Sym = Parser.getContext().lookupSymbol(Name);
5180 // Diagnose assignment to a label.
5182 // FIXME: Diagnostics. Note the location of the definition as a label.
5183 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5184 if (isSymbolUsedInExpression(Sym, Value))
5185 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5186 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5188 ; // Allow redefinitions of undefined symbols only used in directives.
5189 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5190 ; // Allow redefinitions of variables that haven't yet been used.
5191 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5192 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5193 else if (!Sym->isVariable())
5194 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5195 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5196 return Parser.Error(EqualLoc,
5197 "invalid reassignment of non-absolute variable '" +
5199 } else if (Name == ".") {
5200 Parser.getStreamer().emitValueToOffset(Value, 0);
5203 Sym = Parser.getContext().getOrCreateSymbol(Name);
5205 Sym->setRedefinable(allow_redef);
5210 } // namespace MCParserUtils
5213 /// \brief Create an MCAsmParser instance.
5214 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5215 MCStreamer &Out, const MCAsmInfo &MAI) {
5216 return new AsmParser(SM, C, Out, MAI);