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/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCCodeView.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDirectives.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCParser/AsmCond.h"
35 #include "llvm/MC/MCParser/AsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmParser.h"
38 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
39 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
40 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCSection.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/MC/MCTargetOptions.h"
47 #include "llvm/MC/MCValue.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/MemoryBuffer.h"
54 #include "llvm/Support/SMLoc.h"
55 #include "llvm/Support/SourceMgr.h"
56 #include "llvm/Support/raw_ostream.h"
73 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
75 static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
81 /// \brief Helper types for tracking macro definitions.
82 typedef std::vector<AsmToken> MCAsmMacroArgument;
83 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
85 struct MCAsmMacroParameter {
87 MCAsmMacroArgument Value;
88 bool Required = false;
91 MCAsmMacroParameter() = default;
94 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
99 MCAsmMacroParameters Parameters;
102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
106 /// \brief Helper class for storing information about an active macro
108 struct MacroInstantiation {
109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
112 /// The buffer where parsing should resume upon instantiation completion.
115 /// The location where parsing should resume upon instantiation completion.
118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
125 struct ParseStatementInfo {
126 /// \brief The parsed operands from the last parsed statement.
127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
129 /// \brief The opcode from the last parsed instruction.
130 unsigned Opcode = ~0U;
132 /// \brief Was there an error parsing the inline assembly?
133 bool ParseError = false;
135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
137 ParseStatementInfo() = delete;
138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
139 : AsmRewrites(rewrites) {}
142 /// \brief The concrete assembly parser instance.
143 class AsmParser : public MCAsmParser {
148 const MCAsmInfo &MAI;
150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
161 /// \brief maps directive names to handler methods in parser
162 /// extensions. Extensions register themselves in this map by calling
163 /// addDirectiveHandler.
164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
166 /// \brief Map of currently defined macros.
167 StringMap<MCAsmMacro> MacroMap;
169 /// \brief Stack of active macro instantiations.
170 std::vector<MacroInstantiation*> ActiveMacros;
172 /// \brief List of bodies of anonymous macros.
173 std::deque<MCAsmMacro> MacroLikeBodies;
175 /// Boolean tracking whether macro substitution is enabled.
176 unsigned MacrosEnabledFlag : 1;
178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
181 /// The values from the last parsed cpp hash file line comment if any.
182 struct CppHashInfoTy {
184 int64_t LineNumber = 0;
188 CppHashInfoTy CppHashInfo;
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
195 /// and current line. Since this is slow and messes up the SourceMgr's
196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
198 unsigned LastQueryBuffer;
199 unsigned LastQueryLine;
201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
202 unsigned AssemblerDialect = ~0U;
204 /// \brief is Darwin compatibility enabled?
205 bool IsDarwin = false;
207 /// \brief Are we parsing ms-style inline assembly?
208 bool ParsingInlineAsm = false;
211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
212 const MCAsmInfo &MAI, unsigned CB);
213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
215 ~AsmParser() override;
217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
221 ExtensionDirectiveMap[Directive] = Handler;
224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
228 /// @name MCAsmParser Interface
231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
238 unsigned getAssemblerDialect() override {
239 if (AssemblerDialect == ~0U)
240 return MAI.getAssemblerDialect();
242 return AssemblerDialect;
244 void setAssemblerDialect(unsigned i) override {
245 AssemblerDialect = i;
248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
252 const AsmToken &Lex() override;
254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
261 unsigned &NumOutputs, unsigned &NumInputs,
262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
263 SmallVectorImpl<std::string> &Constraints,
264 SmallVectorImpl<std::string> &Clobbers,
265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
268 bool parseExpression(const MCExpr *&Res);
269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
274 bool parseAbsoluteExpression(int64_t &Res) override;
276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
280 /// \brief Parse an identifier or string (as a quoted identifier)
281 /// and set \p Res to the identifier contents.
282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
285 bool checkForValidSection() override;
290 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
291 bool parseStatement(ParseStatementInfo &Info,
292 MCAsmParserSemaCallback *SI);
293 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
294 bool parseCppHashLineFilenameComment(SMLoc L);
296 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
297 ArrayRef<MCAsmMacroParameter> Parameters);
298 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
299 ArrayRef<MCAsmMacroParameter> Parameters,
300 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
303 /// \brief Are macros enabled in the parser?
304 bool areMacrosEnabled() {return MacrosEnabledFlag;}
306 /// \brief Control a flag in the parser that enables or disables macros.
307 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
309 /// \brief Lookup a previously defined macro.
310 /// \param Name Macro name.
311 /// \returns Pointer to macro. NULL if no such macro was defined.
312 const MCAsmMacro* lookupMacro(StringRef Name);
314 /// \brief Define a new macro with the given name and information.
315 void defineMacro(StringRef Name, MCAsmMacro Macro);
317 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
318 void undefineMacro(StringRef Name);
320 /// \brief Are we inside a macro instantiation?
321 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
323 /// \brief Handle entry to macro instantiation.
325 /// \param M The macro.
326 /// \param NameLoc Instantiation location.
327 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
329 /// \brief Handle exit from macro instantiation.
330 void handleMacroExit();
332 /// \brief Extract AsmTokens for a macro argument.
333 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
335 /// \brief Parse all macro arguments for a given macro.
336 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
338 void printMacroInstantiations();
339 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
340 SMRange Range = None) const {
341 ArrayRef<SMRange> Ranges(Range);
342 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
344 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
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, int64_t Skip = 0,
352 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
354 /// \brief Reset the current lexer position to that given by \p Loc. The
355 /// current token is not set; clients should ensure Lex() is called
358 /// \param InBuffer If not 0, should be the known buffer id that contains the
360 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
362 /// \brief Parse up to the end of statement and a return the contents from the
363 /// current token until the end of the statement; the current token on exit
364 /// will be either the EndOfStatement or EOF.
365 StringRef parseStringToEndOfStatement() override;
367 /// \brief Parse until the end of a statement or a comma is encountered,
368 /// return the contents from the current token up to the end or comma.
369 StringRef parseStringToComma();
371 bool parseAssignment(StringRef Name, bool allow_redef,
372 bool NoDeadStrip = false);
374 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
375 MCBinaryExpr::Opcode &Kind);
377 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
379 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
381 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
383 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
384 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
386 // Generic (target and platform independent) directive parsing.
388 DK_NO_DIRECTIVE, // Placeholder
389 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
391 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
392 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
393 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
394 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
395 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
396 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
397 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
398 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
399 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
400 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
401 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
402 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
403 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
404 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
405 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
406 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
407 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
408 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
410 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
411 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
412 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
413 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
414 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
415 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
416 DK_MACROS_ON, DK_MACROS_OFF, DK_ALTMACRO, DK_NOALTMACRO,
417 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
418 DK_SLEB128, DK_ULEB128,
419 DK_ERR, DK_ERROR, DK_WARNING,
423 /// \brief Maps directive name --> DirectiveKind enum, for
424 /// directives parsed by this class.
425 StringMap<DirectiveKind> DirectiveKindMap;
427 // ".ascii", ".asciz", ".string"
428 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
429 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
430 bool parseDirectiveValue(StringRef IDVal,
431 unsigned Size); // ".byte", ".long", ...
432 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
433 bool parseDirectiveRealValue(StringRef IDVal,
434 const fltSemantics &); // ".single", ...
435 bool parseDirectiveFill(); // ".fill"
436 bool parseDirectiveZero(); // ".zero"
437 // ".set", ".equ", ".equiv"
438 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
439 bool parseDirectiveOrg(); // ".org"
440 // ".align{,32}", ".p2align{,w,l}"
441 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
443 // ".file", ".line", ".loc", ".stabs"
444 bool parseDirectiveFile(SMLoc DirectiveLoc);
445 bool parseDirectiveLine();
446 bool parseDirectiveLoc();
447 bool parseDirectiveStabs();
449 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
450 // ".cv_inline_linetable", ".cv_def_range"
451 bool parseDirectiveCVFile();
452 bool parseDirectiveCVFuncId();
453 bool parseDirectiveCVInlineSiteId();
454 bool parseDirectiveCVLoc();
455 bool parseDirectiveCVLinetable();
456 bool parseDirectiveCVInlineLinetable();
457 bool parseDirectiveCVDefRange();
458 bool parseDirectiveCVStringTable();
459 bool parseDirectiveCVFileChecksums();
462 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
463 bool parseDirectiveCFIWindowSave();
464 bool parseDirectiveCFISections();
465 bool parseDirectiveCFIStartProc();
466 bool parseDirectiveCFIEndProc();
467 bool parseDirectiveCFIDefCfaOffset();
468 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
469 bool parseDirectiveCFIAdjustCfaOffset();
470 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
473 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
474 bool parseDirectiveCFIRememberState();
475 bool parseDirectiveCFIRestoreState();
476 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
478 bool parseDirectiveCFIEscape();
479 bool parseDirectiveCFISignalFrame();
480 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
483 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
484 bool parseDirectiveExitMacro(StringRef Directive);
485 bool parseDirectiveEndMacro(StringRef Directive);
486 bool parseDirectiveMacro(SMLoc DirectiveLoc);
487 bool parseDirectiveMacrosOnOff(StringRef Directive);
488 // alternate macro mode directives
489 bool parseDirectiveAltmacro(StringRef Directive);
490 // ".bundle_align_mode"
491 bool parseDirectiveBundleAlignMode();
493 bool parseDirectiveBundleLock();
495 bool parseDirectiveBundleUnlock();
498 bool parseDirectiveSpace(StringRef IDVal);
501 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
502 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
504 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
506 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
507 bool parseDirectiveLEB128(bool Signed);
509 /// \brief Parse a directive like ".globl" which
510 /// accepts a single symbol (which should be a label or an external).
511 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
513 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
515 bool parseDirectiveAbort(); // ".abort"
516 bool parseDirectiveInclude(); // ".include"
517 bool parseDirectiveIncbin(); // ".incbin"
519 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
520 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
521 // ".ifb" or ".ifnb", depending on ExpectBlank.
522 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
523 // ".ifc" or ".ifnc", depending on ExpectEqual.
524 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
525 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
526 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
527 // ".ifdef" or ".ifndef", depending on expect_defined
528 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
529 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
530 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
531 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
532 bool parseEscapedString(std::string &Data) override;
534 const MCExpr *applyModifierToExpr(const MCExpr *E,
535 MCSymbolRefExpr::VariantKind Variant);
537 // Macro-like directives
538 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
539 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
540 raw_svector_ostream &OS);
541 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
542 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
543 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
544 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
546 // "_emit" or "__emit"
547 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
551 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
554 bool parseDirectiveEnd(SMLoc DirectiveLoc);
556 // ".err" or ".error"
557 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
560 bool parseDirectiveWarning(SMLoc DirectiveLoc);
562 void initializeDirectiveKindMap();
565 } // end anonymous namespace
569 extern MCAsmParserExtension *createDarwinAsmParser();
570 extern MCAsmParserExtension *createELFAsmParser();
571 extern MCAsmParserExtension *createCOFFAsmParser();
573 } // end namespace llvm
575 enum { DEFAULT_ADDRSPACE = 0 };
577 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
578 const MCAsmInfo &MAI, unsigned CB = 0)
579 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
580 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
582 // Save the old handler.
583 SavedDiagHandler = SrcMgr.getDiagHandler();
584 SavedDiagContext = SrcMgr.getDiagContext();
585 // Set our own handler which calls the saved handler.
586 SrcMgr.setDiagHandler(DiagHandler, this);
587 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
589 // Initialize the platform / file format parser.
590 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
591 case MCObjectFileInfo::IsCOFF:
592 PlatformParser.reset(createCOFFAsmParser());
594 case MCObjectFileInfo::IsMachO:
595 PlatformParser.reset(createDarwinAsmParser());
598 case MCObjectFileInfo::IsELF:
599 PlatformParser.reset(createELFAsmParser());
601 case MCObjectFileInfo::IsWasm:
602 llvm_unreachable("Wasm parsing not supported yet");
606 PlatformParser->Initialize(*this);
607 initializeDirectiveKindMap();
609 NumOfMacroInstantiations = 0;
612 AsmParser::~AsmParser() {
613 assert((HadError || ActiveMacros.empty()) &&
614 "Unexpected active macro instantiation!");
616 // Restore the saved diagnostics handler and context for use during
618 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
621 void AsmParser::printMacroInstantiations() {
622 // Print the active macro instantiation stack.
623 for (std::vector<MacroInstantiation *>::const_reverse_iterator
624 it = ActiveMacros.rbegin(),
625 ie = ActiveMacros.rend();
627 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
628 "while in macro instantiation");
631 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
632 printPendingErrors();
633 printMessage(L, SourceMgr::DK_Note, Msg, Range);
634 printMacroInstantiations();
637 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
638 if(getTargetParser().getTargetOptions().MCNoWarn)
640 if (getTargetParser().getTargetOptions().MCFatalWarnings)
641 return Error(L, Msg, Range);
642 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
643 printMacroInstantiations();
647 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
649 printMessage(L, SourceMgr::DK_Error, Msg, Range);
650 printMacroInstantiations();
654 bool AsmParser::enterIncludeFile(const std::string &Filename) {
655 std::string IncludedFile;
657 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
662 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
666 /// Process the specified .incbin file by searching for it in the include paths
667 /// then just emitting the byte contents of the file to the streamer. This
668 /// returns true on failure.
669 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
670 const MCExpr *Count, SMLoc Loc) {
671 std::string IncludedFile;
673 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
677 // Pick up the bytes from the file and emit them.
678 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
679 Bytes = Bytes.drop_front(Skip);
682 if (!Count->evaluateAsAbsolute(Res))
683 return Error(Loc, "expected absolute expression");
685 return Warning(Loc, "negative count has no effect");
686 Bytes = Bytes.take_front(Res);
688 getStreamer().EmitBytes(Bytes);
692 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
693 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
694 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
698 const AsmToken &AsmParser::Lex() {
699 if (Lexer.getTok().is(AsmToken::Error))
700 Error(Lexer.getErrLoc(), Lexer.getErr());
702 // if it's a end of statement with a comment in it
703 if (getTok().is(AsmToken::EndOfStatement)) {
704 // if this is a line comment output it.
705 if (getTok().getString().front() != '\n' &&
706 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
707 Out.addExplicitComment(Twine(getTok().getString()));
710 const AsmToken *tok = &Lexer.Lex();
712 // Parse comments here to be deferred until end of next statement.
713 while (tok->is(AsmToken::Comment)) {
714 if (MAI.preserveAsmComments())
715 Out.addExplicitComment(Twine(tok->getString()));
719 if (tok->is(AsmToken::Eof)) {
720 // If this is the end of an included file, pop the parent file off the
722 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
723 if (ParentIncludeLoc != SMLoc()) {
724 jumpToLoc(ParentIncludeLoc);
732 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
733 // Create the initial section, if requested.
734 if (!NoInitialTextSection)
735 Out.InitSections(false);
741 AsmCond StartingCondState = TheCondState;
742 SmallVector<AsmRewrite, 4> AsmStrRewrites;
744 // If we are generating dwarf for assembly source files save the initial text
745 // section and generate a .file directive.
746 if (getContext().getGenDwarfForAssembly()) {
747 MCSection *Sec = getStreamer().getCurrentSectionOnly();
748 if (!Sec->getBeginSymbol()) {
749 MCSymbol *SectionStartSym = getContext().createTempSymbol();
750 getStreamer().EmitLabel(SectionStartSym);
751 Sec->setBeginSymbol(SectionStartSym);
753 bool InsertResult = getContext().addGenDwarfSection(Sec);
754 assert(InsertResult && ".text section should not have debug info yet");
756 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
757 0, StringRef(), getContext().getMainFileName()));
760 // While we have input, parse each statement.
761 while (Lexer.isNot(AsmToken::Eof)) {
762 ParseStatementInfo Info(&AsmStrRewrites);
763 if (!parseStatement(Info, nullptr))
766 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
767 // for printing ErrMsg via Lex() only if no (presumably better) parser error
769 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
773 // parseStatement returned true so may need to emit an error.
774 printPendingErrors();
776 // Skipping to the next line if needed.
777 if (!getLexer().isAtStartOfStatement())
778 eatToEndOfStatement();
781 // All errors should have been emitted.
782 assert(!hasPendingError() && "unexpected error from parseStatement");
784 getTargetParser().flushPendingInstructions(getStreamer());
786 if (TheCondState.TheCond != StartingCondState.TheCond ||
787 TheCondState.Ignore != StartingCondState.Ignore)
788 printError(getTok().getLoc(), "unmatched .ifs or .elses");
789 // Check to see there are no empty DwarfFile slots.
790 const auto &LineTables = getContext().getMCDwarfLineTables();
791 if (!LineTables.empty()) {
793 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
794 if (File.Name.empty() && Index != 0)
795 printError(getTok().getLoc(), "unassigned file number: " +
797 " for .file directives");
802 // Check to see that all assembler local symbols were actually defined.
803 // Targets that don't do subsections via symbols may not want this, though,
804 // so conservatively exclude them. Only do this if we're finalizing, though,
805 // as otherwise we won't necessarilly have seen everything yet.
807 if (MAI.hasSubsectionsViaSymbols()) {
808 for (const auto &TableEntry : getContext().getSymbols()) {
809 MCSymbol *Sym = TableEntry.getValue();
810 // Variable symbols may not be marked as defined, so check those
811 // explicitly. If we know it's a variable, we have a definition for
812 // the purposes of this check.
813 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
814 // FIXME: We would really like to refer back to where the symbol was
815 // first referenced for a source location. We need to add something
816 // to track that. Currently, we just point to the end of the file.
817 printError(getTok().getLoc(), "assembler local symbol '" +
818 Sym->getName() + "' not defined");
822 // Temporary symbols like the ones for directional jumps don't go in the
823 // symbol table. They also need to be diagnosed in all (final) cases.
824 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
825 if (std::get<2>(LocSym)->isUndefined()) {
826 // Reset the state of any "# line file" directives we've seen to the
827 // context as it was at the diagnostic site.
828 CppHashInfo = std::get<1>(LocSym);
829 printError(std::get<0>(LocSym), "directional label undefined");
834 // Finalize the output stream if there are no errors and if the client wants
836 if (!HadError && !NoFinalize)
839 return HadError || getContext().hadError();
842 bool AsmParser::checkForValidSection() {
843 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
844 Out.InitSections(false);
845 return Error(getTok().getLoc(),
846 "expected section directive before assembly directive");
851 /// \brief Throw away the rest of the line for testing purposes.
852 void AsmParser::eatToEndOfStatement() {
853 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
857 if (Lexer.is(AsmToken::EndOfStatement))
861 StringRef AsmParser::parseStringToEndOfStatement() {
862 const char *Start = getTok().getLoc().getPointer();
864 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
867 const char *End = getTok().getLoc().getPointer();
868 return StringRef(Start, End - Start);
871 StringRef AsmParser::parseStringToComma() {
872 const char *Start = getTok().getLoc().getPointer();
874 while (Lexer.isNot(AsmToken::EndOfStatement) &&
875 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
878 const char *End = getTok().getLoc().getPointer();
879 return StringRef(Start, End - Start);
882 /// \brief Parse a paren expression and return it.
883 /// NOTE: This assumes the leading '(' has already been consumed.
885 /// parenexpr ::= expr)
887 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
888 if (parseExpression(Res))
890 if (Lexer.isNot(AsmToken::RParen))
891 return TokError("expected ')' in parentheses expression");
892 EndLoc = Lexer.getTok().getEndLoc();
897 /// \brief Parse a bracket expression and return it.
898 /// NOTE: This assumes the leading '[' has already been consumed.
900 /// bracketexpr ::= expr]
902 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
903 if (parseExpression(Res))
905 EndLoc = getTok().getEndLoc();
906 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
911 /// \brief Parse a primary expression and return it.
912 /// primaryexpr ::= (parenexpr
913 /// primaryexpr ::= symbol
914 /// primaryexpr ::= number
915 /// primaryexpr ::= '.'
916 /// primaryexpr ::= ~,+,- primaryexpr
917 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
918 SMLoc FirstTokenLoc = getLexer().getLoc();
919 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
920 switch (FirstTokenKind) {
922 return TokError("unknown token in expression");
923 // If we have an error assume that we've already handled it.
924 case AsmToken::Error:
926 case AsmToken::Exclaim:
927 Lex(); // Eat the operator.
928 if (parsePrimaryExpr(Res, EndLoc))
930 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
932 case AsmToken::Dollar:
934 case AsmToken::String:
935 case AsmToken::Identifier: {
936 StringRef Identifier;
937 if (parseIdentifier(Identifier)) {
938 // We may have failed but $ may be a valid token.
939 if (getTok().is(AsmToken::Dollar)) {
940 if (Lexer.getMAI().getDollarIsPC()) {
942 // This is a '$' reference, which references the current PC. Emit a
943 // temporary label to the streamer and refer to it.
944 MCSymbol *Sym = Ctx.createTempSymbol();
946 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
948 EndLoc = FirstTokenLoc;
951 return Error(FirstTokenLoc, "invalid token in expression");
954 // Parse symbol variant
955 std::pair<StringRef, StringRef> Split;
956 if (!MAI.useParensForSymbolVariant()) {
957 if (FirstTokenKind == AsmToken::String) {
958 if (Lexer.is(AsmToken::At)) {
960 SMLoc AtLoc = getLexer().getLoc();
962 if (parseIdentifier(VName))
963 return Error(AtLoc, "expected symbol variant after '@'");
965 Split = std::make_pair(Identifier, VName);
968 Split = Identifier.split('@');
970 } else if (Lexer.is(AsmToken::LParen)) {
973 parseIdentifier(VName);
975 if (parseToken(AsmToken::RParen,
976 "unexpected token in variant, expected ')'"))
978 Split = std::make_pair(Identifier, VName);
981 EndLoc = SMLoc::getFromPointer(Identifier.end());
983 // This is a symbol reference.
984 StringRef SymbolName = Identifier;
985 if (SymbolName.empty())
988 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
990 // Lookup the symbol variant if used.
991 if (!Split.second.empty()) {
992 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
993 if (Variant != MCSymbolRefExpr::VK_Invalid) {
994 SymbolName = Split.first;
995 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
996 Variant = MCSymbolRefExpr::VK_None;
998 return Error(SMLoc::getFromPointer(Split.second.begin()),
999 "invalid variant '" + Split.second + "'");
1003 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
1005 // If this is an absolute variable reference, substitute it now to preserve
1006 // semantics in the face of reassignment.
1007 if (Sym->isVariable() &&
1008 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
1010 return Error(EndLoc, "unexpected modifier on variable reference");
1012 Res = Sym->getVariableValue(/*SetUsed*/ false);
1016 // Otherwise create a symbol ref.
1017 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1020 case AsmToken::BigNum:
1021 return TokError("literal value out of range for directive");
1022 case AsmToken::Integer: {
1023 SMLoc Loc = getTok().getLoc();
1024 int64_t IntVal = getTok().getIntVal();
1025 Res = MCConstantExpr::create(IntVal, getContext());
1026 EndLoc = Lexer.getTok().getEndLoc();
1027 Lex(); // Eat token.
1028 // Look for 'b' or 'f' following an Integer as a directional label
1029 if (Lexer.getKind() == AsmToken::Identifier) {
1030 StringRef IDVal = getTok().getString();
1031 // Lookup the symbol variant if used.
1032 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1033 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1034 if (Split.first.size() != IDVal.size()) {
1035 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1036 if (Variant == MCSymbolRefExpr::VK_Invalid)
1037 return TokError("invalid variant '" + Split.second + "'");
1038 IDVal = Split.first;
1040 if (IDVal == "f" || IDVal == "b") {
1042 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1043 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1044 if (IDVal == "b" && Sym->isUndefined())
1045 return Error(Loc, "directional label undefined");
1046 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1047 EndLoc = Lexer.getTok().getEndLoc();
1048 Lex(); // Eat identifier.
1053 case AsmToken::Real: {
1054 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1055 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1056 Res = MCConstantExpr::create(IntVal, getContext());
1057 EndLoc = Lexer.getTok().getEndLoc();
1058 Lex(); // Eat token.
1061 case AsmToken::Dot: {
1062 // This is a '.' reference, which references the current PC. Emit a
1063 // temporary label to the streamer and refer to it.
1064 MCSymbol *Sym = Ctx.createTempSymbol();
1066 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1067 EndLoc = Lexer.getTok().getEndLoc();
1068 Lex(); // Eat identifier.
1071 case AsmToken::LParen:
1072 Lex(); // Eat the '('.
1073 return parseParenExpr(Res, EndLoc);
1074 case AsmToken::LBrac:
1075 if (!PlatformParser->HasBracketExpressions())
1076 return TokError("brackets expression not supported on this target");
1077 Lex(); // Eat the '['.
1078 return parseBracketExpr(Res, EndLoc);
1079 case AsmToken::Minus:
1080 Lex(); // Eat the operator.
1081 if (parsePrimaryExpr(Res, EndLoc))
1083 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1085 case AsmToken::Plus:
1086 Lex(); // Eat the operator.
1087 if (parsePrimaryExpr(Res, EndLoc))
1089 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1091 case AsmToken::Tilde:
1092 Lex(); // Eat the operator.
1093 if (parsePrimaryExpr(Res, EndLoc))
1095 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1097 // MIPS unary expression operators. The lexer won't generate these tokens if
1098 // MCAsmInfo::HasMipsExpressions is false for the target.
1099 case AsmToken::PercentCall16:
1100 case AsmToken::PercentCall_Hi:
1101 case AsmToken::PercentCall_Lo:
1102 case AsmToken::PercentDtprel_Hi:
1103 case AsmToken::PercentDtprel_Lo:
1104 case AsmToken::PercentGot:
1105 case AsmToken::PercentGot_Disp:
1106 case AsmToken::PercentGot_Hi:
1107 case AsmToken::PercentGot_Lo:
1108 case AsmToken::PercentGot_Ofst:
1109 case AsmToken::PercentGot_Page:
1110 case AsmToken::PercentGottprel:
1111 case AsmToken::PercentGp_Rel:
1112 case AsmToken::PercentHi:
1113 case AsmToken::PercentHigher:
1114 case AsmToken::PercentHighest:
1115 case AsmToken::PercentLo:
1116 case AsmToken::PercentNeg:
1117 case AsmToken::PercentPcrel_Hi:
1118 case AsmToken::PercentPcrel_Lo:
1119 case AsmToken::PercentTlsgd:
1120 case AsmToken::PercentTlsldm:
1121 case AsmToken::PercentTprel_Hi:
1122 case AsmToken::PercentTprel_Lo:
1123 Lex(); // Eat the operator.
1124 if (Lexer.isNot(AsmToken::LParen))
1125 return TokError("expected '(' after operator");
1126 Lex(); // Eat the operator.
1127 if (parseExpression(Res, EndLoc))
1129 if (Lexer.isNot(AsmToken::RParen))
1130 return TokError("expected ')'");
1131 Lex(); // Eat the operator.
1132 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1137 bool AsmParser::parseExpression(const MCExpr *&Res) {
1139 return parseExpression(Res, EndLoc);
1143 AsmParser::applyModifierToExpr(const MCExpr *E,
1144 MCSymbolRefExpr::VariantKind Variant) {
1145 // Ask the target implementation about this expression first.
1146 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1149 // Recurse over the given expression, rebuilding it to apply the given variant
1150 // if there is exactly one symbol.
1151 switch (E->getKind()) {
1152 case MCExpr::Target:
1153 case MCExpr::Constant:
1156 case MCExpr::SymbolRef: {
1157 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1159 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1160 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1161 "' (already modified)");
1165 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1168 case MCExpr::Unary: {
1169 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1170 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1173 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1176 case MCExpr::Binary: {
1177 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1178 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1179 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1189 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1193 llvm_unreachable("Invalid expression kind!");
1196 /// This function checks if the next token is <string> type or arithmetic.
1197 /// string that begin with character '<' must end with character '>'.
1198 /// otherwise it is arithmetics.
1199 /// If the function returns a 'true' value,
1200 /// the End argument will be filled with the last location pointed to the '>'
1203 /// There is a gap between the AltMacro's documentation and the single quote implementation.
1204 /// GCC does not fully support this feature and so we will not support it.
1205 /// TODO: Adding single quote as a string.
1206 bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1207 assert((StrLoc.getPointer() != NULL) &&
1208 "Argument to the function cannot be a NULL value");
1209 const char *CharPtr = StrLoc.getPointer();
1210 while ((*CharPtr != '>') && (*CharPtr != '\n') &&
1211 (*CharPtr != '\r') && (*CharPtr != '\0')){
1214 if (*CharPtr == '>') {
1215 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1221 /// \brief Parse an expression and return it.
1223 /// expr ::= expr &&,|| expr -> lowest.
1224 /// expr ::= expr |,^,&,! expr
1225 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1226 /// expr ::= expr <<,>> expr
1227 /// expr ::= expr +,- expr
1228 /// expr ::= expr *,/,% expr -> highest.
1229 /// expr ::= primaryexpr
1231 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1232 // Parse the expression.
1234 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1237 // As a special case, we support 'a op b @ modifier' by rewriting the
1238 // expression to include the modifier. This is inefficient, but in general we
1239 // expect users to use 'a@modifier op b'.
1240 if (Lexer.getKind() == AsmToken::At) {
1243 if (Lexer.isNot(AsmToken::Identifier))
1244 return TokError("unexpected symbol modifier following '@'");
1246 MCSymbolRefExpr::VariantKind Variant =
1247 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1248 if (Variant == MCSymbolRefExpr::VK_Invalid)
1249 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1251 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1253 return TokError("invalid modifier '" + getTok().getIdentifier() +
1254 "' (no symbols present)");
1261 // Try to constant fold it up front, if possible.
1263 if (Res->evaluateAsAbsolute(Value))
1264 Res = MCConstantExpr::create(Value, getContext());
1269 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1271 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1274 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1276 if (parseParenExpr(Res, EndLoc))
1279 for (; ParenDepth > 0; --ParenDepth) {
1280 if (parseBinOpRHS(1, Res, EndLoc))
1283 // We don't Lex() the last RParen.
1284 // This is the same behavior as parseParenExpression().
1285 if (ParenDepth - 1 > 0) {
1286 EndLoc = getTok().getEndLoc();
1287 if (parseToken(AsmToken::RParen,
1288 "expected ')' in parentheses expression"))
1295 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1298 SMLoc StartLoc = Lexer.getLoc();
1299 if (parseExpression(Expr))
1302 if (!Expr->evaluateAsAbsolute(Res))
1303 return Error(StartLoc, "expected absolute expression");
1308 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1309 MCBinaryExpr::Opcode &Kind,
1310 bool ShouldUseLogicalShr) {
1313 return 0; // not a binop.
1315 // Lowest Precedence: &&, ||
1316 case AsmToken::AmpAmp:
1317 Kind = MCBinaryExpr::LAnd;
1319 case AsmToken::PipePipe:
1320 Kind = MCBinaryExpr::LOr;
1323 // Low Precedence: |, &, ^
1325 // FIXME: gas seems to support '!' as an infix operator?
1326 case AsmToken::Pipe:
1327 Kind = MCBinaryExpr::Or;
1329 case AsmToken::Caret:
1330 Kind = MCBinaryExpr::Xor;
1333 Kind = MCBinaryExpr::And;
1336 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1337 case AsmToken::EqualEqual:
1338 Kind = MCBinaryExpr::EQ;
1340 case AsmToken::ExclaimEqual:
1341 case AsmToken::LessGreater:
1342 Kind = MCBinaryExpr::NE;
1344 case AsmToken::Less:
1345 Kind = MCBinaryExpr::LT;
1347 case AsmToken::LessEqual:
1348 Kind = MCBinaryExpr::LTE;
1350 case AsmToken::Greater:
1351 Kind = MCBinaryExpr::GT;
1353 case AsmToken::GreaterEqual:
1354 Kind = MCBinaryExpr::GTE;
1357 // Intermediate Precedence: <<, >>
1358 case AsmToken::LessLess:
1359 Kind = MCBinaryExpr::Shl;
1361 case AsmToken::GreaterGreater:
1362 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1365 // High Intermediate Precedence: +, -
1366 case AsmToken::Plus:
1367 Kind = MCBinaryExpr::Add;
1369 case AsmToken::Minus:
1370 Kind = MCBinaryExpr::Sub;
1373 // Highest Precedence: *, /, %
1374 case AsmToken::Star:
1375 Kind = MCBinaryExpr::Mul;
1377 case AsmToken::Slash:
1378 Kind = MCBinaryExpr::Div;
1380 case AsmToken::Percent:
1381 Kind = MCBinaryExpr::Mod;
1386 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1387 MCBinaryExpr::Opcode &Kind,
1388 bool ShouldUseLogicalShr) {
1391 return 0; // not a binop.
1393 // Lowest Precedence: &&, ||
1394 case AsmToken::AmpAmp:
1395 Kind = MCBinaryExpr::LAnd;
1397 case AsmToken::PipePipe:
1398 Kind = MCBinaryExpr::LOr;
1401 // Low Precedence: ==, !=, <>, <, <=, >, >=
1402 case AsmToken::EqualEqual:
1403 Kind = MCBinaryExpr::EQ;
1405 case AsmToken::ExclaimEqual:
1406 case AsmToken::LessGreater:
1407 Kind = MCBinaryExpr::NE;
1409 case AsmToken::Less:
1410 Kind = MCBinaryExpr::LT;
1412 case AsmToken::LessEqual:
1413 Kind = MCBinaryExpr::LTE;
1415 case AsmToken::Greater:
1416 Kind = MCBinaryExpr::GT;
1418 case AsmToken::GreaterEqual:
1419 Kind = MCBinaryExpr::GTE;
1422 // Low Intermediate Precedence: +, -
1423 case AsmToken::Plus:
1424 Kind = MCBinaryExpr::Add;
1426 case AsmToken::Minus:
1427 Kind = MCBinaryExpr::Sub;
1430 // High Intermediate Precedence: |, &, ^
1432 // FIXME: gas seems to support '!' as an infix operator?
1433 case AsmToken::Pipe:
1434 Kind = MCBinaryExpr::Or;
1436 case AsmToken::Caret:
1437 Kind = MCBinaryExpr::Xor;
1440 Kind = MCBinaryExpr::And;
1443 // Highest Precedence: *, /, %, <<, >>
1444 case AsmToken::Star:
1445 Kind = MCBinaryExpr::Mul;
1447 case AsmToken::Slash:
1448 Kind = MCBinaryExpr::Div;
1450 case AsmToken::Percent:
1451 Kind = MCBinaryExpr::Mod;
1453 case AsmToken::LessLess:
1454 Kind = MCBinaryExpr::Shl;
1456 case AsmToken::GreaterGreater:
1457 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1462 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1463 MCBinaryExpr::Opcode &Kind) {
1464 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1465 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1466 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1469 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1470 /// Res contains the LHS of the expression on input.
1471 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1473 SMLoc StartLoc = Lexer.getLoc();
1475 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1476 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1478 // If the next token is lower precedence than we are allowed to eat, return
1479 // successfully with what we ate already.
1480 if (TokPrec < Precedence)
1485 // Eat the next primary expression.
1487 if (parsePrimaryExpr(RHS, EndLoc))
1490 // If BinOp binds less tightly with RHS than the operator after RHS, let
1491 // the pending operator take RHS as its LHS.
1492 MCBinaryExpr::Opcode Dummy;
1493 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1494 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1497 // Merge LHS and RHS according to operator.
1498 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1503 /// ::= EndOfStatement
1504 /// ::= Label* Directive ...Operands... EndOfStatement
1505 /// ::= Label* Identifier OperandList* EndOfStatement
1506 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1507 MCAsmParserSemaCallback *SI) {
1508 assert(!hasPendingError() && "parseStatement started with pending error");
1509 // Eat initial spaces and comments
1510 while (Lexer.is(AsmToken::Space))
1512 if (Lexer.is(AsmToken::EndOfStatement)) {
1513 // if this is a line comment we can drop it safely
1514 if (getTok().getString().front() == '\r' ||
1515 getTok().getString().front() == '\n')
1520 if (Lexer.is(AsmToken::Hash)) {
1521 // Seeing a hash here means that it was an end-of-line comment in
1522 // an asm syntax where hash's are not comment and the previous
1523 // statement parser did not check the end of statement. Relex as
1525 StringRef CommentStr = parseStringToEndOfStatement();
1527 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1530 // Statements always start with an identifier.
1531 AsmToken ID = getTok();
1532 SMLoc IDLoc = ID.getLoc();
1534 int64_t LocalLabelVal = -1;
1535 if (Lexer.is(AsmToken::HashDirective))
1536 return parseCppHashLineFilenameComment(IDLoc);
1537 // Allow an integer followed by a ':' as a directional local label.
1538 if (Lexer.is(AsmToken::Integer)) {
1539 LocalLabelVal = getTok().getIntVal();
1540 if (LocalLabelVal < 0) {
1541 if (!TheCondState.Ignore) {
1542 Lex(); // always eat a token
1543 return Error(IDLoc, "unexpected token at start of statement");
1547 IDVal = getTok().getString();
1548 Lex(); // Consume the integer token to be used as an identifier token.
1549 if (Lexer.getKind() != AsmToken::Colon) {
1550 if (!TheCondState.Ignore) {
1551 Lex(); // always eat a token
1552 return Error(IDLoc, "unexpected token at start of statement");
1556 } else if (Lexer.is(AsmToken::Dot)) {
1557 // Treat '.' as a valid identifier in this context.
1560 } else if (Lexer.is(AsmToken::LCurly)) {
1561 // Treat '{' as a valid identifier in this context.
1565 } else if (Lexer.is(AsmToken::RCurly)) {
1566 // Treat '}' as a valid identifier in this context.
1569 } else if (parseIdentifier(IDVal)) {
1570 if (!TheCondState.Ignore) {
1571 Lex(); // always eat a token
1572 return Error(IDLoc, "unexpected token at start of statement");
1577 // Handle conditional assembly here before checking for skipping. We
1578 // have to do this so that .endif isn't skipped in a ".if 0" block for
1580 StringMap<DirectiveKind>::const_iterator DirKindIt =
1581 DirectiveKindMap.find(IDVal);
1582 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1584 : DirKindIt->getValue();
1595 return parseDirectiveIf(IDLoc, DirKind);
1597 return parseDirectiveIfb(IDLoc, true);
1599 return parseDirectiveIfb(IDLoc, false);
1601 return parseDirectiveIfc(IDLoc, true);
1603 return parseDirectiveIfeqs(IDLoc, true);
1605 return parseDirectiveIfc(IDLoc, false);
1607 return parseDirectiveIfeqs(IDLoc, false);
1609 return parseDirectiveIfdef(IDLoc, true);
1612 return parseDirectiveIfdef(IDLoc, false);
1614 return parseDirectiveElseIf(IDLoc);
1616 return parseDirectiveElse(IDLoc);
1618 return parseDirectiveEndIf(IDLoc);
1621 // Ignore the statement if in the middle of inactive conditional
1623 if (TheCondState.Ignore) {
1624 eatToEndOfStatement();
1628 // FIXME: Recurse on local labels?
1630 // See what kind of statement we have.
1631 switch (Lexer.getKind()) {
1632 case AsmToken::Colon: {
1633 if (!getTargetParser().isLabel(ID))
1635 if (checkForValidSection())
1638 // identifier ':' -> Label.
1641 // Diagnose attempt to use '.' as a label.
1643 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1645 // Diagnose attempt to use a variable as a label.
1647 // FIXME: Diagnostics. Note the location of the definition as a label.
1648 // FIXME: This doesn't diagnose assignment to a symbol which has been
1649 // implicitly marked as external.
1651 if (LocalLabelVal == -1) {
1652 if (ParsingInlineAsm && SI) {
1653 StringRef RewrittenLabel =
1654 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1655 assert(!RewrittenLabel.empty() &&
1656 "We should have an internal name here.");
1657 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1659 IDVal = RewrittenLabel;
1661 Sym = getContext().getOrCreateSymbol(IDVal);
1663 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1664 // End of Labels should be treated as end of line for lexing
1665 // purposes but that information is not available to the Lexer who
1666 // does not understand Labels. This may cause us to see a Hash
1667 // here instead of a preprocessor line comment.
1668 if (getTok().is(AsmToken::Hash)) {
1669 StringRef CommentStr = parseStringToEndOfStatement();
1671 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1674 // Consume any end of statement token, if present, to avoid spurious
1675 // AddBlankLine calls().
1676 if (getTok().is(AsmToken::EndOfStatement)) {
1681 if (!getTargetParser().isParsingInlineAsm())
1682 Out.EmitLabel(Sym, IDLoc);
1684 // If we are generating dwarf for assembly source files then gather the
1685 // info to make a dwarf label entry for this label if needed.
1686 if (getContext().getGenDwarfForAssembly())
1687 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1690 getTargetParser().onLabelParsed(Sym);
1695 case AsmToken::Equal:
1696 if (!getTargetParser().equalIsAsmAssignment())
1698 // identifier '=' ... -> assignment statement
1701 return parseAssignment(IDVal, true);
1703 default: // Normal instruction or directive.
1707 // If macros are enabled, check to see if this is a macro instantiation.
1708 if (areMacrosEnabled())
1709 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1710 return handleMacroEntry(M, IDLoc);
1713 // Otherwise, we have a normal instruction or directive.
1715 // Directives start with "."
1716 if (IDVal[0] == '.' && IDVal != ".") {
1717 // There are several entities interested in parsing directives:
1719 // 1. The target-specific assembly parser. Some directives are target
1720 // specific or may potentially behave differently on certain targets.
1721 // 2. Asm parser extensions. For example, platform-specific parsers
1722 // (like the ELF parser) register themselves as extensions.
1723 // 3. The generic directive parser implemented by this class. These are
1724 // all the directives that behave in a target and platform independent
1725 // manner, or at least have a default behavior that's shared between
1726 // all targets and platforms.
1728 getTargetParser().flushPendingInstructions(getStreamer());
1730 SMLoc StartTokLoc = getTok().getLoc();
1731 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1733 if (hasPendingError())
1735 // Currently the return value should be true if we are
1736 // uninterested but as this is at odds with the standard parsing
1737 // convention (return true = error) we have instances of a parsed
1738 // directive that fails returning true as an error. Catch these
1739 // cases as best as possible errors here.
1740 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1742 // Return if we did some parsing or believe we succeeded.
1743 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1746 // Next, check the extension directive map to see if any extension has
1747 // registered itself to parse this directive.
1748 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1749 ExtensionDirectiveMap.lookup(IDVal);
1751 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1753 // Finally, if no one else is interested in this directive, it must be
1754 // generic and familiar to this class.
1760 return parseDirectiveSet(IDVal, true);
1762 return parseDirectiveSet(IDVal, false);
1764 return parseDirectiveAscii(IDVal, false);
1767 return parseDirectiveAscii(IDVal, true);
1770 return parseDirectiveValue(IDVal, 1);
1776 return parseDirectiveValue(IDVal, 2);
1781 return parseDirectiveValue(IDVal, 4);
1784 return parseDirectiveValue(IDVal, 8);
1786 return parseDirectiveValue(
1787 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1789 return parseDirectiveOctaValue(IDVal);
1793 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1796 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1798 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1799 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1802 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1803 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1806 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1808 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1810 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1812 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1814 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1816 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1818 return parseDirectiveOrg();
1820 return parseDirectiveFill();
1822 return parseDirectiveZero();
1824 eatToEndOfStatement(); // .extern is the default, ignore it.
1828 return parseDirectiveSymbolAttribute(MCSA_Global);
1829 case DK_LAZY_REFERENCE:
1830 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1831 case DK_NO_DEAD_STRIP:
1832 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1833 case DK_SYMBOL_RESOLVER:
1834 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1835 case DK_PRIVATE_EXTERN:
1836 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1838 return parseDirectiveSymbolAttribute(MCSA_Reference);
1839 case DK_WEAK_DEFINITION:
1840 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1841 case DK_WEAK_REFERENCE:
1842 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1843 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1844 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1847 return parseDirectiveComm(/*IsLocal=*/false);
1849 return parseDirectiveComm(/*IsLocal=*/true);
1851 return parseDirectiveAbort();
1853 return parseDirectiveInclude();
1855 return parseDirectiveIncbin();
1858 return TokError(Twine(IDVal) +
1859 " not currently supported for this target");
1861 return parseDirectiveRept(IDLoc, IDVal);
1863 return parseDirectiveIrp(IDLoc);
1865 return parseDirectiveIrpc(IDLoc);
1867 return parseDirectiveEndr(IDLoc);
1868 case DK_BUNDLE_ALIGN_MODE:
1869 return parseDirectiveBundleAlignMode();
1870 case DK_BUNDLE_LOCK:
1871 return parseDirectiveBundleLock();
1872 case DK_BUNDLE_UNLOCK:
1873 return parseDirectiveBundleUnlock();
1875 return parseDirectiveLEB128(true);
1877 return parseDirectiveLEB128(false);
1880 return parseDirectiveSpace(IDVal);
1882 return parseDirectiveFile(IDLoc);
1884 return parseDirectiveLine();
1886 return parseDirectiveLoc();
1888 return parseDirectiveStabs();
1890 return parseDirectiveCVFile();
1892 return parseDirectiveCVFuncId();
1893 case DK_CV_INLINE_SITE_ID:
1894 return parseDirectiveCVInlineSiteId();
1896 return parseDirectiveCVLoc();
1897 case DK_CV_LINETABLE:
1898 return parseDirectiveCVLinetable();
1899 case DK_CV_INLINE_LINETABLE:
1900 return parseDirectiveCVInlineLinetable();
1901 case DK_CV_DEF_RANGE:
1902 return parseDirectiveCVDefRange();
1903 case DK_CV_STRINGTABLE:
1904 return parseDirectiveCVStringTable();
1905 case DK_CV_FILECHECKSUMS:
1906 return parseDirectiveCVFileChecksums();
1907 case DK_CFI_SECTIONS:
1908 return parseDirectiveCFISections();
1909 case DK_CFI_STARTPROC:
1910 return parseDirectiveCFIStartProc();
1911 case DK_CFI_ENDPROC:
1912 return parseDirectiveCFIEndProc();
1913 case DK_CFI_DEF_CFA:
1914 return parseDirectiveCFIDefCfa(IDLoc);
1915 case DK_CFI_DEF_CFA_OFFSET:
1916 return parseDirectiveCFIDefCfaOffset();
1917 case DK_CFI_ADJUST_CFA_OFFSET:
1918 return parseDirectiveCFIAdjustCfaOffset();
1919 case DK_CFI_DEF_CFA_REGISTER:
1920 return parseDirectiveCFIDefCfaRegister(IDLoc);
1922 return parseDirectiveCFIOffset(IDLoc);
1923 case DK_CFI_REL_OFFSET:
1924 return parseDirectiveCFIRelOffset(IDLoc);
1925 case DK_CFI_PERSONALITY:
1926 return parseDirectiveCFIPersonalityOrLsda(true);
1928 return parseDirectiveCFIPersonalityOrLsda(false);
1929 case DK_CFI_REMEMBER_STATE:
1930 return parseDirectiveCFIRememberState();
1931 case DK_CFI_RESTORE_STATE:
1932 return parseDirectiveCFIRestoreState();
1933 case DK_CFI_SAME_VALUE:
1934 return parseDirectiveCFISameValue(IDLoc);
1935 case DK_CFI_RESTORE:
1936 return parseDirectiveCFIRestore(IDLoc);
1938 return parseDirectiveCFIEscape();
1939 case DK_CFI_SIGNAL_FRAME:
1940 return parseDirectiveCFISignalFrame();
1941 case DK_CFI_UNDEFINED:
1942 return parseDirectiveCFIUndefined(IDLoc);
1943 case DK_CFI_REGISTER:
1944 return parseDirectiveCFIRegister(IDLoc);
1945 case DK_CFI_WINDOW_SAVE:
1946 return parseDirectiveCFIWindowSave();
1949 return parseDirectiveMacrosOnOff(IDVal);
1951 return parseDirectiveMacro(IDLoc);
1954 return parseDirectiveAltmacro(IDVal);
1956 return parseDirectiveExitMacro(IDVal);
1959 return parseDirectiveEndMacro(IDVal);
1961 return parseDirectivePurgeMacro(IDLoc);
1963 return parseDirectiveEnd(IDLoc);
1965 return parseDirectiveError(IDLoc, false);
1967 return parseDirectiveError(IDLoc, true);
1969 return parseDirectiveWarning(IDLoc);
1971 return parseDirectiveReloc(IDLoc);
1974 return parseDirectiveDCB(IDVal, 2);
1976 return parseDirectiveDCB(IDVal, 1);
1978 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
1980 return parseDirectiveDCB(IDVal, 4);
1982 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
1985 return TokError(Twine(IDVal) +
1986 " not currently supported for this target");
1989 return parseDirectiveDS(IDVal, 2);
1991 return parseDirectiveDS(IDVal, 1);
1993 return parseDirectiveDS(IDVal, 8);
1996 return parseDirectiveDS(IDVal, 4);
1999 return parseDirectiveDS(IDVal, 12);
2002 return Error(IDLoc, "unknown directive");
2005 // __asm _emit or __asm __emit
2006 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2007 IDVal == "_EMIT" || IDVal == "__EMIT"))
2008 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2011 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2012 return parseDirectiveMSAlign(IDLoc, Info);
2014 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2015 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2016 if (checkForValidSection())
2019 // Canonicalize the opcode to lower case.
2020 std::string OpcodeStr = IDVal.lower();
2021 ParseInstructionInfo IInfo(Info.AsmRewrites);
2022 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2023 Info.ParsedOperands);
2024 Info.ParseError = ParseHadError;
2026 // Dump the parsed representation, if requested.
2027 if (getShowParsedOperands()) {
2028 SmallString<256> Str;
2029 raw_svector_ostream OS(Str);
2030 OS << "parsed instruction: [";
2031 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2034 Info.ParsedOperands[i]->print(OS);
2038 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2041 // Fail even if ParseInstruction erroneously returns false.
2042 if (hasPendingError() || ParseHadError)
2045 // If we are generating dwarf for the current section then generate a .loc
2046 // directive for the instruction.
2047 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
2048 getContext().getGenDwarfSectionSyms().count(
2049 getStreamer().getCurrentSectionOnly())) {
2051 if (ActiveMacros.empty())
2052 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2054 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2055 ActiveMacros.front()->ExitBuffer);
2057 // If we previously parsed a cpp hash file line comment then make sure the
2058 // current Dwarf File is for the CppHashFilename if not then emit the
2059 // Dwarf File table for it and adjust the line number for the .loc.
2060 if (!CppHashInfo.Filename.empty()) {
2061 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2062 0, StringRef(), CppHashInfo.Filename);
2063 getContext().setGenDwarfFileNumber(FileNumber);
2065 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2066 // cache with the different Loc from the call above we save the last
2067 // info we queried here with SrcMgr.FindLineNumber().
2068 unsigned CppHashLocLineNo;
2069 if (LastQueryIDLoc == CppHashInfo.Loc &&
2070 LastQueryBuffer == CppHashInfo.Buf)
2071 CppHashLocLineNo = LastQueryLine;
2074 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2075 LastQueryLine = CppHashLocLineNo;
2076 LastQueryIDLoc = CppHashInfo.Loc;
2077 LastQueryBuffer = CppHashInfo.Buf;
2079 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2082 getStreamer().EmitDwarfLocDirective(
2083 getContext().getGenDwarfFileNumber(), Line, 0,
2084 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2088 // If parsing succeeded, match the instruction.
2089 if (!ParseHadError) {
2091 if (getTargetParser().MatchAndEmitInstruction(
2092 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2093 getTargetParser().isParsingInlineAsm()))
2099 // Parse and erase curly braces marking block start/end
2101 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2102 // Identify curly brace marking block start/end
2103 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2106 SMLoc StartLoc = Lexer.getLoc();
2107 Lex(); // Eat the brace
2108 if (Lexer.is(AsmToken::EndOfStatement))
2109 Lex(); // Eat EndOfStatement following the brace
2111 // Erase the block start/end brace from the output asm string
2112 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2113 StartLoc.getPointer());
2117 /// parseCppHashLineFilenameComment as this:
2118 /// ::= # number "filename"
2119 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2120 Lex(); // Eat the hash token.
2121 // Lexer only ever emits HashDirective if it fully formed if it's
2122 // done the checking already so this is an internal error.
2123 assert(getTok().is(AsmToken::Integer) &&
2124 "Lexing Cpp line comment: Expected Integer");
2125 int64_t LineNumber = getTok().getIntVal();
2127 assert(getTok().is(AsmToken::String) &&
2128 "Lexing Cpp line comment: Expected String");
2129 StringRef Filename = getTok().getString();
2132 // Get rid of the enclosing quotes.
2133 Filename = Filename.substr(1, Filename.size() - 2);
2135 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2136 CppHashInfo.Loc = L;
2137 CppHashInfo.Filename = Filename;
2138 CppHashInfo.LineNumber = LineNumber;
2139 CppHashInfo.Buf = CurBuffer;
2143 /// \brief will use the last parsed cpp hash line filename comment
2144 /// for the Filename and LineNo if any in the diagnostic.
2145 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2146 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2147 raw_ostream &OS = errs();
2149 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2150 SMLoc DiagLoc = Diag.getLoc();
2151 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2152 unsigned CppHashBuf =
2153 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2155 // Like SourceMgr::printMessage() we need to print the include stack if any
2156 // before printing the message.
2157 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2158 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2159 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2160 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2161 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2164 // If we have not parsed a cpp hash line filename comment or the source
2165 // manager changed or buffer changed (like in a nested include) then just
2166 // print the normal diagnostic using its Filename and LineNo.
2167 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2168 DiagBuf != CppHashBuf) {
2169 if (Parser->SavedDiagHandler)
2170 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2172 Diag.print(nullptr, OS);
2176 // Use the CppHashFilename and calculate a line number based on the
2177 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2178 // for the diagnostic.
2179 const std::string &Filename = Parser->CppHashInfo.Filename;
2181 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2182 int CppHashLocLineNo =
2183 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2185 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2187 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2188 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2189 Diag.getLineContents(), Diag.getRanges());
2191 if (Parser->SavedDiagHandler)
2192 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2194 NewDiag.print(nullptr, OS);
2197 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2198 // difference being that that function accepts '@' as part of identifiers and
2199 // we can't do that. AsmLexer.cpp should probably be changed to handle
2200 // '@' as a special case when needed.
2201 static bool isIdentifierChar(char c) {
2202 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2206 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2207 ArrayRef<MCAsmMacroParameter> Parameters,
2208 ArrayRef<MCAsmMacroArgument> A,
2209 bool EnableAtPseudoVariable, SMLoc L) {
2210 unsigned NParameters = Parameters.size();
2211 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2212 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2213 return Error(L, "Wrong number of arguments");
2215 // A macro without parameters is handled differently on Darwin:
2216 // gas accepts no arguments and does no substitutions
2217 while (!Body.empty()) {
2218 // Scan for the next substitution.
2219 std::size_t End = Body.size(), Pos = 0;
2220 for (; Pos != End; ++Pos) {
2221 // Check for a substitution or escape.
2222 if (IsDarwin && !NParameters) {
2223 // This macro has no parameters, look for $0, $1, etc.
2224 if (Body[Pos] != '$' || Pos + 1 == End)
2227 char Next = Body[Pos + 1];
2228 if (Next == '$' || Next == 'n' ||
2229 isdigit(static_cast<unsigned char>(Next)))
2232 // This macro has parameters, look for \foo, \bar, etc.
2233 if (Body[Pos] == '\\' && Pos + 1 != End)
2239 OS << Body.slice(0, Pos);
2241 // Check if we reached the end.
2245 if (IsDarwin && !NParameters) {
2246 switch (Body[Pos + 1]) {
2252 // $n => number of arguments
2257 // $[0-9] => argument
2259 // Missing arguments are ignored.
2260 unsigned Index = Body[Pos + 1] - '0';
2261 if (Index >= A.size())
2264 // Otherwise substitute with the token values, with spaces eliminated.
2265 for (const AsmToken &Token : A[Index])
2266 OS << Token.getString();
2272 unsigned I = Pos + 1;
2274 // Check for the \@ pseudo-variable.
2275 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2278 while (isIdentifierChar(Body[I]) && I + 1 != End)
2281 const char *Begin = Body.data() + Pos + 1;
2282 StringRef Argument(Begin, I - (Pos + 1));
2285 if (Argument == "@") {
2286 OS << NumOfMacroInstantiations;
2289 for (; Index < NParameters; ++Index)
2290 if (Parameters[Index].Name == Argument)
2293 if (Index == NParameters) {
2294 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2297 OS << '\\' << Argument;
2301 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2302 for (const AsmToken &Token : A[Index])
2303 // For altmacro mode, you can write '%expr'.
2304 // The prefix '%' evaluates the expression 'expr'
2305 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2306 // Here, we identify the integer token which is the result of the
2307 // absolute expression evaluation and replace it with its string representation.
2308 if ((Lexer.IsaAltMacroMode()) &&
2309 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2310 // Emit an integer value to the buffer.
2311 OS << Token.getIntVal();
2312 // We expect no quotes around the string's contents when
2313 // parsing for varargs.
2314 else if (Token.isNot(AsmToken::String) || VarargParameter)
2315 OS << Token.getString();
2317 OS << Token.getStringContents();
2319 Pos += 1 + Argument.size();
2323 // Update the scan point.
2324 Body = Body.substr(Pos);
2330 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2331 size_t CondStackDepth)
2332 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2333 CondStackDepth(CondStackDepth) {}
2335 static bool isOperator(AsmToken::TokenKind kind) {
2339 case AsmToken::Plus:
2340 case AsmToken::Minus:
2341 case AsmToken::Tilde:
2342 case AsmToken::Slash:
2343 case AsmToken::Star:
2345 case AsmToken::Equal:
2346 case AsmToken::EqualEqual:
2347 case AsmToken::Pipe:
2348 case AsmToken::PipePipe:
2349 case AsmToken::Caret:
2351 case AsmToken::AmpAmp:
2352 case AsmToken::Exclaim:
2353 case AsmToken::ExclaimEqual:
2354 case AsmToken::Less:
2355 case AsmToken::LessEqual:
2356 case AsmToken::LessLess:
2357 case AsmToken::LessGreater:
2358 case AsmToken::Greater:
2359 case AsmToken::GreaterEqual:
2360 case AsmToken::GreaterGreater:
2367 class AsmLexerSkipSpaceRAII {
2369 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2370 Lexer.setSkipSpace(SkipSpace);
2373 ~AsmLexerSkipSpaceRAII() {
2374 Lexer.setSkipSpace(true);
2381 } // end anonymous namespace
2383 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2386 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2387 StringRef Str = parseStringToEndOfStatement();
2388 MA.emplace_back(AsmToken::String, Str);
2393 unsigned ParenLevel = 0;
2395 // Darwin doesn't use spaces to delmit arguments.
2396 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2402 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2403 return TokError("unexpected token in macro instantiation");
2405 if (ParenLevel == 0) {
2407 if (Lexer.is(AsmToken::Comma))
2410 if (Lexer.is(AsmToken::Space)) {
2412 Lexer.Lex(); // Eat spaces
2415 // Spaces can delimit parameters, but could also be part an expression.
2416 // If the token after a space is an operator, add the token and the next
2417 // one into this argument
2419 if (isOperator(Lexer.getKind())) {
2420 MA.push_back(getTok());
2423 // Whitespace after an operator can be ignored.
2424 if (Lexer.is(AsmToken::Space))
2434 // handleMacroEntry relies on not advancing the lexer here
2435 // to be able to fill in the remaining default parameter values
2436 if (Lexer.is(AsmToken::EndOfStatement))
2439 // Adjust the current parentheses level.
2440 if (Lexer.is(AsmToken::LParen))
2442 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2445 // Append the token to the current argument list.
2446 MA.push_back(getTok());
2450 if (ParenLevel != 0)
2451 return TokError("unbalanced parentheses in macro argument");
2455 // Parse the macro instantiation arguments.
2456 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2457 MCAsmMacroArguments &A) {
2458 const unsigned NParameters = M ? M->Parameters.size() : 0;
2459 bool NamedParametersFound = false;
2460 SmallVector<SMLoc, 4> FALocs;
2462 A.resize(NParameters);
2463 FALocs.resize(NParameters);
2465 // Parse two kinds of macro invocations:
2466 // - macros defined without any parameters accept an arbitrary number of them
2467 // - macros defined with parameters accept at most that many of them
2468 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2469 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2471 SMLoc IDLoc = Lexer.getLoc();
2472 MCAsmMacroParameter FA;
2474 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2475 if (parseIdentifier(FA.Name))
2476 return Error(IDLoc, "invalid argument identifier for formal argument");
2478 if (Lexer.isNot(AsmToken::Equal))
2479 return TokError("expected '=' after formal parameter identifier");
2483 NamedParametersFound = true;
2485 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2487 if (NamedParametersFound && FA.Name.empty())
2488 return Error(IDLoc, "cannot mix positional and keyword arguments");
2490 SMLoc StrLoc = Lexer.getLoc();
2492 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
2493 const MCExpr *AbsoluteExp;
2497 if (parseExpression(AbsoluteExp, EndLoc))
2499 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2500 return Error(StrLoc, "expected absolute expression");
2501 const char *StrChar = StrLoc.getPointer();
2502 const char *EndChar = EndLoc.getPointer();
2503 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2504 FA.Value.push_back(newToken);
2505 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2506 isAltmacroString(StrLoc, EndLoc)) {
2507 const char *StrChar = StrLoc.getPointer();
2508 const char *EndChar = EndLoc.getPointer();
2509 jumpToLoc(EndLoc, CurBuffer);
2510 /// Eat from '<' to '>'
2512 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2513 FA.Value.push_back(newToken);
2514 } else if(parseMacroArgument(FA.Value, Vararg))
2517 unsigned PI = Parameter;
2518 if (!FA.Name.empty()) {
2520 for (FAI = 0; FAI < NParameters; ++FAI)
2521 if (M->Parameters[FAI].Name == FA.Name)
2524 if (FAI >= NParameters) {
2525 assert(M && "expected macro to be defined");
2526 return Error(IDLoc, "parameter named '" + FA.Name +
2527 "' does not exist for macro '" + M->Name + "'");
2532 if (!FA.Value.empty()) {
2537 if (FALocs.size() <= PI)
2538 FALocs.resize(PI + 1);
2540 FALocs[PI] = Lexer.getLoc();
2543 // At the end of the statement, fill in remaining arguments that have
2544 // default values. If there aren't any, then the next argument is
2545 // required but missing
2546 if (Lexer.is(AsmToken::EndOfStatement)) {
2547 bool Failure = false;
2548 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2549 if (A[FAI].empty()) {
2550 if (M->Parameters[FAI].Required) {
2551 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2552 "missing value for required parameter "
2553 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2557 if (!M->Parameters[FAI].Value.empty())
2558 A[FAI] = M->Parameters[FAI].Value;
2564 if (Lexer.is(AsmToken::Comma))
2568 return TokError("too many positional arguments");
2571 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2572 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2573 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2576 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2577 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2580 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2582 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2583 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2584 // eliminate this, although we should protect against infinite loops.
2585 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2586 if (ActiveMacros.size() == MaxNestingDepth) {
2587 std::ostringstream MaxNestingDepthError;
2588 MaxNestingDepthError << "macros cannot be nested more than "
2589 << MaxNestingDepth << " levels deep."
2590 << " Use -asm-macro-max-nesting-depth to increase "
2592 return TokError(MaxNestingDepthError.str());
2595 MCAsmMacroArguments A;
2596 if (parseMacroArguments(M, A))
2599 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2600 // to hold the macro body with substitutions.
2601 SmallString<256> Buf;
2602 StringRef Body = M->Body;
2603 raw_svector_ostream OS(Buf);
2605 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2608 // We include the .endmacro in the buffer as our cue to exit the macro
2610 OS << ".endmacro\n";
2612 std::unique_ptr<MemoryBuffer> Instantiation =
2613 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2615 // Create the macro instantiation object and add to the current macro
2616 // instantiation stack.
2617 MacroInstantiation *MI = new MacroInstantiation(
2618 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2619 ActiveMacros.push_back(MI);
2621 ++NumOfMacroInstantiations;
2623 // Jump to the macro instantiation and prime the lexer.
2624 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2625 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2631 void AsmParser::handleMacroExit() {
2632 // Jump to the EndOfStatement we should return to, and consume it.
2633 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2636 // Pop the instantiation entry.
2637 delete ActiveMacros.back();
2638 ActiveMacros.pop_back();
2641 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2644 const MCExpr *Value;
2645 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2650 // In the case where we parse an expression starting with a '.', we will
2651 // not generate an error, nor will we create a symbol. In this case we
2652 // should just return out.
2656 // Do the assignment.
2657 Out.EmitAssignment(Sym, Value);
2659 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2664 /// parseIdentifier:
2667 bool AsmParser::parseIdentifier(StringRef &Res) {
2668 // The assembler has relaxed rules for accepting identifiers, in particular we
2669 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2670 // separate tokens. At this level, we have already lexed so we cannot (currently)
2671 // handle this as a context dependent token, instead we detect adjacent tokens
2672 // and return the combined identifier.
2673 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2674 SMLoc PrefixLoc = getLexer().getLoc();
2676 // Consume the prefix character, and check for a following identifier.
2679 Lexer.peekTokens(Buf, false);
2681 if (Buf[0].isNot(AsmToken::Identifier))
2684 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2685 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2689 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2690 // Construct the joined identifier and consume the token.
2692 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2693 Lex(); // Parser Lex to maintain invariants.
2697 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2700 Res = getTok().getIdentifier();
2702 Lex(); // Consume the identifier token.
2707 /// parseDirectiveSet:
2708 /// ::= .equ identifier ',' expression
2709 /// ::= .equiv identifier ',' expression
2710 /// ::= .set identifier ',' expression
2711 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2713 if (check(parseIdentifier(Name), "expected identifier") ||
2714 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2715 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2719 bool AsmParser::parseEscapedString(std::string &Data) {
2720 if (check(getTok().isNot(AsmToken::String), "expected string"))
2724 StringRef Str = getTok().getStringContents();
2725 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2726 if (Str[i] != '\\') {
2731 // Recognize escaped characters. Note that this escape semantics currently
2732 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2735 return TokError("unexpected backslash at end of string");
2737 // Recognize octal sequences.
2738 if ((unsigned)(Str[i] - '0') <= 7) {
2739 // Consume up to three octal characters.
2740 unsigned Value = Str[i] - '0';
2742 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2744 Value = Value * 8 + (Str[i] - '0');
2746 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2748 Value = Value * 8 + (Str[i] - '0');
2753 return TokError("invalid octal escape sequence (out of range)");
2755 Data += (unsigned char)Value;
2759 // Otherwise recognize individual escapes.
2762 // Just reject invalid escape sequences for now.
2763 return TokError("invalid escape sequence (unrecognized character)");
2765 case 'b': Data += '\b'; break;
2766 case 'f': Data += '\f'; break;
2767 case 'n': Data += '\n'; break;
2768 case 'r': Data += '\r'; break;
2769 case 't': Data += '\t'; break;
2770 case '"': Data += '"'; break;
2771 case '\\': Data += '\\'; break;
2779 /// parseDirectiveAscii:
2780 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2781 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2782 auto parseOp = [&]() -> bool {
2784 if (checkForValidSection() || parseEscapedString(Data))
2786 getStreamer().EmitBytes(Data);
2788 getStreamer().EmitBytes(StringRef("\0", 1));
2792 if (parseMany(parseOp))
2793 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2797 /// parseDirectiveReloc
2798 /// ::= .reloc expression , identifier [ , expression ]
2799 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2800 const MCExpr *Offset;
2801 const MCExpr *Expr = nullptr;
2803 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2804 int64_t OffsetValue;
2805 // We can only deal with constant expressions at the moment.
2807 if (parseExpression(Offset))
2810 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2811 "expression is not a constant value") ||
2812 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2813 parseToken(AsmToken::Comma, "expected comma") ||
2814 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2817 SMLoc NameLoc = Lexer.getTok().getLoc();
2818 StringRef Name = Lexer.getTok().getIdentifier();
2821 if (Lexer.is(AsmToken::Comma)) {
2823 SMLoc ExprLoc = Lexer.getLoc();
2824 if (parseExpression(Expr))
2828 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2829 return Error(ExprLoc, "expression must be relocatable");
2832 if (parseToken(AsmToken::EndOfStatement,
2833 "unexpected token in .reloc directive"))
2836 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2837 return Error(NameLoc, "unknown relocation name");
2842 /// parseDirectiveValue
2843 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2844 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2845 auto parseOp = [&]() -> bool {
2846 const MCExpr *Value;
2847 SMLoc ExprLoc = getLexer().getLoc();
2848 if (checkForValidSection() || parseExpression(Value))
2850 // Special case constant expressions to match code generator.
2851 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2852 assert(Size <= 8 && "Invalid size");
2853 uint64_t IntValue = MCE->getValue();
2854 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2855 return Error(ExprLoc, "out of range literal value");
2856 getStreamer().EmitIntValue(IntValue, Size);
2858 getStreamer().EmitValue(Value, Size, ExprLoc);
2862 if (parseMany(parseOp))
2863 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2867 /// ParseDirectiveOctaValue
2868 /// ::= .octa [ hexconstant (, hexconstant)* ]
2870 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2871 auto parseOp = [&]() -> bool {
2872 if (checkForValidSection())
2874 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2875 return TokError("unknown token in expression");
2876 SMLoc ExprLoc = getTok().getLoc();
2877 APInt IntValue = getTok().getAPIntVal();
2880 if (!IntValue.isIntN(128))
2881 return Error(ExprLoc, "out of range literal value");
2882 if (!IntValue.isIntN(64)) {
2883 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2884 lo = IntValue.getLoBits(64).getZExtValue();
2887 lo = IntValue.getZExtValue();
2889 if (MAI.isLittleEndian()) {
2890 getStreamer().EmitIntValue(lo, 8);
2891 getStreamer().EmitIntValue(hi, 8);
2893 getStreamer().EmitIntValue(hi, 8);
2894 getStreamer().EmitIntValue(lo, 8);
2899 if (parseMany(parseOp))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2904 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2905 // We don't truly support arithmetic on floating point expressions, so we
2906 // have to manually parse unary prefixes.
2908 if (getLexer().is(AsmToken::Minus)) {
2911 } else if (getLexer().is(AsmToken::Plus))
2914 if (Lexer.is(AsmToken::Error))
2915 return TokError(Lexer.getErr());
2916 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2917 Lexer.isNot(AsmToken::Identifier))
2918 return TokError("unexpected token in directive");
2920 // Convert to an APFloat.
2921 APFloat Value(Semantics);
2922 StringRef IDVal = getTok().getString();
2923 if (getLexer().is(AsmToken::Identifier)) {
2924 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2925 Value = APFloat::getInf(Semantics);
2926 else if (!IDVal.compare_lower("nan"))
2927 Value = APFloat::getNaN(Semantics, false, ~0);
2929 return TokError("invalid floating point literal");
2930 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2931 APFloat::opInvalidOp)
2932 return TokError("invalid floating point literal");
2936 // Consume the numeric token.
2939 Res = Value.bitcastToAPInt();
2944 /// parseDirectiveRealValue
2945 /// ::= (.single | .double) [ expression (, expression)* ]
2946 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2947 const fltSemantics &Semantics) {
2948 auto parseOp = [&]() -> bool {
2950 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
2952 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2953 AsInt.getBitWidth() / 8);
2957 if (parseMany(parseOp))
2958 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2962 /// parseDirectiveZero
2963 /// ::= .zero expression
2964 bool AsmParser::parseDirectiveZero() {
2965 SMLoc NumBytesLoc = Lexer.getLoc();
2966 const MCExpr *NumBytes;
2967 if (checkForValidSection() || parseExpression(NumBytes))
2971 if (getLexer().is(AsmToken::Comma)) {
2973 if (parseAbsoluteExpression(Val))
2977 if (parseToken(AsmToken::EndOfStatement,
2978 "unexpected token in '.zero' directive"))
2980 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
2985 /// parseDirectiveFill
2986 /// ::= .fill expression [ , expression [ , expression ] ]
2987 bool AsmParser::parseDirectiveFill() {
2988 SMLoc NumValuesLoc = Lexer.getLoc();
2989 const MCExpr *NumValues;
2990 if (checkForValidSection() || parseExpression(NumValues))
2993 int64_t FillSize = 1;
2994 int64_t FillExpr = 0;
2996 SMLoc SizeLoc, ExprLoc;
2998 if (parseOptionalToken(AsmToken::Comma)) {
2999 SizeLoc = getTok().getLoc();
3000 if (parseAbsoluteExpression(FillSize))
3002 if (parseOptionalToken(AsmToken::Comma)) {
3003 ExprLoc = getTok().getLoc();
3004 if (parseAbsoluteExpression(FillExpr))
3008 if (parseToken(AsmToken::EndOfStatement,
3009 "unexpected token in '.fill' directive"))
3013 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3017 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3021 if (!isUInt<32>(FillExpr) && FillSize > 4)
3022 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3024 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3029 /// parseDirectiveOrg
3030 /// ::= .org expression [ , expression ]
3031 bool AsmParser::parseDirectiveOrg() {
3032 const MCExpr *Offset;
3033 SMLoc OffsetLoc = Lexer.getLoc();
3034 if (checkForValidSection() || parseExpression(Offset))
3037 // Parse optional fill expression.
3038 int64_t FillExpr = 0;
3039 if (parseOptionalToken(AsmToken::Comma))
3040 if (parseAbsoluteExpression(FillExpr))
3041 return addErrorSuffix(" in '.org' directive");
3042 if (parseToken(AsmToken::EndOfStatement))
3043 return addErrorSuffix(" in '.org' directive");
3045 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3049 /// parseDirectiveAlign
3050 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3051 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3052 SMLoc AlignmentLoc = getLexer().getLoc();
3055 bool HasFillExpr = false;
3056 int64_t FillExpr = 0;
3057 int64_t MaxBytesToFill = 0;
3059 auto parseAlign = [&]() -> bool {
3060 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
3062 if (parseOptionalToken(AsmToken::Comma)) {
3063 // The fill expression can be omitted while specifying a maximum number of
3064 // alignment bytes, e.g:
3066 if (getTok().isNot(AsmToken::Comma)) {
3068 if (parseAbsoluteExpression(FillExpr))
3071 if (parseOptionalToken(AsmToken::Comma))
3072 if (parseTokenLoc(MaxBytesLoc) ||
3073 parseAbsoluteExpression(MaxBytesToFill))
3076 return parseToken(AsmToken::EndOfStatement);
3080 return addErrorSuffix(" in directive");
3082 // Always emit an alignment here even if we thrown an error.
3083 bool ReturnVal = false;
3085 // Compute alignment in bytes.
3087 // FIXME: Diagnose overflow.
3088 if (Alignment >= 32) {
3089 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3093 Alignment = 1ULL << Alignment;
3095 // Reject alignments that aren't either a power of two or zero,
3096 // for gas compatibility. Alignment of zero is silently rounded
3100 if (!isPowerOf2_64(Alignment))
3101 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3104 // Diagnose non-sensical max bytes to align.
3105 if (MaxBytesLoc.isValid()) {
3106 if (MaxBytesToFill < 1) {
3107 ReturnVal |= Error(MaxBytesLoc,
3108 "alignment directive can never be satisfied in this "
3109 "many bytes, ignoring maximum bytes expression");
3113 if (MaxBytesToFill >= Alignment) {
3114 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3120 // Check whether we should use optimal code alignment for this .align
3122 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3123 assert(Section && "must have section to emit alignment");
3124 bool UseCodeAlign = Section->UseCodeAlign();
3125 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3126 ValueSize == 1 && UseCodeAlign) {
3127 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3129 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3130 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3137 /// parseDirectiveFile
3138 /// ::= .file [number] filename
3139 /// ::= .file number directory filename
3140 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3141 // FIXME: I'm not sure what this is.
3142 int64_t FileNumber = -1;
3143 SMLoc FileNumberLoc = getLexer().getLoc();
3144 if (getLexer().is(AsmToken::Integer)) {
3145 FileNumber = getTok().getIntVal();
3149 return TokError("file number less than one");
3152 std::string Path = getTok().getString();
3154 // Usually the directory and filename together, otherwise just the directory.
3155 // Allow the strings to have escaped octal character sequence.
3156 if (check(getTok().isNot(AsmToken::String),
3157 "unexpected token in '.file' directive") ||
3158 parseEscapedString(Path))
3161 StringRef Directory;
3163 std::string FilenameData;
3164 if (getLexer().is(AsmToken::String)) {
3165 if (check(FileNumber == -1,
3166 "explicit path specified, but no file number") ||
3167 parseEscapedString(FilenameData))
3169 Filename = FilenameData;
3175 if (parseToken(AsmToken::EndOfStatement,
3176 "unexpected token in '.file' directive"))
3179 if (FileNumber == -1)
3180 getStreamer().EmitFileDirective(Filename);
3182 // If there is -g option as well as debug info from directive file,
3183 // we turn off -g option, directly use the existing debug info instead.
3184 if (getContext().getGenDwarfForAssembly())
3185 getContext().setGenDwarfForAssembly(false);
3186 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3188 return Error(FileNumberLoc, "file number already allocated");
3194 /// parseDirectiveLine
3195 /// ::= .line [number]
3196 bool AsmParser::parseDirectiveLine() {
3198 if (getLexer().is(AsmToken::Integer)) {
3199 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3202 // FIXME: Do something with the .line.
3204 if (parseToken(AsmToken::EndOfStatement,
3205 "unexpected token in '.line' directive"))
3211 /// parseDirectiveLoc
3212 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3213 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3214 /// The first number is a file number, must have been previously assigned with
3215 /// a .file directive, the second number is the line number and optionally the
3216 /// third number is a column position (zero if not specified). The remaining
3217 /// optional items are .loc sub-directives.
3218 bool AsmParser::parseDirectiveLoc() {
3219 int64_t FileNumber = 0, LineNumber = 0;
3220 SMLoc Loc = getTok().getLoc();
3221 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3222 check(FileNumber < 1, Loc,
3223 "file number less than one in '.loc' directive") ||
3224 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3225 "unassigned file number in '.loc' directive"))
3229 if (getLexer().is(AsmToken::Integer)) {
3230 LineNumber = getTok().getIntVal();
3232 return TokError("line number less than zero in '.loc' directive");
3236 int64_t ColumnPos = 0;
3237 if (getLexer().is(AsmToken::Integer)) {
3238 ColumnPos = getTok().getIntVal();
3240 return TokError("column position less than zero in '.loc' directive");
3244 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3246 int64_t Discriminator = 0;
3248 auto parseLocOp = [&]() -> bool {
3250 SMLoc Loc = getTok().getLoc();
3251 if (parseIdentifier(Name))
3252 return TokError("unexpected token in '.loc' directive");
3254 if (Name == "basic_block")
3255 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3256 else if (Name == "prologue_end")
3257 Flags |= DWARF2_FLAG_PROLOGUE_END;
3258 else if (Name == "epilogue_begin")
3259 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3260 else if (Name == "is_stmt") {
3261 Loc = getTok().getLoc();
3262 const MCExpr *Value;
3263 if (parseExpression(Value))
3265 // The expression must be the constant 0 or 1.
3266 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3267 int Value = MCE->getValue();
3269 Flags &= ~DWARF2_FLAG_IS_STMT;
3270 else if (Value == 1)
3271 Flags |= DWARF2_FLAG_IS_STMT;
3273 return Error(Loc, "is_stmt value not 0 or 1");
3275 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3277 } else if (Name == "isa") {
3278 Loc = getTok().getLoc();
3279 const MCExpr *Value;
3280 if (parseExpression(Value))
3282 // The expression must be a constant greater or equal to 0.
3283 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3284 int Value = MCE->getValue();
3286 return Error(Loc, "isa number less than zero");
3289 return Error(Loc, "isa number not a constant value");
3291 } else if (Name == "discriminator") {
3292 if (parseAbsoluteExpression(Discriminator))
3295 return Error(Loc, "unknown sub-directive in '.loc' directive");
3300 if (parseMany(parseLocOp, false /*hasComma*/))
3303 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3304 Isa, Discriminator, StringRef());
3309 /// parseDirectiveStabs
3310 /// ::= .stabs string, number, number, number
3311 bool AsmParser::parseDirectiveStabs() {
3312 return TokError("unsupported directive '.stabs'");
3315 /// parseDirectiveCVFile
3316 /// ::= .cv_file number filename
3317 bool AsmParser::parseDirectiveCVFile() {
3318 SMLoc FileNumberLoc = getTok().getLoc();
3320 std::string Filename;
3322 if (parseIntToken(FileNumber,
3323 "expected file number in '.cv_file' directive") ||
3324 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3325 check(getTok().isNot(AsmToken::String),
3326 "unexpected token in '.cv_file' directive") ||
3327 // Usually directory and filename are together, otherwise just
3328 // directory. Allow the strings to have escaped octal character sequence.
3329 parseEscapedString(Filename) ||
3330 parseToken(AsmToken::EndOfStatement,
3331 "unexpected token in '.cv_file' directive"))
3334 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
3335 return Error(FileNumberLoc, "file number already allocated");
3340 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3341 StringRef DirectiveName) {
3343 return parseTokenLoc(Loc) ||
3344 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3346 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3347 "expected function id within range [0, UINT_MAX)");
3350 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3352 return parseTokenLoc(Loc) ||
3353 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3355 check(FileNumber < 1, Loc, "file number less than one in '" +
3356 DirectiveName + "' directive") ||
3357 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3358 "unassigned file number in '" + DirectiveName + "' directive");
3361 /// parseDirectiveCVFuncId
3362 /// ::= .cv_func_id FunctionId
3364 /// Introduces a function ID that can be used with .cv_loc.
3365 bool AsmParser::parseDirectiveCVFuncId() {
3366 SMLoc FunctionIdLoc = getTok().getLoc();
3369 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3370 parseToken(AsmToken::EndOfStatement,
3371 "unexpected token in '.cv_func_id' directive"))
3374 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3375 return Error(FunctionIdLoc, "function id already allocated");
3380 /// parseDirectiveCVInlineSiteId
3381 /// ::= .cv_inline_site_id FunctionId
3383 /// "inlined_at" IAFile IALine [IACol]
3385 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3386 /// at" source location information for use in the line table of the caller,
3387 /// whether the caller is a real function or another inlined call site.
3388 bool AsmParser::parseDirectiveCVInlineSiteId() {
3389 SMLoc FunctionIdLoc = getTok().getLoc();
3397 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3401 if (check((getLexer().isNot(AsmToken::Identifier) ||
3402 getTok().getIdentifier() != "within"),
3403 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3408 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3412 if (check((getLexer().isNot(AsmToken::Identifier) ||
3413 getTok().getIdentifier() != "inlined_at"),
3414 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3420 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3421 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3425 if (getLexer().is(AsmToken::Integer)) {
3426 IACol = getTok().getIntVal();
3430 if (parseToken(AsmToken::EndOfStatement,
3431 "unexpected token in '.cv_inline_site_id' directive"))
3434 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3435 IALine, IACol, FunctionIdLoc))
3436 return Error(FunctionIdLoc, "function id already allocated");
3441 /// parseDirectiveCVLoc
3442 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3444 /// The first number is a file number, must have been previously assigned with
3445 /// a .file directive, the second number is the line number and optionally the
3446 /// third number is a column position (zero if not specified). The remaining
3447 /// optional items are .loc sub-directives.
3448 bool AsmParser::parseDirectiveCVLoc() {
3449 SMLoc DirectiveLoc = getTok().getLoc();
3451 int64_t FunctionId, FileNumber;
3452 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3453 parseCVFileId(FileNumber, ".cv_loc"))
3456 int64_t LineNumber = 0;
3457 if (getLexer().is(AsmToken::Integer)) {
3458 LineNumber = getTok().getIntVal();
3460 return TokError("line number less than zero in '.cv_loc' directive");
3464 int64_t ColumnPos = 0;
3465 if (getLexer().is(AsmToken::Integer)) {
3466 ColumnPos = getTok().getIntVal();
3468 return TokError("column position less than zero in '.cv_loc' directive");
3472 bool PrologueEnd = false;
3473 uint64_t IsStmt = 0;
3475 auto parseOp = [&]() -> bool {
3477 SMLoc Loc = getTok().getLoc();
3478 if (parseIdentifier(Name))
3479 return TokError("unexpected token in '.cv_loc' directive");
3480 if (Name == "prologue_end")
3482 else if (Name == "is_stmt") {
3483 Loc = getTok().getLoc();
3484 const MCExpr *Value;
3485 if (parseExpression(Value))
3487 // The expression must be the constant 0 or 1.
3489 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3490 IsStmt = MCE->getValue();
3493 return Error(Loc, "is_stmt value not 0 or 1");
3495 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3500 if (parseMany(parseOp, false /*hasComma*/))
3503 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3504 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3509 /// parseDirectiveCVLinetable
3510 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3511 bool AsmParser::parseDirectiveCVLinetable() {
3513 StringRef FnStartName, FnEndName;
3514 SMLoc Loc = getTok().getLoc();
3515 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3516 parseToken(AsmToken::Comma,
3517 "unexpected token in '.cv_linetable' directive") ||
3518 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3519 "expected identifier in directive") ||
3520 parseToken(AsmToken::Comma,
3521 "unexpected token in '.cv_linetable' directive") ||
3522 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3523 "expected identifier in directive"))
3526 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3527 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3529 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3533 /// parseDirectiveCVInlineLinetable
3534 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3535 bool AsmParser::parseDirectiveCVInlineLinetable() {
3536 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3537 StringRef FnStartName, FnEndName;
3538 SMLoc Loc = getTok().getLoc();
3539 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3540 parseTokenLoc(Loc) ||
3543 "expected SourceField in '.cv_inline_linetable' directive") ||
3544 check(SourceFileId <= 0, Loc,
3545 "File id less than zero in '.cv_inline_linetable' directive") ||
3546 parseTokenLoc(Loc) ||
3549 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3550 check(SourceLineNum < 0, Loc,
3551 "Line number less than zero in '.cv_inline_linetable' directive") ||
3552 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3553 "expected identifier in directive") ||
3554 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3555 "expected identifier in directive"))
3558 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3561 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3562 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3563 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3564 SourceLineNum, FnStartSym,
3569 /// parseDirectiveCVDefRange
3570 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3571 bool AsmParser::parseDirectiveCVDefRange() {
3573 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3574 while (getLexer().is(AsmToken::Identifier)) {
3575 Loc = getLexer().getLoc();
3576 StringRef GapStartName;
3577 if (parseIdentifier(GapStartName))
3578 return Error(Loc, "expected identifier in directive");
3579 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3581 Loc = getLexer().getLoc();
3582 StringRef GapEndName;
3583 if (parseIdentifier(GapEndName))
3584 return Error(Loc, "expected identifier in directive");
3585 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3587 Ranges.push_back({GapStartSym, GapEndSym});
3590 std::string FixedSizePortion;
3591 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3592 parseEscapedString(FixedSizePortion))
3595 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3599 /// parseDirectiveCVStringTable
3600 /// ::= .cv_stringtable
3601 bool AsmParser::parseDirectiveCVStringTable() {
3602 getStreamer().EmitCVStringTableDirective();
3606 /// parseDirectiveCVFileChecksums
3607 /// ::= .cv_filechecksums
3608 bool AsmParser::parseDirectiveCVFileChecksums() {
3609 getStreamer().EmitCVFileChecksumsDirective();
3613 /// parseDirectiveCFISections
3614 /// ::= .cfi_sections section [, section]
3615 bool AsmParser::parseDirectiveCFISections() {
3620 if (parseIdentifier(Name))
3621 return TokError("Expected an identifier");
3623 if (Name == ".eh_frame")
3625 else if (Name == ".debug_frame")
3628 if (getLexer().is(AsmToken::Comma)) {
3631 if (parseIdentifier(Name))
3632 return TokError("Expected an identifier");
3634 if (Name == ".eh_frame")
3636 else if (Name == ".debug_frame")
3640 getStreamer().EmitCFISections(EH, Debug);
3644 /// parseDirectiveCFIStartProc
3645 /// ::= .cfi_startproc [simple]
3646 bool AsmParser::parseDirectiveCFIStartProc() {
3648 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3649 if (check(parseIdentifier(Simple) || Simple != "simple",
3650 "unexpected token") ||
3651 parseToken(AsmToken::EndOfStatement))
3652 return addErrorSuffix(" in '.cfi_startproc' directive");
3655 getStreamer().EmitCFIStartProc(!Simple.empty());
3659 /// parseDirectiveCFIEndProc
3660 /// ::= .cfi_endproc
3661 bool AsmParser::parseDirectiveCFIEndProc() {
3662 getStreamer().EmitCFIEndProc();
3666 /// \brief parse register name or number.
3667 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3668 SMLoc DirectiveLoc) {
3671 if (getLexer().isNot(AsmToken::Integer)) {
3672 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3674 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3676 return parseAbsoluteExpression(Register);
3681 /// parseDirectiveCFIDefCfa
3682 /// ::= .cfi_def_cfa register, offset
3683 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3684 int64_t Register = 0, Offset = 0;
3685 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3686 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3687 parseAbsoluteExpression(Offset))
3690 getStreamer().EmitCFIDefCfa(Register, Offset);
3694 /// parseDirectiveCFIDefCfaOffset
3695 /// ::= .cfi_def_cfa_offset offset
3696 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3698 if (parseAbsoluteExpression(Offset))
3701 getStreamer().EmitCFIDefCfaOffset(Offset);
3705 /// parseDirectiveCFIRegister
3706 /// ::= .cfi_register register, register
3707 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3708 int64_t Register1 = 0, Register2 = 0;
3709 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3710 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3711 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3714 getStreamer().EmitCFIRegister(Register1, Register2);
3718 /// parseDirectiveCFIWindowSave
3719 /// ::= .cfi_window_save
3720 bool AsmParser::parseDirectiveCFIWindowSave() {
3721 getStreamer().EmitCFIWindowSave();
3725 /// parseDirectiveCFIAdjustCfaOffset
3726 /// ::= .cfi_adjust_cfa_offset adjustment
3727 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3728 int64_t Adjustment = 0;
3729 if (parseAbsoluteExpression(Adjustment))
3732 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3736 /// parseDirectiveCFIDefCfaRegister
3737 /// ::= .cfi_def_cfa_register register
3738 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3739 int64_t Register = 0;
3740 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3743 getStreamer().EmitCFIDefCfaRegister(Register);
3747 /// parseDirectiveCFIOffset
3748 /// ::= .cfi_offset register, offset
3749 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3750 int64_t Register = 0;
3753 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3754 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3755 parseAbsoluteExpression(Offset))
3758 getStreamer().EmitCFIOffset(Register, Offset);
3762 /// parseDirectiveCFIRelOffset
3763 /// ::= .cfi_rel_offset register, offset
3764 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3765 int64_t Register = 0, Offset = 0;
3767 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3768 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3769 parseAbsoluteExpression(Offset))
3772 getStreamer().EmitCFIRelOffset(Register, Offset);
3776 static bool isValidEncoding(int64_t Encoding) {
3777 if (Encoding & ~0xff)
3780 if (Encoding == dwarf::DW_EH_PE_omit)
3783 const unsigned Format = Encoding & 0xf;
3784 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3785 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3786 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3787 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3790 const unsigned Application = Encoding & 0x70;
3791 if (Application != dwarf::DW_EH_PE_absptr &&
3792 Application != dwarf::DW_EH_PE_pcrel)
3798 /// parseDirectiveCFIPersonalityOrLsda
3799 /// IsPersonality true for cfi_personality, false for cfi_lsda
3800 /// ::= .cfi_personality encoding, [symbol_name]
3801 /// ::= .cfi_lsda encoding, [symbol_name]
3802 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3803 int64_t Encoding = 0;
3804 if (parseAbsoluteExpression(Encoding))
3806 if (Encoding == dwarf::DW_EH_PE_omit)
3810 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3811 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3812 check(parseIdentifier(Name), "expected identifier in directive"))
3815 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3818 getStreamer().EmitCFIPersonality(Sym, Encoding);
3820 getStreamer().EmitCFILsda(Sym, Encoding);
3824 /// parseDirectiveCFIRememberState
3825 /// ::= .cfi_remember_state
3826 bool AsmParser::parseDirectiveCFIRememberState() {
3827 getStreamer().EmitCFIRememberState();
3831 /// parseDirectiveCFIRestoreState
3832 /// ::= .cfi_remember_state
3833 bool AsmParser::parseDirectiveCFIRestoreState() {
3834 getStreamer().EmitCFIRestoreState();
3838 /// parseDirectiveCFISameValue
3839 /// ::= .cfi_same_value register
3840 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3841 int64_t Register = 0;
3843 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3846 getStreamer().EmitCFISameValue(Register);
3850 /// parseDirectiveCFIRestore
3851 /// ::= .cfi_restore register
3852 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3853 int64_t Register = 0;
3854 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3857 getStreamer().EmitCFIRestore(Register);
3861 /// parseDirectiveCFIEscape
3862 /// ::= .cfi_escape expression[,...]
3863 bool AsmParser::parseDirectiveCFIEscape() {
3866 if (parseAbsoluteExpression(CurrValue))
3869 Values.push_back((uint8_t)CurrValue);
3871 while (getLexer().is(AsmToken::Comma)) {
3874 if (parseAbsoluteExpression(CurrValue))
3877 Values.push_back((uint8_t)CurrValue);
3880 getStreamer().EmitCFIEscape(Values);
3884 /// parseDirectiveCFISignalFrame
3885 /// ::= .cfi_signal_frame
3886 bool AsmParser::parseDirectiveCFISignalFrame() {
3887 if (parseToken(AsmToken::EndOfStatement,
3888 "unexpected token in '.cfi_signal_frame'"))
3891 getStreamer().EmitCFISignalFrame();
3895 /// parseDirectiveCFIUndefined
3896 /// ::= .cfi_undefined register
3897 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3898 int64_t Register = 0;
3900 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3903 getStreamer().EmitCFIUndefined(Register);
3907 /// parseDirectiveAltmacro
3910 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
3911 if (getLexer().isNot(AsmToken::EndOfStatement))
3912 return TokError("unexpected token in '" + Directive + "' directive");
3913 if (Directive == ".altmacro")
3914 getLexer().SetAltMacroMode(true);
3916 getLexer().SetAltMacroMode(false);
3920 /// parseDirectiveMacrosOnOff
3923 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3924 if (parseToken(AsmToken::EndOfStatement,
3925 "unexpected token in '" + Directive + "' directive"))
3928 setMacrosEnabled(Directive == ".macros_on");
3932 /// parseDirectiveMacro
3933 /// ::= .macro name[,] [parameters]
3934 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3936 if (parseIdentifier(Name))
3937 return TokError("expected identifier in '.macro' directive");
3939 if (getLexer().is(AsmToken::Comma))
3942 MCAsmMacroParameters Parameters;
3943 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3945 if (!Parameters.empty() && Parameters.back().Vararg)
3946 return Error(Lexer.getLoc(),
3947 "Vararg parameter '" + Parameters.back().Name +
3948 "' should be last one in the list of parameters.");
3950 MCAsmMacroParameter Parameter;
3951 if (parseIdentifier(Parameter.Name))
3952 return TokError("expected identifier in '.macro' directive");
3954 // Emit an error if two (or more) named parameters share the same name
3955 for (const MCAsmMacroParameter& CurrParam : Parameters)
3956 if (CurrParam.Name.equals(Parameter.Name))
3957 return TokError("macro '" + Name + "' has multiple parameters"
3958 " named '" + Parameter.Name + "'");
3960 if (Lexer.is(AsmToken::Colon)) {
3961 Lex(); // consume ':'
3964 StringRef Qualifier;
3966 QualLoc = Lexer.getLoc();
3967 if (parseIdentifier(Qualifier))
3968 return Error(QualLoc, "missing parameter qualifier for "
3969 "'" + Parameter.Name + "' in macro '" + Name + "'");
3971 if (Qualifier == "req")
3972 Parameter.Required = true;
3973 else if (Qualifier == "vararg")
3974 Parameter.Vararg = true;
3976 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3977 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3980 if (getLexer().is(AsmToken::Equal)) {
3985 ParamLoc = Lexer.getLoc();
3986 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3989 if (Parameter.Required)
3990 Warning(ParamLoc, "pointless default value for required parameter "
3991 "'" + Parameter.Name + "' in macro '" + Name + "'");
3994 Parameters.push_back(std::move(Parameter));
3996 if (getLexer().is(AsmToken::Comma))
4000 // Eat just the end of statement.
4003 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4004 AsmToken EndToken, StartToken = getTok();
4005 unsigned MacroDepth = 0;
4006 // Lex the macro definition.
4008 // Ignore Lexing errors in macros.
4009 while (Lexer.is(AsmToken::Error)) {
4013 // Check whether we have reached the end of the file.
4014 if (getLexer().is(AsmToken::Eof))
4015 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4017 // Otherwise, check whether we have reach the .endmacro.
4018 if (getLexer().is(AsmToken::Identifier)) {
4019 if (getTok().getIdentifier() == ".endm" ||
4020 getTok().getIdentifier() == ".endmacro") {
4021 if (MacroDepth == 0) { // Outermost macro.
4022 EndToken = getTok();
4024 if (getLexer().isNot(AsmToken::EndOfStatement))
4025 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4029 // Otherwise we just found the end of an inner macro.
4032 } else if (getTok().getIdentifier() == ".macro") {
4033 // We allow nested macros. Those aren't instantiated until the outermost
4034 // macro is expanded so just ignore them for now.
4039 // Otherwise, scan til the end of the statement.
4040 eatToEndOfStatement();
4043 if (lookupMacro(Name)) {
4044 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4047 const char *BodyStart = StartToken.getLoc().getPointer();
4048 const char *BodyEnd = EndToken.getLoc().getPointer();
4049 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4050 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4051 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
4055 /// checkForBadMacro
4057 /// With the support added for named parameters there may be code out there that
4058 /// is transitioning from positional parameters. In versions of gas that did
4059 /// not support named parameters they would be ignored on the macro definition.
4060 /// But to support both styles of parameters this is not possible so if a macro
4061 /// definition has named parameters but does not use them and has what appears
4062 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4063 /// warning that the positional parameter found in body which have no effect.
4064 /// Hoping the developer will either remove the named parameters from the macro
4065 /// definition so the positional parameters get used if that was what was
4066 /// intended or change the macro to use the named parameters. It is possible
4067 /// this warning will trigger when the none of the named parameters are used
4068 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4069 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4071 ArrayRef<MCAsmMacroParameter> Parameters) {
4072 // If this macro is not defined with named parameters the warning we are
4073 // checking for here doesn't apply.
4074 unsigned NParameters = Parameters.size();
4075 if (NParameters == 0)
4078 bool NamedParametersFound = false;
4079 bool PositionalParametersFound = false;
4081 // Look at the body of the macro for use of both the named parameters and what
4082 // are likely to be positional parameters. This is what expandMacro() is
4083 // doing when it finds the parameters in the body.
4084 while (!Body.empty()) {
4085 // Scan for the next possible parameter.
4086 std::size_t End = Body.size(), Pos = 0;
4087 for (; Pos != End; ++Pos) {
4088 // Check for a substitution or escape.
4089 // This macro is defined with parameters, look for \foo, \bar, etc.
4090 if (Body[Pos] == '\\' && Pos + 1 != End)
4093 // This macro should have parameters, but look for $0, $1, ..., $n too.
4094 if (Body[Pos] != '$' || Pos + 1 == End)
4096 char Next = Body[Pos + 1];
4097 if (Next == '$' || Next == 'n' ||
4098 isdigit(static_cast<unsigned char>(Next)))
4102 // Check if we reached the end.
4106 if (Body[Pos] == '$') {
4107 switch (Body[Pos + 1]) {
4112 // $n => number of arguments
4114 PositionalParametersFound = true;
4117 // $[0-9] => argument
4119 PositionalParametersFound = true;
4125 unsigned I = Pos + 1;
4126 while (isIdentifierChar(Body[I]) && I + 1 != End)
4129 const char *Begin = Body.data() + Pos + 1;
4130 StringRef Argument(Begin, I - (Pos + 1));
4132 for (; Index < NParameters; ++Index)
4133 if (Parameters[Index].Name == Argument)
4136 if (Index == NParameters) {
4137 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4143 NamedParametersFound = true;
4144 Pos += 1 + Argument.size();
4147 // Update the scan point.
4148 Body = Body.substr(Pos);
4151 if (!NamedParametersFound && PositionalParametersFound)
4152 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4153 "used in macro body, possible positional parameter "
4154 "found in body which will have no effect");
4157 /// parseDirectiveExitMacro
4159 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4160 if (parseToken(AsmToken::EndOfStatement,
4161 "unexpected token in '" + Directive + "' directive"))
4164 if (!isInsideMacroInstantiation())
4165 return TokError("unexpected '" + Directive + "' in file, "
4166 "no current macro definition");
4168 // Exit all conditionals that are active in the current macro.
4169 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4170 TheCondState = TheCondStack.back();
4171 TheCondStack.pop_back();
4178 /// parseDirectiveEndMacro
4181 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4182 if (getLexer().isNot(AsmToken::EndOfStatement))
4183 return TokError("unexpected token in '" + Directive + "' directive");
4185 // If we are inside a macro instantiation, terminate the current
4187 if (isInsideMacroInstantiation()) {
4192 // Otherwise, this .endmacro is a stray entry in the file; well formed
4193 // .endmacro directives are handled during the macro definition parsing.
4194 return TokError("unexpected '" + Directive + "' in file, "
4195 "no current macro definition");
4198 /// parseDirectivePurgeMacro
4200 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4203 if (parseTokenLoc(Loc) ||
4204 check(parseIdentifier(Name), Loc,
4205 "expected identifier in '.purgem' directive") ||
4206 parseToken(AsmToken::EndOfStatement,
4207 "unexpected token in '.purgem' directive"))
4210 if (!lookupMacro(Name))
4211 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4213 undefineMacro(Name);
4217 /// parseDirectiveBundleAlignMode
4218 /// ::= {.bundle_align_mode} expression
4219 bool AsmParser::parseDirectiveBundleAlignMode() {
4220 // Expect a single argument: an expression that evaluates to a constant
4221 // in the inclusive range 0-30.
4222 SMLoc ExprLoc = getLexer().getLoc();
4223 int64_t AlignSizePow2;
4224 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4225 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4226 "in '.bundle_align_mode' "
4228 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4229 "invalid bundle alignment size (expected between 0 and 30)"))
4232 // Because of AlignSizePow2's verified range we can safely truncate it to
4234 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4238 /// parseDirectiveBundleLock
4239 /// ::= {.bundle_lock} [align_to_end]
4240 bool AsmParser::parseDirectiveBundleLock() {
4241 if (checkForValidSection())
4243 bool AlignToEnd = false;
4246 SMLoc Loc = getTok().getLoc();
4247 const char *kInvalidOptionError =
4248 "invalid option for '.bundle_lock' directive";
4250 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4251 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4252 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4253 parseToken(AsmToken::EndOfStatement,
4254 "unexpected token after '.bundle_lock' directive option"))
4259 getStreamer().EmitBundleLock(AlignToEnd);
4263 /// parseDirectiveBundleLock
4264 /// ::= {.bundle_lock}
4265 bool AsmParser::parseDirectiveBundleUnlock() {
4266 if (checkForValidSection() ||
4267 parseToken(AsmToken::EndOfStatement,
4268 "unexpected token in '.bundle_unlock' directive"))
4271 getStreamer().EmitBundleUnlock();
4275 /// parseDirectiveSpace
4276 /// ::= (.skip | .space) expression [ , expression ]
4277 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4278 SMLoc NumBytesLoc = Lexer.getLoc();
4279 const MCExpr *NumBytes;
4280 if (checkForValidSection() || parseExpression(NumBytes))
4283 int64_t FillExpr = 0;
4284 if (parseOptionalToken(AsmToken::Comma))
4285 if (parseAbsoluteExpression(FillExpr))
4286 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4287 if (parseToken(AsmToken::EndOfStatement))
4288 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4290 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4291 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4296 /// parseDirectiveDCB
4297 /// ::= .dcb.{b, l, w} expression, expression
4298 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4299 SMLoc NumValuesLoc = Lexer.getLoc();
4301 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4304 if (NumValues < 0) {
4305 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4309 if (parseToken(AsmToken::Comma,
4310 "unexpected token in '" + Twine(IDVal) + "' directive"))
4313 const MCExpr *Value;
4314 SMLoc ExprLoc = getLexer().getLoc();
4315 if (parseExpression(Value))
4318 // Special case constant expressions to match code generator.
4319 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4320 assert(Size <= 8 && "Invalid size");
4321 uint64_t IntValue = MCE->getValue();
4322 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4323 return Error(ExprLoc, "literal value out of range for directive");
4324 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4325 getStreamer().EmitIntValue(IntValue, Size);
4327 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4328 getStreamer().EmitValue(Value, Size, ExprLoc);
4331 if (parseToken(AsmToken::EndOfStatement,
4332 "unexpected token in '" + Twine(IDVal) + "' directive"))
4338 /// parseDirectiveRealDCB
4339 /// ::= .dcb.{d, s} expression, expression
4340 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4341 SMLoc NumValuesLoc = Lexer.getLoc();
4343 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4346 if (NumValues < 0) {
4347 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4351 if (parseToken(AsmToken::Comma,
4352 "unexpected token in '" + Twine(IDVal) + "' directive"))
4356 if (parseRealValue(Semantics, AsInt))
4359 if (parseToken(AsmToken::EndOfStatement,
4360 "unexpected token in '" + Twine(IDVal) + "' directive"))
4363 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4364 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4365 AsInt.getBitWidth() / 8);
4370 /// parseDirectiveDS
4371 /// ::= .ds.{b, d, l, p, s, w, x} expression
4372 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4373 SMLoc NumValuesLoc = Lexer.getLoc();
4375 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4378 if (NumValues < 0) {
4379 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4383 if (parseToken(AsmToken::EndOfStatement,
4384 "unexpected token in '" + Twine(IDVal) + "' directive"))
4387 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4388 getStreamer().emitFill(Size, 0);
4393 /// parseDirectiveLEB128
4394 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4395 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4396 if (checkForValidSection())
4399 auto parseOp = [&]() -> bool {
4400 const MCExpr *Value;
4401 if (parseExpression(Value))
4404 getStreamer().EmitSLEB128Value(Value);
4406 getStreamer().EmitULEB128Value(Value);
4410 if (parseMany(parseOp))
4411 return addErrorSuffix(" in directive");
4416 /// parseDirectiveSymbolAttribute
4417 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4418 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4419 auto parseOp = [&]() -> bool {
4421 SMLoc Loc = getTok().getLoc();
4422 if (parseIdentifier(Name))
4423 return Error(Loc, "expected identifier");
4424 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4426 // Assembler local symbols don't make any sense here. Complain loudly.
4427 if (Sym->isTemporary())
4428 return Error(Loc, "non-local symbol required");
4430 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4431 return Error(Loc, "unable to emit symbol attribute");
4435 if (parseMany(parseOp))
4436 return addErrorSuffix(" in directive");
4440 /// parseDirectiveComm
4441 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4442 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4443 if (checkForValidSection())
4446 SMLoc IDLoc = getLexer().getLoc();
4448 if (parseIdentifier(Name))
4449 return TokError("expected identifier in directive");
4451 // Handle the identifier as the key symbol.
4452 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4454 if (getLexer().isNot(AsmToken::Comma))
4455 return TokError("unexpected token in directive");
4459 SMLoc SizeLoc = getLexer().getLoc();
4460 if (parseAbsoluteExpression(Size))
4463 int64_t Pow2Alignment = 0;
4464 SMLoc Pow2AlignmentLoc;
4465 if (getLexer().is(AsmToken::Comma)) {
4467 Pow2AlignmentLoc = getLexer().getLoc();
4468 if (parseAbsoluteExpression(Pow2Alignment))
4471 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4472 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4473 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4475 // If this target takes alignments in bytes (not log) validate and convert.
4476 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4477 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4478 if (!isPowerOf2_64(Pow2Alignment))
4479 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4480 Pow2Alignment = Log2_64(Pow2Alignment);
4484 if (parseToken(AsmToken::EndOfStatement,
4485 "unexpected token in '.comm' or '.lcomm' directive"))
4488 // NOTE: a size of zero for a .comm should create a undefined symbol
4489 // but a size of .lcomm creates a bss symbol of size zero.
4491 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4492 "be less than zero");
4494 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4495 // may internally end up wanting an alignment in bytes.
4496 // FIXME: Diagnose overflow.
4497 if (Pow2Alignment < 0)
4498 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4499 "alignment, can't be less than zero");
4501 Sym->redefineIfPossible();
4502 if (!Sym->isUndefined())
4503 return Error(IDLoc, "invalid symbol redefinition");
4505 // Create the Symbol as a common or local common with Size and Pow2Alignment
4507 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4511 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4515 /// parseDirectiveAbort
4516 /// ::= .abort [... message ...]
4517 bool AsmParser::parseDirectiveAbort() {
4518 // FIXME: Use loc from directive.
4519 SMLoc Loc = getLexer().getLoc();
4521 StringRef Str = parseStringToEndOfStatement();
4522 if (parseToken(AsmToken::EndOfStatement,
4523 "unexpected token in '.abort' directive"))
4527 return Error(Loc, ".abort detected. Assembly stopping.");
4529 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4530 // FIXME: Actually abort assembly here.
4535 /// parseDirectiveInclude
4536 /// ::= .include "filename"
4537 bool AsmParser::parseDirectiveInclude() {
4538 // Allow the strings to have escaped octal character sequence.
4539 std::string Filename;
4540 SMLoc IncludeLoc = getTok().getLoc();
4542 if (check(getTok().isNot(AsmToken::String),
4543 "expected string in '.include' directive") ||
4544 parseEscapedString(Filename) ||
4545 check(getTok().isNot(AsmToken::EndOfStatement),
4546 "unexpected token in '.include' directive") ||
4547 // Attempt to switch the lexer to the included file before consuming the
4548 // end of statement to avoid losing it when we switch.
4549 check(enterIncludeFile(Filename), IncludeLoc,
4550 "Could not find include file '" + Filename + "'"))
4556 /// parseDirectiveIncbin
4557 /// ::= .incbin "filename" [ , skip [ , count ] ]
4558 bool AsmParser::parseDirectiveIncbin() {
4559 // Allow the strings to have escaped octal character sequence.
4560 std::string Filename;
4561 SMLoc IncbinLoc = getTok().getLoc();
4562 if (check(getTok().isNot(AsmToken::String),
4563 "expected string in '.incbin' directive") ||
4564 parseEscapedString(Filename))
4568 const MCExpr *Count = nullptr;
4569 SMLoc SkipLoc, CountLoc;
4570 if (parseOptionalToken(AsmToken::Comma)) {
4571 // The skip expression can be omitted while specifying the count, e.g:
4572 // .incbin "filename",,4
4573 if (getTok().isNot(AsmToken::Comma)) {
4574 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4577 if (parseOptionalToken(AsmToken::Comma)) {
4578 CountLoc = getTok().getLoc();
4579 if (parseExpression(Count))
4584 if (parseToken(AsmToken::EndOfStatement,
4585 "unexpected token in '.incbin' directive"))
4588 if (check(Skip < 0, SkipLoc, "skip is negative"))
4591 // Attempt to process the included file.
4592 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4593 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4597 /// parseDirectiveIf
4598 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4599 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4600 TheCondStack.push_back(TheCondState);
4601 TheCondState.TheCond = AsmCond::IfCond;
4602 if (TheCondState.Ignore) {
4603 eatToEndOfStatement();
4606 if (parseAbsoluteExpression(ExprValue) ||
4607 parseToken(AsmToken::EndOfStatement,
4608 "unexpected token in '.if' directive"))
4613 llvm_unreachable("unsupported directive");
4618 ExprValue = ExprValue == 0;
4621 ExprValue = ExprValue >= 0;
4624 ExprValue = ExprValue > 0;
4627 ExprValue = ExprValue <= 0;
4630 ExprValue = ExprValue < 0;
4634 TheCondState.CondMet = ExprValue;
4635 TheCondState.Ignore = !TheCondState.CondMet;
4641 /// parseDirectiveIfb
4643 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4644 TheCondStack.push_back(TheCondState);
4645 TheCondState.TheCond = AsmCond::IfCond;
4647 if (TheCondState.Ignore) {
4648 eatToEndOfStatement();
4650 StringRef Str = parseStringToEndOfStatement();
4652 if (parseToken(AsmToken::EndOfStatement,
4653 "unexpected token in '.ifb' directive"))
4656 TheCondState.CondMet = ExpectBlank == Str.empty();
4657 TheCondState.Ignore = !TheCondState.CondMet;
4663 /// parseDirectiveIfc
4664 /// ::= .ifc string1, string2
4665 /// ::= .ifnc string1, string2
4666 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4667 TheCondStack.push_back(TheCondState);
4668 TheCondState.TheCond = AsmCond::IfCond;
4670 if (TheCondState.Ignore) {
4671 eatToEndOfStatement();
4673 StringRef Str1 = parseStringToComma();
4675 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4678 StringRef Str2 = parseStringToEndOfStatement();
4680 if (parseToken(AsmToken::EndOfStatement,
4681 "unexpected token in '.ifc' directive"))
4684 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4685 TheCondState.Ignore = !TheCondState.CondMet;
4691 /// parseDirectiveIfeqs
4692 /// ::= .ifeqs string1, string2
4693 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4694 if (Lexer.isNot(AsmToken::String)) {
4696 return TokError("expected string parameter for '.ifeqs' directive");
4697 return TokError("expected string parameter for '.ifnes' directive");
4700 StringRef String1 = getTok().getStringContents();
4703 if (Lexer.isNot(AsmToken::Comma)) {
4706 "expected comma after first string for '.ifeqs' directive");
4707 return TokError("expected comma after first string for '.ifnes' directive");
4712 if (Lexer.isNot(AsmToken::String)) {
4714 return TokError("expected string parameter for '.ifeqs' directive");
4715 return TokError("expected string parameter for '.ifnes' directive");
4718 StringRef String2 = getTok().getStringContents();
4721 TheCondStack.push_back(TheCondState);
4722 TheCondState.TheCond = AsmCond::IfCond;
4723 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4724 TheCondState.Ignore = !TheCondState.CondMet;
4729 /// parseDirectiveIfdef
4730 /// ::= .ifdef symbol
4731 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4733 TheCondStack.push_back(TheCondState);
4734 TheCondState.TheCond = AsmCond::IfCond;
4736 if (TheCondState.Ignore) {
4737 eatToEndOfStatement();
4739 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4740 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4743 MCSymbol *Sym = getContext().lookupSymbol(Name);
4746 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4748 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4749 TheCondState.Ignore = !TheCondState.CondMet;
4755 /// parseDirectiveElseIf
4756 /// ::= .elseif expression
4757 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4758 if (TheCondState.TheCond != AsmCond::IfCond &&
4759 TheCondState.TheCond != AsmCond::ElseIfCond)
4760 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4761 " .if or an .elseif");
4762 TheCondState.TheCond = AsmCond::ElseIfCond;
4764 bool LastIgnoreState = false;
4765 if (!TheCondStack.empty())
4766 LastIgnoreState = TheCondStack.back().Ignore;
4767 if (LastIgnoreState || TheCondState.CondMet) {
4768 TheCondState.Ignore = true;
4769 eatToEndOfStatement();
4772 if (parseAbsoluteExpression(ExprValue))
4775 if (parseToken(AsmToken::EndOfStatement,
4776 "unexpected token in '.elseif' directive"))
4779 TheCondState.CondMet = ExprValue;
4780 TheCondState.Ignore = !TheCondState.CondMet;
4786 /// parseDirectiveElse
4788 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4789 if (parseToken(AsmToken::EndOfStatement,
4790 "unexpected token in '.else' directive"))
4793 if (TheCondState.TheCond != AsmCond::IfCond &&
4794 TheCondState.TheCond != AsmCond::ElseIfCond)
4795 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4796 " an .if or an .elseif");
4797 TheCondState.TheCond = AsmCond::ElseCond;
4798 bool LastIgnoreState = false;
4799 if (!TheCondStack.empty())
4800 LastIgnoreState = TheCondStack.back().Ignore;
4801 if (LastIgnoreState || TheCondState.CondMet)
4802 TheCondState.Ignore = true;
4804 TheCondState.Ignore = false;
4809 /// parseDirectiveEnd
4811 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4812 if (parseToken(AsmToken::EndOfStatement,
4813 "unexpected token in '.end' directive"))
4816 while (Lexer.isNot(AsmToken::Eof))
4822 /// parseDirectiveError
4824 /// ::= .error [string]
4825 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4826 if (!TheCondStack.empty()) {
4827 if (TheCondStack.back().Ignore) {
4828 eatToEndOfStatement();
4834 return Error(L, ".err encountered");
4836 StringRef Message = ".error directive invoked in source file";
4837 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4838 if (Lexer.isNot(AsmToken::String))
4839 return TokError(".error argument must be a string");
4841 Message = getTok().getStringContents();
4845 return Error(L, Message);
4848 /// parseDirectiveWarning
4849 /// ::= .warning [string]
4850 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4851 if (!TheCondStack.empty()) {
4852 if (TheCondStack.back().Ignore) {
4853 eatToEndOfStatement();
4858 StringRef Message = ".warning directive invoked in source file";
4860 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4861 if (Lexer.isNot(AsmToken::String))
4862 return TokError(".warning argument must be a string");
4864 Message = getTok().getStringContents();
4866 if (parseToken(AsmToken::EndOfStatement,
4867 "expected end of statement in '.warning' directive"))
4871 return Warning(L, Message);
4874 /// parseDirectiveEndIf
4876 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4877 if (parseToken(AsmToken::EndOfStatement,
4878 "unexpected token in '.endif' directive"))
4881 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4882 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4884 if (!TheCondStack.empty()) {
4885 TheCondState = TheCondStack.back();
4886 TheCondStack.pop_back();
4892 void AsmParser::initializeDirectiveKindMap() {
4893 DirectiveKindMap[".set"] = DK_SET;
4894 DirectiveKindMap[".equ"] = DK_EQU;
4895 DirectiveKindMap[".equiv"] = DK_EQUIV;
4896 DirectiveKindMap[".ascii"] = DK_ASCII;
4897 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4898 DirectiveKindMap[".string"] = DK_STRING;
4899 DirectiveKindMap[".byte"] = DK_BYTE;
4900 DirectiveKindMap[".short"] = DK_SHORT;
4901 DirectiveKindMap[".value"] = DK_VALUE;
4902 DirectiveKindMap[".2byte"] = DK_2BYTE;
4903 DirectiveKindMap[".long"] = DK_LONG;
4904 DirectiveKindMap[".int"] = DK_INT;
4905 DirectiveKindMap[".4byte"] = DK_4BYTE;
4906 DirectiveKindMap[".quad"] = DK_QUAD;
4907 DirectiveKindMap[".8byte"] = DK_8BYTE;
4908 DirectiveKindMap[".octa"] = DK_OCTA;
4909 DirectiveKindMap[".single"] = DK_SINGLE;
4910 DirectiveKindMap[".float"] = DK_FLOAT;
4911 DirectiveKindMap[".double"] = DK_DOUBLE;
4912 DirectiveKindMap[".align"] = DK_ALIGN;
4913 DirectiveKindMap[".align32"] = DK_ALIGN32;
4914 DirectiveKindMap[".balign"] = DK_BALIGN;
4915 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4916 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4917 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4918 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4919 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4920 DirectiveKindMap[".org"] = DK_ORG;
4921 DirectiveKindMap[".fill"] = DK_FILL;
4922 DirectiveKindMap[".zero"] = DK_ZERO;
4923 DirectiveKindMap[".extern"] = DK_EXTERN;
4924 DirectiveKindMap[".globl"] = DK_GLOBL;
4925 DirectiveKindMap[".global"] = DK_GLOBAL;
4926 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4927 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4928 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4929 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4930 DirectiveKindMap[".reference"] = DK_REFERENCE;
4931 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4932 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4933 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4934 DirectiveKindMap[".comm"] = DK_COMM;
4935 DirectiveKindMap[".common"] = DK_COMMON;
4936 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4937 DirectiveKindMap[".abort"] = DK_ABORT;
4938 DirectiveKindMap[".include"] = DK_INCLUDE;
4939 DirectiveKindMap[".incbin"] = DK_INCBIN;
4940 DirectiveKindMap[".code16"] = DK_CODE16;
4941 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4942 DirectiveKindMap[".rept"] = DK_REPT;
4943 DirectiveKindMap[".rep"] = DK_REPT;
4944 DirectiveKindMap[".irp"] = DK_IRP;
4945 DirectiveKindMap[".irpc"] = DK_IRPC;
4946 DirectiveKindMap[".endr"] = DK_ENDR;
4947 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4948 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4949 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4950 DirectiveKindMap[".if"] = DK_IF;
4951 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4952 DirectiveKindMap[".ifge"] = DK_IFGE;
4953 DirectiveKindMap[".ifgt"] = DK_IFGT;
4954 DirectiveKindMap[".ifle"] = DK_IFLE;
4955 DirectiveKindMap[".iflt"] = DK_IFLT;
4956 DirectiveKindMap[".ifne"] = DK_IFNE;
4957 DirectiveKindMap[".ifb"] = DK_IFB;
4958 DirectiveKindMap[".ifnb"] = DK_IFNB;
4959 DirectiveKindMap[".ifc"] = DK_IFC;
4960 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4961 DirectiveKindMap[".ifnc"] = DK_IFNC;
4962 DirectiveKindMap[".ifnes"] = DK_IFNES;
4963 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4964 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4965 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4966 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4967 DirectiveKindMap[".else"] = DK_ELSE;
4968 DirectiveKindMap[".end"] = DK_END;
4969 DirectiveKindMap[".endif"] = DK_ENDIF;
4970 DirectiveKindMap[".skip"] = DK_SKIP;
4971 DirectiveKindMap[".space"] = DK_SPACE;
4972 DirectiveKindMap[".file"] = DK_FILE;
4973 DirectiveKindMap[".line"] = DK_LINE;
4974 DirectiveKindMap[".loc"] = DK_LOC;
4975 DirectiveKindMap[".stabs"] = DK_STABS;
4976 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4977 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
4978 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4979 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4980 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
4981 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
4982 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
4983 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4984 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
4985 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4986 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4987 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4988 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4989 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4990 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4991 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4992 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4993 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4994 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4995 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4996 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4997 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4998 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4999 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5000 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5001 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5002 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5003 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5004 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5005 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5006 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5007 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5008 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5009 DirectiveKindMap[".macro"] = DK_MACRO;
5010 DirectiveKindMap[".exitm"] = DK_EXITM;
5011 DirectiveKindMap[".endm"] = DK_ENDM;
5012 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5013 DirectiveKindMap[".purgem"] = DK_PURGEM;
5014 DirectiveKindMap[".err"] = DK_ERR;
5015 DirectiveKindMap[".error"] = DK_ERROR;
5016 DirectiveKindMap[".warning"] = DK_WARNING;
5017 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5018 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5019 DirectiveKindMap[".reloc"] = DK_RELOC;
5020 DirectiveKindMap[".dc"] = DK_DC;
5021 DirectiveKindMap[".dc.a"] = DK_DC_A;
5022 DirectiveKindMap[".dc.b"] = DK_DC_B;
5023 DirectiveKindMap[".dc.d"] = DK_DC_D;
5024 DirectiveKindMap[".dc.l"] = DK_DC_L;
5025 DirectiveKindMap[".dc.s"] = DK_DC_S;
5026 DirectiveKindMap[".dc.w"] = DK_DC_W;
5027 DirectiveKindMap[".dc.x"] = DK_DC_X;
5028 DirectiveKindMap[".dcb"] = DK_DCB;
5029 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5030 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5031 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5032 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5033 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5034 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5035 DirectiveKindMap[".ds"] = DK_DS;
5036 DirectiveKindMap[".ds.b"] = DK_DS_B;
5037 DirectiveKindMap[".ds.d"] = DK_DS_D;
5038 DirectiveKindMap[".ds.l"] = DK_DS_L;
5039 DirectiveKindMap[".ds.p"] = DK_DS_P;
5040 DirectiveKindMap[".ds.s"] = DK_DS_S;
5041 DirectiveKindMap[".ds.w"] = DK_DS_W;
5042 DirectiveKindMap[".ds.x"] = DK_DS_X;
5045 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5046 AsmToken EndToken, StartToken = getTok();
5048 unsigned NestLevel = 0;
5050 // Check whether we have reached the end of the file.
5051 if (getLexer().is(AsmToken::Eof)) {
5052 printError(DirectiveLoc, "no matching '.endr' in definition");
5056 if (Lexer.is(AsmToken::Identifier) &&
5057 (getTok().getIdentifier() == ".rept" ||
5058 getTok().getIdentifier() == ".irp" ||
5059 getTok().getIdentifier() == ".irpc")) {
5063 // Otherwise, check whether we have reached the .endr.
5064 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5065 if (NestLevel == 0) {
5066 EndToken = getTok();
5068 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5069 printError(getTok().getLoc(),
5070 "unexpected token in '.endr' directive");
5078 // Otherwise, scan till the end of the statement.
5079 eatToEndOfStatement();
5082 const char *BodyStart = StartToken.getLoc().getPointer();
5083 const char *BodyEnd = EndToken.getLoc().getPointer();
5084 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5086 // We Are Anonymous.
5087 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5088 return &MacroLikeBodies.back();
5091 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5092 raw_svector_ostream &OS) {
5095 std::unique_ptr<MemoryBuffer> Instantiation =
5096 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5098 // Create the macro instantiation object and add to the current macro
5099 // instantiation stack.
5100 MacroInstantiation *MI = new MacroInstantiation(
5101 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5102 ActiveMacros.push_back(MI);
5104 // Jump to the macro instantiation and prime the lexer.
5105 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5106 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5110 /// parseDirectiveRept
5111 /// ::= .rep | .rept count
5112 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5113 const MCExpr *CountExpr;
5114 SMLoc CountLoc = getTok().getLoc();
5115 if (parseExpression(CountExpr))
5119 if (!CountExpr->evaluateAsAbsolute(Count)) {
5120 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5123 if (check(Count < 0, CountLoc, "Count is negative") ||
5124 parseToken(AsmToken::EndOfStatement,
5125 "unexpected token in '" + Dir + "' directive"))
5128 // Lex the rept definition.
5129 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5133 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5134 // to hold the macro body with substitutions.
5135 SmallString<256> Buf;
5136 raw_svector_ostream OS(Buf);
5138 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5139 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5142 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5147 /// parseDirectiveIrp
5148 /// ::= .irp symbol,values
5149 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5150 MCAsmMacroParameter Parameter;
5151 MCAsmMacroArguments A;
5152 if (check(parseIdentifier(Parameter.Name),
5153 "expected identifier in '.irp' directive") ||
5154 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5155 parseMacroArguments(nullptr, A) ||
5156 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5159 // Lex the irp definition.
5160 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5164 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5165 // to hold the macro body with substitutions.
5166 SmallString<256> Buf;
5167 raw_svector_ostream OS(Buf);
5169 for (const MCAsmMacroArgument &Arg : A) {
5170 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5171 // This is undocumented, but GAS seems to support it.
5172 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5176 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5181 /// parseDirectiveIrpc
5182 /// ::= .irpc symbol,values
5183 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5184 MCAsmMacroParameter Parameter;
5185 MCAsmMacroArguments A;
5187 if (check(parseIdentifier(Parameter.Name),
5188 "expected identifier in '.irpc' directive") ||
5189 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5190 parseMacroArguments(nullptr, A))
5193 if (A.size() != 1 || A.front().size() != 1)
5194 return TokError("unexpected token in '.irpc' directive");
5196 // Eat the end of statement.
5197 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5200 // Lex the irpc definition.
5201 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5205 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5206 // to hold the macro body with substitutions.
5207 SmallString<256> Buf;
5208 raw_svector_ostream OS(Buf);
5210 StringRef Values = A.front().front().getString();
5211 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5212 MCAsmMacroArgument Arg;
5213 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5215 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5216 // This is undocumented, but GAS seems to support it.
5217 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5221 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5226 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5227 if (ActiveMacros.empty())
5228 return TokError("unmatched '.endr' directive");
5230 // The only .repl that should get here are the ones created by
5231 // instantiateMacroLikeBody.
5232 assert(getLexer().is(AsmToken::EndOfStatement));
5238 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5240 const MCExpr *Value;
5241 SMLoc ExprLoc = getLexer().getLoc();
5242 if (parseExpression(Value))
5244 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5246 return Error(ExprLoc, "unexpected expression in _emit");
5247 uint64_t IntValue = MCE->getValue();
5248 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5249 return Error(ExprLoc, "literal value out of range for directive");
5251 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5255 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5256 const MCExpr *Value;
5257 SMLoc ExprLoc = getLexer().getLoc();
5258 if (parseExpression(Value))
5260 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5262 return Error(ExprLoc, "unexpected expression in align");
5263 uint64_t IntValue = MCE->getValue();
5264 if (!isPowerOf2_64(IntValue))
5265 return Error(ExprLoc, "literal value not a power of two greater then zero");
5267 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5271 // We are comparing pointers, but the pointers are relative to a single string.
5272 // Thus, this should always be deterministic.
5273 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5274 const AsmRewrite *AsmRewriteB) {
5275 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5277 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5280 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5281 // rewrite to the same location. Make sure the SizeDirective rewrite is
5282 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5283 // ensures the sort algorithm is stable.
5284 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5285 AsmRewritePrecedence[AsmRewriteB->Kind])
5288 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5289 AsmRewritePrecedence[AsmRewriteB->Kind])
5291 llvm_unreachable("Unstable rewrite sort.");
5294 bool AsmParser::parseMSInlineAsm(
5295 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5296 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5297 SmallVectorImpl<std::string> &Constraints,
5298 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5299 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5300 SmallVector<void *, 4> InputDecls;
5301 SmallVector<void *, 4> OutputDecls;
5302 SmallVector<bool, 4> InputDeclsAddressOf;
5303 SmallVector<bool, 4> OutputDeclsAddressOf;
5304 SmallVector<std::string, 4> InputConstraints;
5305 SmallVector<std::string, 4> OutputConstraints;
5306 SmallVector<unsigned, 4> ClobberRegs;
5308 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5313 // While we have input, parse each statement.
5314 unsigned InputIdx = 0;
5315 unsigned OutputIdx = 0;
5316 while (getLexer().isNot(AsmToken::Eof)) {
5317 // Parse curly braces marking block start/end
5318 if (parseCurlyBlockScope(AsmStrRewrites))
5321 ParseStatementInfo Info(&AsmStrRewrites);
5322 bool StatementErr = parseStatement(Info, &SI);
5324 if (StatementErr || Info.ParseError) {
5325 // Emit pending errors if any exist.
5326 printPendingErrors();
5330 // No pending error should exist here.
5331 assert(!hasPendingError() && "unexpected error from parseStatement");
5333 if (Info.Opcode == ~0U)
5336 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5338 // Build the list of clobbers, outputs and inputs.
5339 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5340 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5343 if (Operand.isImm())
5346 // Register operand.
5347 if (Operand.isReg() && !Operand.needAddressOf() &&
5348 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5349 unsigned NumDefs = Desc.getNumDefs();
5351 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5352 ClobberRegs.push_back(Operand.getReg());
5356 // Expr/Input or Output.
5357 StringRef SymName = Operand.getSymName();
5358 if (SymName.empty())
5361 void *OpDecl = Operand.getOpDecl();
5365 bool isOutput = (i == 1) && Desc.mayStore();
5366 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5369 OutputDecls.push_back(OpDecl);
5370 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5371 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5372 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5374 InputDecls.push_back(OpDecl);
5375 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5376 InputConstraints.push_back(Operand.getConstraint().str());
5377 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5381 // Consider implicit defs to be clobbers. Think of cpuid and push.
5382 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5383 Desc.getNumImplicitDefs());
5384 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5387 // Set the number of Outputs and Inputs.
5388 NumOutputs = OutputDecls.size();
5389 NumInputs = InputDecls.size();
5391 // Set the unique clobbers.
5392 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5393 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5395 Clobbers.assign(ClobberRegs.size(), std::string());
5396 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5397 raw_string_ostream OS(Clobbers[I]);
5398 IP->printRegName(OS, ClobberRegs[I]);
5401 // Merge the various outputs and inputs. Output are expected first.
5402 if (NumOutputs || NumInputs) {
5403 unsigned NumExprs = NumOutputs + NumInputs;
5404 OpDecls.resize(NumExprs);
5405 Constraints.resize(NumExprs);
5406 for (unsigned i = 0; i < NumOutputs; ++i) {
5407 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5408 Constraints[i] = OutputConstraints[i];
5410 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5411 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5412 Constraints[j] = InputConstraints[i];
5416 // Build the IR assembly string.
5417 std::string AsmStringIR;
5418 raw_string_ostream OS(AsmStringIR);
5419 StringRef ASMString =
5420 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5421 const char *AsmStart = ASMString.begin();
5422 const char *AsmEnd = ASMString.end();
5423 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5424 for (const AsmRewrite &AR : AsmStrRewrites) {
5425 AsmRewriteKind Kind = AR.Kind;
5426 if (Kind == AOK_Delete)
5429 const char *Loc = AR.Loc.getPointer();
5430 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5432 // Emit everything up to the immediate/expression.
5433 if (unsigned Len = Loc - AsmStart)
5434 OS << StringRef(AsmStart, Len);
5436 // Skip the original expression.
5437 if (Kind == AOK_Skip) {
5438 AsmStart = Loc + AR.Len;
5442 unsigned AdditionalSkip = 0;
5443 // Rewrite expressions in $N notation.
5448 OS << "$$" << AR.Val;
5454 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5457 OS << '$' << InputIdx++;
5460 OS << '$' << OutputIdx++;
5462 case AOK_SizeDirective:
5465 case 8: OS << "byte ptr "; break;
5466 case 16: OS << "word ptr "; break;
5467 case 32: OS << "dword ptr "; break;
5468 case 64: OS << "qword ptr "; break;
5469 case 80: OS << "xword ptr "; break;
5470 case 128: OS << "xmmword ptr "; break;
5471 case 256: OS << "ymmword ptr "; break;
5478 // MS alignment directives are measured in bytes. If the native assembler
5479 // measures alignment in bytes, we can pass it straight through.
5481 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5484 // Alignment is in log2 form, so print that instead and skip the original
5486 unsigned Val = AR.Val;
5488 assert(Val < 10 && "Expected alignment less then 2^10.");
5489 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5495 case AOK_DotOperator:
5496 // Insert the dot if the user omitted it.
5498 if (AsmStringIR.back() != '.')
5502 case AOK_EndOfStatement:
5507 // Skip the original expression.
5508 AsmStart = Loc + AR.Len + AdditionalSkip;
5511 // Emit the remainder of the asm string.
5512 if (AsmStart != AsmEnd)
5513 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5515 AsmString = OS.str();
5520 namespace MCParserUtils {
5522 /// Returns whether the given symbol is used anywhere in the given expression,
5523 /// or subexpressions.
5524 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5525 switch (Value->getKind()) {
5526 case MCExpr::Binary: {
5527 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5528 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5529 isSymbolUsedInExpression(Sym, BE->getRHS());
5531 case MCExpr::Target:
5532 case MCExpr::Constant:
5534 case MCExpr::SymbolRef: {
5536 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5538 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5542 return isSymbolUsedInExpression(
5543 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5546 llvm_unreachable("Unknown expr kind!");
5549 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5550 MCAsmParser &Parser, MCSymbol *&Sym,
5551 const MCExpr *&Value) {
5553 // FIXME: Use better location, we should use proper tokens.
5554 SMLoc EqualLoc = Parser.getTok().getLoc();
5556 if (Parser.parseExpression(Value)) {
5557 return Parser.TokError("missing expression");
5560 // Note: we don't count b as used in "a = b". This is to allow
5564 if (Parser.parseToken(AsmToken::EndOfStatement))
5567 // Validate that the LHS is allowed to be a variable (either it has not been
5568 // used as a symbol, or it is an absolute symbol).
5569 Sym = Parser.getContext().lookupSymbol(Name);
5571 // Diagnose assignment to a label.
5573 // FIXME: Diagnostics. Note the location of the definition as a label.
5574 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5575 if (isSymbolUsedInExpression(Sym, Value))
5576 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5577 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5579 ; // Allow redefinitions of undefined symbols only used in directives.
5580 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5581 ; // Allow redefinitions of variables that haven't yet been used.
5582 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5583 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5584 else if (!Sym->isVariable())
5585 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5586 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5587 return Parser.Error(EqualLoc,
5588 "invalid reassignment of non-absolute variable '" +
5590 } else if (Name == ".") {
5591 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5594 Sym = Parser.getContext().getOrCreateSymbol(Name);
5596 Sym->setRedefinable(allow_redef);
5601 } // end namespace MCParserUtils
5602 } // end namespace llvm
5604 /// \brief Create an MCAsmParser instance.
5605 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5606 MCStreamer &Out, const MCAsmInfo &MAI,
5608 return new AsmParser(SM, C, Out, MAI, CB);