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 parseStatement(ParseStatementInfo &Info,
291 MCAsmParserSemaCallback *SI);
292 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
293 bool parseCppHashLineFilenameComment(SMLoc L);
295 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
296 ArrayRef<MCAsmMacroParameter> Parameters);
297 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
298 ArrayRef<MCAsmMacroParameter> Parameters,
299 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
302 /// \brief Are macros enabled in the parser?
303 bool areMacrosEnabled() {return MacrosEnabledFlag;}
305 /// \brief Control a flag in the parser that enables or disables macros.
306 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
308 /// \brief Lookup a previously defined macro.
309 /// \param Name Macro name.
310 /// \returns Pointer to macro. NULL if no such macro was defined.
311 const MCAsmMacro* lookupMacro(StringRef Name);
313 /// \brief Define a new macro with the given name and information.
314 void defineMacro(StringRef Name, MCAsmMacro Macro);
316 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
317 void undefineMacro(StringRef Name);
319 /// \brief Are we inside a macro instantiation?
320 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
322 /// \brief Handle entry to macro instantiation.
324 /// \param M The macro.
325 /// \param NameLoc Instantiation location.
326 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
328 /// \brief Handle exit from macro instantiation.
329 void handleMacroExit();
331 /// \brief Extract AsmTokens for a macro argument.
332 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
334 /// \brief Parse all macro arguments for a given macro.
335 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
337 void printMacroInstantiations();
338 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
339 SMRange Range = None) const {
340 ArrayRef<SMRange> Ranges(Range);
341 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
343 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
345 /// \brief Enter the specified file. This returns true on failure.
346 bool enterIncludeFile(const std::string &Filename);
348 /// \brief Process the specified file for the .incbin directive.
349 /// This returns true on failure.
350 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
351 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
353 /// \brief Reset the current lexer position to that given by \p Loc. The
354 /// current token is not set; clients should ensure Lex() is called
357 /// \param InBuffer If not 0, should be the known buffer id that contains the
359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
364 StringRef parseStringToEndOfStatement() override;
366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
368 StringRef parseStringToComma();
370 bool parseAssignment(StringRef Name, bool allow_redef,
371 bool NoDeadStrip = false);
373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
382 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
383 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
385 // Generic (target and platform independent) directive parsing.
387 DK_NO_DIRECTIVE, // Placeholder
388 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
390 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
391 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
392 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
393 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
394 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
395 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
396 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
397 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
398 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
399 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
400 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
401 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
402 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
403 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
404 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
405 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
406 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
407 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
409 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
410 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
411 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
412 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
413 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
414 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
415 DK_MACROS_ON, DK_MACROS_OFF,
416 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
417 DK_SLEB128, DK_ULEB128,
418 DK_ERR, DK_ERROR, DK_WARNING,
422 /// \brief Maps directive name --> DirectiveKind enum, for
423 /// directives parsed by this class.
424 StringMap<DirectiveKind> DirectiveKindMap;
426 // ".ascii", ".asciz", ".string"
427 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
428 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
429 bool parseDirectiveValue(StringRef IDVal,
430 unsigned Size); // ".byte", ".long", ...
431 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
432 bool parseDirectiveRealValue(StringRef IDVal,
433 const fltSemantics &); // ".single", ...
434 bool parseDirectiveFill(); // ".fill"
435 bool parseDirectiveZero(); // ".zero"
436 // ".set", ".equ", ".equiv"
437 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
438 bool parseDirectiveOrg(); // ".org"
439 // ".align{,32}", ".p2align{,w,l}"
440 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
442 // ".file", ".line", ".loc", ".stabs"
443 bool parseDirectiveFile(SMLoc DirectiveLoc);
444 bool parseDirectiveLine();
445 bool parseDirectiveLoc();
446 bool parseDirectiveStabs();
448 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
449 // ".cv_inline_linetable", ".cv_def_range"
450 bool parseDirectiveCVFile();
451 bool parseDirectiveCVFuncId();
452 bool parseDirectiveCVInlineSiteId();
453 bool parseDirectiveCVLoc();
454 bool parseDirectiveCVLinetable();
455 bool parseDirectiveCVInlineLinetable();
456 bool parseDirectiveCVDefRange();
457 bool parseDirectiveCVStringTable();
458 bool parseDirectiveCVFileChecksums();
461 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
462 bool parseDirectiveCFIWindowSave();
463 bool parseDirectiveCFISections();
464 bool parseDirectiveCFIStartProc();
465 bool parseDirectiveCFIEndProc();
466 bool parseDirectiveCFIDefCfaOffset();
467 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
468 bool parseDirectiveCFIAdjustCfaOffset();
469 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
473 bool parseDirectiveCFIRememberState();
474 bool parseDirectiveCFIRestoreState();
475 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIEscape();
478 bool parseDirectiveCFISignalFrame();
479 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
482 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
483 bool parseDirectiveExitMacro(StringRef Directive);
484 bool parseDirectiveEndMacro(StringRef Directive);
485 bool parseDirectiveMacro(SMLoc DirectiveLoc);
486 bool parseDirectiveMacrosOnOff(StringRef Directive);
488 // ".bundle_align_mode"
489 bool parseDirectiveBundleAlignMode();
491 bool parseDirectiveBundleLock();
493 bool parseDirectiveBundleUnlock();
496 bool parseDirectiveSpace(StringRef IDVal);
499 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
500 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
502 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
504 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
505 bool parseDirectiveLEB128(bool Signed);
507 /// \brief Parse a directive like ".globl" which
508 /// accepts a single symbol (which should be a label or an external).
509 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
511 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
513 bool parseDirectiveAbort(); // ".abort"
514 bool parseDirectiveInclude(); // ".include"
515 bool parseDirectiveIncbin(); // ".incbin"
517 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
518 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
519 // ".ifb" or ".ifnb", depending on ExpectBlank.
520 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
521 // ".ifc" or ".ifnc", depending on ExpectEqual.
522 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
523 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
524 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
525 // ".ifdef" or ".ifndef", depending on expect_defined
526 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
527 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
528 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
529 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
530 bool parseEscapedString(std::string &Data) override;
532 const MCExpr *applyModifierToExpr(const MCExpr *E,
533 MCSymbolRefExpr::VariantKind Variant);
535 // Macro-like directives
536 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
537 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
538 raw_svector_ostream &OS);
539 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
540 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
541 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
542 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
544 // "_emit" or "__emit"
545 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
549 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
552 bool parseDirectiveEnd(SMLoc DirectiveLoc);
554 // ".err" or ".error"
555 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
558 bool parseDirectiveWarning(SMLoc DirectiveLoc);
560 void initializeDirectiveKindMap();
563 } // end anonymous namespace
567 extern MCAsmParserExtension *createDarwinAsmParser();
568 extern MCAsmParserExtension *createELFAsmParser();
569 extern MCAsmParserExtension *createCOFFAsmParser();
571 } // end namespace llvm
573 enum { DEFAULT_ADDRSPACE = 0 };
575 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
576 const MCAsmInfo &MAI, unsigned CB = 0)
577 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
578 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
580 // Save the old handler.
581 SavedDiagHandler = SrcMgr.getDiagHandler();
582 SavedDiagContext = SrcMgr.getDiagContext();
583 // Set our own handler which calls the saved handler.
584 SrcMgr.setDiagHandler(DiagHandler, this);
585 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
587 // Initialize the platform / file format parser.
588 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
589 case MCObjectFileInfo::IsCOFF:
590 PlatformParser.reset(createCOFFAsmParser());
592 case MCObjectFileInfo::IsMachO:
593 PlatformParser.reset(createDarwinAsmParser());
596 case MCObjectFileInfo::IsELF:
597 PlatformParser.reset(createELFAsmParser());
599 case MCObjectFileInfo::IsWasm:
600 llvm_unreachable("Wasm parsing not supported yet");
604 PlatformParser->Initialize(*this);
605 initializeDirectiveKindMap();
607 NumOfMacroInstantiations = 0;
610 AsmParser::~AsmParser() {
611 assert((HadError || ActiveMacros.empty()) &&
612 "Unexpected active macro instantiation!");
614 // Restore the saved diagnostics handler and context for use during
616 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
619 void AsmParser::printMacroInstantiations() {
620 // Print the active macro instantiation stack.
621 for (std::vector<MacroInstantiation *>::const_reverse_iterator
622 it = ActiveMacros.rbegin(),
623 ie = ActiveMacros.rend();
625 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
626 "while in macro instantiation");
629 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
630 printPendingErrors();
631 printMessage(L, SourceMgr::DK_Note, Msg, Range);
632 printMacroInstantiations();
635 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
636 if(getTargetParser().getTargetOptions().MCNoWarn)
638 if (getTargetParser().getTargetOptions().MCFatalWarnings)
639 return Error(L, Msg, Range);
640 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
641 printMacroInstantiations();
645 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
647 printMessage(L, SourceMgr::DK_Error, Msg, Range);
648 printMacroInstantiations();
652 bool AsmParser::enterIncludeFile(const std::string &Filename) {
653 std::string IncludedFile;
655 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
660 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
664 /// Process the specified .incbin file by searching for it in the include paths
665 /// then just emitting the byte contents of the file to the streamer. This
666 /// returns true on failure.
667 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
668 const MCExpr *Count, SMLoc Loc) {
669 std::string IncludedFile;
671 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
675 // Pick up the bytes from the file and emit them.
676 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
677 Bytes = Bytes.drop_front(Skip);
680 if (!Count->evaluateAsAbsolute(Res))
681 return Error(Loc, "expected absolute expression");
683 return Warning(Loc, "negative count has no effect");
684 Bytes = Bytes.take_front(Res);
686 getStreamer().EmitBytes(Bytes);
690 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
691 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
692 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
696 const AsmToken &AsmParser::Lex() {
697 if (Lexer.getTok().is(AsmToken::Error))
698 Error(Lexer.getErrLoc(), Lexer.getErr());
700 // if it's a end of statement with a comment in it
701 if (getTok().is(AsmToken::EndOfStatement)) {
702 // if this is a line comment output it.
703 if (getTok().getString().front() != '\n' &&
704 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
705 Out.addExplicitComment(Twine(getTok().getString()));
708 const AsmToken *tok = &Lexer.Lex();
710 // Parse comments here to be deferred until end of next statement.
711 while (tok->is(AsmToken::Comment)) {
712 if (MAI.preserveAsmComments())
713 Out.addExplicitComment(Twine(tok->getString()));
717 if (tok->is(AsmToken::Eof)) {
718 // If this is the end of an included file, pop the parent file off the
720 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
721 if (ParentIncludeLoc != SMLoc()) {
722 jumpToLoc(ParentIncludeLoc);
730 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
731 // Create the initial section, if requested.
732 if (!NoInitialTextSection)
733 Out.InitSections(false);
739 AsmCond StartingCondState = TheCondState;
740 SmallVector<AsmRewrite, 4> AsmStrRewrites;
742 // If we are generating dwarf for assembly source files save the initial text
743 // section and generate a .file directive.
744 if (getContext().getGenDwarfForAssembly()) {
745 MCSection *Sec = getStreamer().getCurrentSectionOnly();
746 if (!Sec->getBeginSymbol()) {
747 MCSymbol *SectionStartSym = getContext().createTempSymbol();
748 getStreamer().EmitLabel(SectionStartSym);
749 Sec->setBeginSymbol(SectionStartSym);
751 bool InsertResult = getContext().addGenDwarfSection(Sec);
752 assert(InsertResult && ".text section should not have debug info yet");
754 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
755 0, StringRef(), getContext().getMainFileName()));
758 // While we have input, parse each statement.
759 while (Lexer.isNot(AsmToken::Eof)) {
760 ParseStatementInfo Info(&AsmStrRewrites);
761 if (!parseStatement(Info, nullptr))
764 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
765 // for printing ErrMsg via Lex() only if no (presumably better) parser error
767 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
771 // parseStatement returned true so may need to emit an error.
772 printPendingErrors();
774 // Skipping to the next line if needed.
775 if (!getLexer().isAtStartOfStatement())
776 eatToEndOfStatement();
779 // All errors should have been emitted.
780 assert(!hasPendingError() && "unexpected error from parseStatement");
782 getTargetParser().flushPendingInstructions(getStreamer());
784 if (TheCondState.TheCond != StartingCondState.TheCond ||
785 TheCondState.Ignore != StartingCondState.Ignore)
786 printError(getTok().getLoc(), "unmatched .ifs or .elses");
787 // Check to see there are no empty DwarfFile slots.
788 const auto &LineTables = getContext().getMCDwarfLineTables();
789 if (!LineTables.empty()) {
791 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
792 if (File.Name.empty() && Index != 0)
793 printError(getTok().getLoc(), "unassigned file number: " +
795 " for .file directives");
800 // Check to see that all assembler local symbols were actually defined.
801 // Targets that don't do subsections via symbols may not want this, though,
802 // so conservatively exclude them. Only do this if we're finalizing, though,
803 // as otherwise we won't necessarilly have seen everything yet.
805 if (MAI.hasSubsectionsViaSymbols()) {
806 for (const auto &TableEntry : getContext().getSymbols()) {
807 MCSymbol *Sym = TableEntry.getValue();
808 // Variable symbols may not be marked as defined, so check those
809 // explicitly. If we know it's a variable, we have a definition for
810 // the purposes of this check.
811 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
812 // FIXME: We would really like to refer back to where the symbol was
813 // first referenced for a source location. We need to add something
814 // to track that. Currently, we just point to the end of the file.
815 printError(getTok().getLoc(), "assembler local symbol '" +
816 Sym->getName() + "' not defined");
820 // Temporary symbols like the ones for directional jumps don't go in the
821 // symbol table. They also need to be diagnosed in all (final) cases.
822 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
823 if (std::get<2>(LocSym)->isUndefined()) {
824 // Reset the state of any "# line file" directives we've seen to the
825 // context as it was at the diagnostic site.
826 CppHashInfo = std::get<1>(LocSym);
827 printError(std::get<0>(LocSym), "directional label undefined");
832 // Finalize the output stream if there are no errors and if the client wants
834 if (!HadError && !NoFinalize)
837 return HadError || getContext().hadError();
840 bool AsmParser::checkForValidSection() {
841 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
842 Out.InitSections(false);
843 return Error(getTok().getLoc(),
844 "expected section directive before assembly directive");
849 /// \brief Throw away the rest of the line for testing purposes.
850 void AsmParser::eatToEndOfStatement() {
851 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
855 if (Lexer.is(AsmToken::EndOfStatement))
859 StringRef AsmParser::parseStringToEndOfStatement() {
860 const char *Start = getTok().getLoc().getPointer();
862 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
865 const char *End = getTok().getLoc().getPointer();
866 return StringRef(Start, End - Start);
869 StringRef AsmParser::parseStringToComma() {
870 const char *Start = getTok().getLoc().getPointer();
872 while (Lexer.isNot(AsmToken::EndOfStatement) &&
873 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
876 const char *End = getTok().getLoc().getPointer();
877 return StringRef(Start, End - Start);
880 /// \brief Parse a paren expression and return it.
881 /// NOTE: This assumes the leading '(' has already been consumed.
883 /// parenexpr ::= expr)
885 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
886 if (parseExpression(Res))
888 if (Lexer.isNot(AsmToken::RParen))
889 return TokError("expected ')' in parentheses expression");
890 EndLoc = Lexer.getTok().getEndLoc();
895 /// \brief Parse a bracket expression and return it.
896 /// NOTE: This assumes the leading '[' has already been consumed.
898 /// bracketexpr ::= expr]
900 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
901 if (parseExpression(Res))
903 EndLoc = getTok().getEndLoc();
904 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
909 /// \brief Parse a primary expression and return it.
910 /// primaryexpr ::= (parenexpr
911 /// primaryexpr ::= symbol
912 /// primaryexpr ::= number
913 /// primaryexpr ::= '.'
914 /// primaryexpr ::= ~,+,- primaryexpr
915 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
916 SMLoc FirstTokenLoc = getLexer().getLoc();
917 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
918 switch (FirstTokenKind) {
920 return TokError("unknown token in expression");
921 // If we have an error assume that we've already handled it.
922 case AsmToken::Error:
924 case AsmToken::Exclaim:
925 Lex(); // Eat the operator.
926 if (parsePrimaryExpr(Res, EndLoc))
928 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
930 case AsmToken::Dollar:
932 case AsmToken::String:
933 case AsmToken::Identifier: {
934 StringRef Identifier;
935 if (parseIdentifier(Identifier)) {
936 // We may have failed but $ may be a valid token.
937 if (getTok().is(AsmToken::Dollar)) {
938 if (Lexer.getMAI().getDollarIsPC()) {
940 // This is a '$' reference, which references the current PC. Emit a
941 // temporary label to the streamer and refer to it.
942 MCSymbol *Sym = Ctx.createTempSymbol();
944 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
946 EndLoc = FirstTokenLoc;
949 return Error(FirstTokenLoc, "invalid token in expression");
952 // Parse symbol variant
953 std::pair<StringRef, StringRef> Split;
954 if (!MAI.useParensForSymbolVariant()) {
955 if (FirstTokenKind == AsmToken::String) {
956 if (Lexer.is(AsmToken::At)) {
958 SMLoc AtLoc = getLexer().getLoc();
960 if (parseIdentifier(VName))
961 return Error(AtLoc, "expected symbol variant after '@'");
963 Split = std::make_pair(Identifier, VName);
966 Split = Identifier.split('@');
968 } else if (Lexer.is(AsmToken::LParen)) {
971 parseIdentifier(VName);
973 if (parseToken(AsmToken::RParen,
974 "unexpected token in variant, expected ')'"))
976 Split = std::make_pair(Identifier, VName);
979 EndLoc = SMLoc::getFromPointer(Identifier.end());
981 // This is a symbol reference.
982 StringRef SymbolName = Identifier;
983 if (SymbolName.empty())
986 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
988 // Lookup the symbol variant if used.
989 if (!Split.second.empty()) {
990 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
991 if (Variant != MCSymbolRefExpr::VK_Invalid) {
992 SymbolName = Split.first;
993 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
994 Variant = MCSymbolRefExpr::VK_None;
996 return Error(SMLoc::getFromPointer(Split.second.begin()),
997 "invalid variant '" + Split.second + "'");
1001 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
1003 // If this is an absolute variable reference, substitute it now to preserve
1004 // semantics in the face of reassignment.
1005 if (Sym->isVariable() &&
1006 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
1008 return Error(EndLoc, "unexpected modifier on variable reference");
1010 Res = Sym->getVariableValue(/*SetUsed*/ false);
1014 // Otherwise create a symbol ref.
1015 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1018 case AsmToken::BigNum:
1019 return TokError("literal value out of range for directive");
1020 case AsmToken::Integer: {
1021 SMLoc Loc = getTok().getLoc();
1022 int64_t IntVal = getTok().getIntVal();
1023 Res = MCConstantExpr::create(IntVal, getContext());
1024 EndLoc = Lexer.getTok().getEndLoc();
1025 Lex(); // Eat token.
1026 // Look for 'b' or 'f' following an Integer as a directional label
1027 if (Lexer.getKind() == AsmToken::Identifier) {
1028 StringRef IDVal = getTok().getString();
1029 // Lookup the symbol variant if used.
1030 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1031 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1032 if (Split.first.size() != IDVal.size()) {
1033 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1034 if (Variant == MCSymbolRefExpr::VK_Invalid)
1035 return TokError("invalid variant '" + Split.second + "'");
1036 IDVal = Split.first;
1038 if (IDVal == "f" || IDVal == "b") {
1040 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1041 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1042 if (IDVal == "b" && Sym->isUndefined())
1043 return Error(Loc, "directional label undefined");
1044 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1045 EndLoc = Lexer.getTok().getEndLoc();
1046 Lex(); // Eat identifier.
1051 case AsmToken::Real: {
1052 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1053 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1054 Res = MCConstantExpr::create(IntVal, getContext());
1055 EndLoc = Lexer.getTok().getEndLoc();
1056 Lex(); // Eat token.
1059 case AsmToken::Dot: {
1060 // This is a '.' reference, which references the current PC. Emit a
1061 // temporary label to the streamer and refer to it.
1062 MCSymbol *Sym = Ctx.createTempSymbol();
1064 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1065 EndLoc = Lexer.getTok().getEndLoc();
1066 Lex(); // Eat identifier.
1069 case AsmToken::LParen:
1070 Lex(); // Eat the '('.
1071 return parseParenExpr(Res, EndLoc);
1072 case AsmToken::LBrac:
1073 if (!PlatformParser->HasBracketExpressions())
1074 return TokError("brackets expression not supported on this target");
1075 Lex(); // Eat the '['.
1076 return parseBracketExpr(Res, EndLoc);
1077 case AsmToken::Minus:
1078 Lex(); // Eat the operator.
1079 if (parsePrimaryExpr(Res, EndLoc))
1081 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1083 case AsmToken::Plus:
1084 Lex(); // Eat the operator.
1085 if (parsePrimaryExpr(Res, EndLoc))
1087 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1089 case AsmToken::Tilde:
1090 Lex(); // Eat the operator.
1091 if (parsePrimaryExpr(Res, EndLoc))
1093 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1095 // MIPS unary expression operators. The lexer won't generate these tokens if
1096 // MCAsmInfo::HasMipsExpressions is false for the target.
1097 case AsmToken::PercentCall16:
1098 case AsmToken::PercentCall_Hi:
1099 case AsmToken::PercentCall_Lo:
1100 case AsmToken::PercentDtprel_Hi:
1101 case AsmToken::PercentDtprel_Lo:
1102 case AsmToken::PercentGot:
1103 case AsmToken::PercentGot_Disp:
1104 case AsmToken::PercentGot_Hi:
1105 case AsmToken::PercentGot_Lo:
1106 case AsmToken::PercentGot_Ofst:
1107 case AsmToken::PercentGot_Page:
1108 case AsmToken::PercentGottprel:
1109 case AsmToken::PercentGp_Rel:
1110 case AsmToken::PercentHi:
1111 case AsmToken::PercentHigher:
1112 case AsmToken::PercentHighest:
1113 case AsmToken::PercentLo:
1114 case AsmToken::PercentNeg:
1115 case AsmToken::PercentPcrel_Hi:
1116 case AsmToken::PercentPcrel_Lo:
1117 case AsmToken::PercentTlsgd:
1118 case AsmToken::PercentTlsldm:
1119 case AsmToken::PercentTprel_Hi:
1120 case AsmToken::PercentTprel_Lo:
1121 Lex(); // Eat the operator.
1122 if (Lexer.isNot(AsmToken::LParen))
1123 return TokError("expected '(' after operator");
1124 Lex(); // Eat the operator.
1125 if (parseExpression(Res, EndLoc))
1127 if (Lexer.isNot(AsmToken::RParen))
1128 return TokError("expected ')'");
1129 Lex(); // Eat the operator.
1130 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1135 bool AsmParser::parseExpression(const MCExpr *&Res) {
1137 return parseExpression(Res, EndLoc);
1141 AsmParser::applyModifierToExpr(const MCExpr *E,
1142 MCSymbolRefExpr::VariantKind Variant) {
1143 // Ask the target implementation about this expression first.
1144 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1147 // Recurse over the given expression, rebuilding it to apply the given variant
1148 // if there is exactly one symbol.
1149 switch (E->getKind()) {
1150 case MCExpr::Target:
1151 case MCExpr::Constant:
1154 case MCExpr::SymbolRef: {
1155 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1157 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1158 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1159 "' (already modified)");
1163 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1166 case MCExpr::Unary: {
1167 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1168 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1171 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1174 case MCExpr::Binary: {
1175 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1176 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1177 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1187 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1191 llvm_unreachable("Invalid expression kind!");
1194 /// \brief Parse an expression and return it.
1196 /// expr ::= expr &&,|| expr -> lowest.
1197 /// expr ::= expr |,^,&,! expr
1198 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1199 /// expr ::= expr <<,>> expr
1200 /// expr ::= expr +,- expr
1201 /// expr ::= expr *,/,% expr -> highest.
1202 /// expr ::= primaryexpr
1204 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1205 // Parse the expression.
1207 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1210 // As a special case, we support 'a op b @ modifier' by rewriting the
1211 // expression to include the modifier. This is inefficient, but in general we
1212 // expect users to use 'a@modifier op b'.
1213 if (Lexer.getKind() == AsmToken::At) {
1216 if (Lexer.isNot(AsmToken::Identifier))
1217 return TokError("unexpected symbol modifier following '@'");
1219 MCSymbolRefExpr::VariantKind Variant =
1220 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1221 if (Variant == MCSymbolRefExpr::VK_Invalid)
1222 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1224 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1226 return TokError("invalid modifier '" + getTok().getIdentifier() +
1227 "' (no symbols present)");
1234 // Try to constant fold it up front, if possible.
1236 if (Res->evaluateAsAbsolute(Value))
1237 Res = MCConstantExpr::create(Value, getContext());
1242 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1244 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1247 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1249 if (parseParenExpr(Res, EndLoc))
1252 for (; ParenDepth > 0; --ParenDepth) {
1253 if (parseBinOpRHS(1, Res, EndLoc))
1256 // We don't Lex() the last RParen.
1257 // This is the same behavior as parseParenExpression().
1258 if (ParenDepth - 1 > 0) {
1259 EndLoc = getTok().getEndLoc();
1260 if (parseToken(AsmToken::RParen,
1261 "expected ')' in parentheses expression"))
1268 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1271 SMLoc StartLoc = Lexer.getLoc();
1272 if (parseExpression(Expr))
1275 if (!Expr->evaluateAsAbsolute(Res))
1276 return Error(StartLoc, "expected absolute expression");
1281 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1282 MCBinaryExpr::Opcode &Kind,
1283 bool ShouldUseLogicalShr) {
1286 return 0; // not a binop.
1288 // Lowest Precedence: &&, ||
1289 case AsmToken::AmpAmp:
1290 Kind = MCBinaryExpr::LAnd;
1292 case AsmToken::PipePipe:
1293 Kind = MCBinaryExpr::LOr;
1296 // Low Precedence: |, &, ^
1298 // FIXME: gas seems to support '!' as an infix operator?
1299 case AsmToken::Pipe:
1300 Kind = MCBinaryExpr::Or;
1302 case AsmToken::Caret:
1303 Kind = MCBinaryExpr::Xor;
1306 Kind = MCBinaryExpr::And;
1309 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1310 case AsmToken::EqualEqual:
1311 Kind = MCBinaryExpr::EQ;
1313 case AsmToken::ExclaimEqual:
1314 case AsmToken::LessGreater:
1315 Kind = MCBinaryExpr::NE;
1317 case AsmToken::Less:
1318 Kind = MCBinaryExpr::LT;
1320 case AsmToken::LessEqual:
1321 Kind = MCBinaryExpr::LTE;
1323 case AsmToken::Greater:
1324 Kind = MCBinaryExpr::GT;
1326 case AsmToken::GreaterEqual:
1327 Kind = MCBinaryExpr::GTE;
1330 // Intermediate Precedence: <<, >>
1331 case AsmToken::LessLess:
1332 Kind = MCBinaryExpr::Shl;
1334 case AsmToken::GreaterGreater:
1335 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1338 // High Intermediate Precedence: +, -
1339 case AsmToken::Plus:
1340 Kind = MCBinaryExpr::Add;
1342 case AsmToken::Minus:
1343 Kind = MCBinaryExpr::Sub;
1346 // Highest Precedence: *, /, %
1347 case AsmToken::Star:
1348 Kind = MCBinaryExpr::Mul;
1350 case AsmToken::Slash:
1351 Kind = MCBinaryExpr::Div;
1353 case AsmToken::Percent:
1354 Kind = MCBinaryExpr::Mod;
1359 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1360 MCBinaryExpr::Opcode &Kind,
1361 bool ShouldUseLogicalShr) {
1364 return 0; // not a binop.
1366 // Lowest Precedence: &&, ||
1367 case AsmToken::AmpAmp:
1368 Kind = MCBinaryExpr::LAnd;
1370 case AsmToken::PipePipe:
1371 Kind = MCBinaryExpr::LOr;
1374 // Low Precedence: ==, !=, <>, <, <=, >, >=
1375 case AsmToken::EqualEqual:
1376 Kind = MCBinaryExpr::EQ;
1378 case AsmToken::ExclaimEqual:
1379 case AsmToken::LessGreater:
1380 Kind = MCBinaryExpr::NE;
1382 case AsmToken::Less:
1383 Kind = MCBinaryExpr::LT;
1385 case AsmToken::LessEqual:
1386 Kind = MCBinaryExpr::LTE;
1388 case AsmToken::Greater:
1389 Kind = MCBinaryExpr::GT;
1391 case AsmToken::GreaterEqual:
1392 Kind = MCBinaryExpr::GTE;
1395 // Low Intermediate Precedence: +, -
1396 case AsmToken::Plus:
1397 Kind = MCBinaryExpr::Add;
1399 case AsmToken::Minus:
1400 Kind = MCBinaryExpr::Sub;
1403 // High Intermediate Precedence: |, &, ^
1405 // FIXME: gas seems to support '!' as an infix operator?
1406 case AsmToken::Pipe:
1407 Kind = MCBinaryExpr::Or;
1409 case AsmToken::Caret:
1410 Kind = MCBinaryExpr::Xor;
1413 Kind = MCBinaryExpr::And;
1416 // Highest Precedence: *, /, %, <<, >>
1417 case AsmToken::Star:
1418 Kind = MCBinaryExpr::Mul;
1420 case AsmToken::Slash:
1421 Kind = MCBinaryExpr::Div;
1423 case AsmToken::Percent:
1424 Kind = MCBinaryExpr::Mod;
1426 case AsmToken::LessLess:
1427 Kind = MCBinaryExpr::Shl;
1429 case AsmToken::GreaterGreater:
1430 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1435 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1436 MCBinaryExpr::Opcode &Kind) {
1437 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1438 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1439 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1442 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1443 /// Res contains the LHS of the expression on input.
1444 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1446 SMLoc StartLoc = Lexer.getLoc();
1448 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1449 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1451 // If the next token is lower precedence than we are allowed to eat, return
1452 // successfully with what we ate already.
1453 if (TokPrec < Precedence)
1458 // Eat the next primary expression.
1460 if (parsePrimaryExpr(RHS, EndLoc))
1463 // If BinOp binds less tightly with RHS than the operator after RHS, let
1464 // the pending operator take RHS as its LHS.
1465 MCBinaryExpr::Opcode Dummy;
1466 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1467 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1470 // Merge LHS and RHS according to operator.
1471 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1476 /// ::= EndOfStatement
1477 /// ::= Label* Directive ...Operands... EndOfStatement
1478 /// ::= Label* Identifier OperandList* EndOfStatement
1479 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1480 MCAsmParserSemaCallback *SI) {
1481 assert(!hasPendingError() && "parseStatement started with pending error");
1482 // Eat initial spaces and comments
1483 while (Lexer.is(AsmToken::Space))
1485 if (Lexer.is(AsmToken::EndOfStatement)) {
1486 // if this is a line comment we can drop it safely
1487 if (getTok().getString().front() == '\r' ||
1488 getTok().getString().front() == '\n')
1493 if (Lexer.is(AsmToken::Hash)) {
1494 // Seeing a hash here means that it was an end-of-line comment in
1495 // an asm syntax where hash's are not comment and the previous
1496 // statement parser did not check the end of statement. Relex as
1498 StringRef CommentStr = parseStringToEndOfStatement();
1500 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1503 // Statements always start with an identifier.
1504 AsmToken ID = getTok();
1505 SMLoc IDLoc = ID.getLoc();
1507 int64_t LocalLabelVal = -1;
1508 if (Lexer.is(AsmToken::HashDirective))
1509 return parseCppHashLineFilenameComment(IDLoc);
1510 // Allow an integer followed by a ':' as a directional local label.
1511 if (Lexer.is(AsmToken::Integer)) {
1512 LocalLabelVal = getTok().getIntVal();
1513 if (LocalLabelVal < 0) {
1514 if (!TheCondState.Ignore) {
1515 Lex(); // always eat a token
1516 return Error(IDLoc, "unexpected token at start of statement");
1520 IDVal = getTok().getString();
1521 Lex(); // Consume the integer token to be used as an identifier token.
1522 if (Lexer.getKind() != AsmToken::Colon) {
1523 if (!TheCondState.Ignore) {
1524 Lex(); // always eat a token
1525 return Error(IDLoc, "unexpected token at start of statement");
1529 } else if (Lexer.is(AsmToken::Dot)) {
1530 // Treat '.' as a valid identifier in this context.
1533 } else if (Lexer.is(AsmToken::LCurly)) {
1534 // Treat '{' as a valid identifier in this context.
1538 } else if (Lexer.is(AsmToken::RCurly)) {
1539 // Treat '}' as a valid identifier in this context.
1542 } else if (parseIdentifier(IDVal)) {
1543 if (!TheCondState.Ignore) {
1544 Lex(); // always eat a token
1545 return Error(IDLoc, "unexpected token at start of statement");
1550 // Handle conditional assembly here before checking for skipping. We
1551 // have to do this so that .endif isn't skipped in a ".if 0" block for
1553 StringMap<DirectiveKind>::const_iterator DirKindIt =
1554 DirectiveKindMap.find(IDVal);
1555 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1557 : DirKindIt->getValue();
1568 return parseDirectiveIf(IDLoc, DirKind);
1570 return parseDirectiveIfb(IDLoc, true);
1572 return parseDirectiveIfb(IDLoc, false);
1574 return parseDirectiveIfc(IDLoc, true);
1576 return parseDirectiveIfeqs(IDLoc, true);
1578 return parseDirectiveIfc(IDLoc, false);
1580 return parseDirectiveIfeqs(IDLoc, false);
1582 return parseDirectiveIfdef(IDLoc, true);
1585 return parseDirectiveIfdef(IDLoc, false);
1587 return parseDirectiveElseIf(IDLoc);
1589 return parseDirectiveElse(IDLoc);
1591 return parseDirectiveEndIf(IDLoc);
1594 // Ignore the statement if in the middle of inactive conditional
1596 if (TheCondState.Ignore) {
1597 eatToEndOfStatement();
1601 // FIXME: Recurse on local labels?
1603 // See what kind of statement we have.
1604 switch (Lexer.getKind()) {
1605 case AsmToken::Colon: {
1606 if (!getTargetParser().isLabel(ID))
1608 if (checkForValidSection())
1611 // identifier ':' -> Label.
1614 // Diagnose attempt to use '.' as a label.
1616 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1618 // Diagnose attempt to use a variable as a label.
1620 // FIXME: Diagnostics. Note the location of the definition as a label.
1621 // FIXME: This doesn't diagnose assignment to a symbol which has been
1622 // implicitly marked as external.
1624 if (LocalLabelVal == -1) {
1625 if (ParsingInlineAsm && SI) {
1626 StringRef RewrittenLabel =
1627 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1628 assert(!RewrittenLabel.empty() &&
1629 "We should have an internal name here.");
1630 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1632 IDVal = RewrittenLabel;
1634 Sym = getContext().getOrCreateSymbol(IDVal);
1636 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1637 // End of Labels should be treated as end of line for lexing
1638 // purposes but that information is not available to the Lexer who
1639 // does not understand Labels. This may cause us to see a Hash
1640 // here instead of a preprocessor line comment.
1641 if (getTok().is(AsmToken::Hash)) {
1642 StringRef CommentStr = parseStringToEndOfStatement();
1644 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1647 // Consume any end of statement token, if present, to avoid spurious
1648 // AddBlankLine calls().
1649 if (getTok().is(AsmToken::EndOfStatement)) {
1654 if (!getTargetParser().isParsingInlineAsm())
1655 Out.EmitLabel(Sym, IDLoc);
1657 // If we are generating dwarf for assembly source files then gather the
1658 // info to make a dwarf label entry for this label if needed.
1659 if (getContext().getGenDwarfForAssembly())
1660 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1663 getTargetParser().onLabelParsed(Sym);
1668 case AsmToken::Equal:
1669 if (!getTargetParser().equalIsAsmAssignment())
1671 // identifier '=' ... -> assignment statement
1674 return parseAssignment(IDVal, true);
1676 default: // Normal instruction or directive.
1680 // If macros are enabled, check to see if this is a macro instantiation.
1681 if (areMacrosEnabled())
1682 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1683 return handleMacroEntry(M, IDLoc);
1686 // Otherwise, we have a normal instruction or directive.
1688 // Directives start with "."
1689 if (IDVal[0] == '.' && IDVal != ".") {
1690 // There are several entities interested in parsing directives:
1692 // 1. The target-specific assembly parser. Some directives are target
1693 // specific or may potentially behave differently on certain targets.
1694 // 2. Asm parser extensions. For example, platform-specific parsers
1695 // (like the ELF parser) register themselves as extensions.
1696 // 3. The generic directive parser implemented by this class. These are
1697 // all the directives that behave in a target and platform independent
1698 // manner, or at least have a default behavior that's shared between
1699 // all targets and platforms.
1701 getTargetParser().flushPendingInstructions(getStreamer());
1703 SMLoc StartTokLoc = getTok().getLoc();
1704 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1706 if (hasPendingError())
1708 // Currently the return value should be true if we are
1709 // uninterested but as this is at odds with the standard parsing
1710 // convention (return true = error) we have instances of a parsed
1711 // directive that fails returning true as an error. Catch these
1712 // cases as best as possible errors here.
1713 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1715 // Return if we did some parsing or believe we succeeded.
1716 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1719 // Next, check the extension directive map to see if any extension has
1720 // registered itself to parse this directive.
1721 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1722 ExtensionDirectiveMap.lookup(IDVal);
1724 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1726 // Finally, if no one else is interested in this directive, it must be
1727 // generic and familiar to this class.
1733 return parseDirectiveSet(IDVal, true);
1735 return parseDirectiveSet(IDVal, false);
1737 return parseDirectiveAscii(IDVal, false);
1740 return parseDirectiveAscii(IDVal, true);
1743 return parseDirectiveValue(IDVal, 1);
1749 return parseDirectiveValue(IDVal, 2);
1754 return parseDirectiveValue(IDVal, 4);
1757 return parseDirectiveValue(IDVal, 8);
1759 return parseDirectiveValue(
1760 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1762 return parseDirectiveOctaValue(IDVal);
1766 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1769 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1771 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1772 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1775 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1776 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1783 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1789 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1791 return parseDirectiveOrg();
1793 return parseDirectiveFill();
1795 return parseDirectiveZero();
1797 eatToEndOfStatement(); // .extern is the default, ignore it.
1801 return parseDirectiveSymbolAttribute(MCSA_Global);
1802 case DK_LAZY_REFERENCE:
1803 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1804 case DK_NO_DEAD_STRIP:
1805 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1806 case DK_SYMBOL_RESOLVER:
1807 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1808 case DK_PRIVATE_EXTERN:
1809 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1811 return parseDirectiveSymbolAttribute(MCSA_Reference);
1812 case DK_WEAK_DEFINITION:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1814 case DK_WEAK_REFERENCE:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1816 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1817 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1820 return parseDirectiveComm(/*IsLocal=*/false);
1822 return parseDirectiveComm(/*IsLocal=*/true);
1824 return parseDirectiveAbort();
1826 return parseDirectiveInclude();
1828 return parseDirectiveIncbin();
1831 return TokError(Twine(IDVal) +
1832 " not currently supported for this target");
1834 return parseDirectiveRept(IDLoc, IDVal);
1836 return parseDirectiveIrp(IDLoc);
1838 return parseDirectiveIrpc(IDLoc);
1840 return parseDirectiveEndr(IDLoc);
1841 case DK_BUNDLE_ALIGN_MODE:
1842 return parseDirectiveBundleAlignMode();
1843 case DK_BUNDLE_LOCK:
1844 return parseDirectiveBundleLock();
1845 case DK_BUNDLE_UNLOCK:
1846 return parseDirectiveBundleUnlock();
1848 return parseDirectiveLEB128(true);
1850 return parseDirectiveLEB128(false);
1853 return parseDirectiveSpace(IDVal);
1855 return parseDirectiveFile(IDLoc);
1857 return parseDirectiveLine();
1859 return parseDirectiveLoc();
1861 return parseDirectiveStabs();
1863 return parseDirectiveCVFile();
1865 return parseDirectiveCVFuncId();
1866 case DK_CV_INLINE_SITE_ID:
1867 return parseDirectiveCVInlineSiteId();
1869 return parseDirectiveCVLoc();
1870 case DK_CV_LINETABLE:
1871 return parseDirectiveCVLinetable();
1872 case DK_CV_INLINE_LINETABLE:
1873 return parseDirectiveCVInlineLinetable();
1874 case DK_CV_DEF_RANGE:
1875 return parseDirectiveCVDefRange();
1876 case DK_CV_STRINGTABLE:
1877 return parseDirectiveCVStringTable();
1878 case DK_CV_FILECHECKSUMS:
1879 return parseDirectiveCVFileChecksums();
1880 case DK_CFI_SECTIONS:
1881 return parseDirectiveCFISections();
1882 case DK_CFI_STARTPROC:
1883 return parseDirectiveCFIStartProc();
1884 case DK_CFI_ENDPROC:
1885 return parseDirectiveCFIEndProc();
1886 case DK_CFI_DEF_CFA:
1887 return parseDirectiveCFIDefCfa(IDLoc);
1888 case DK_CFI_DEF_CFA_OFFSET:
1889 return parseDirectiveCFIDefCfaOffset();
1890 case DK_CFI_ADJUST_CFA_OFFSET:
1891 return parseDirectiveCFIAdjustCfaOffset();
1892 case DK_CFI_DEF_CFA_REGISTER:
1893 return parseDirectiveCFIDefCfaRegister(IDLoc);
1895 return parseDirectiveCFIOffset(IDLoc);
1896 case DK_CFI_REL_OFFSET:
1897 return parseDirectiveCFIRelOffset(IDLoc);
1898 case DK_CFI_PERSONALITY:
1899 return parseDirectiveCFIPersonalityOrLsda(true);
1901 return parseDirectiveCFIPersonalityOrLsda(false);
1902 case DK_CFI_REMEMBER_STATE:
1903 return parseDirectiveCFIRememberState();
1904 case DK_CFI_RESTORE_STATE:
1905 return parseDirectiveCFIRestoreState();
1906 case DK_CFI_SAME_VALUE:
1907 return parseDirectiveCFISameValue(IDLoc);
1908 case DK_CFI_RESTORE:
1909 return parseDirectiveCFIRestore(IDLoc);
1911 return parseDirectiveCFIEscape();
1912 case DK_CFI_SIGNAL_FRAME:
1913 return parseDirectiveCFISignalFrame();
1914 case DK_CFI_UNDEFINED:
1915 return parseDirectiveCFIUndefined(IDLoc);
1916 case DK_CFI_REGISTER:
1917 return parseDirectiveCFIRegister(IDLoc);
1918 case DK_CFI_WINDOW_SAVE:
1919 return parseDirectiveCFIWindowSave();
1922 return parseDirectiveMacrosOnOff(IDVal);
1924 return parseDirectiveMacro(IDLoc);
1926 return parseDirectiveExitMacro(IDVal);
1929 return parseDirectiveEndMacro(IDVal);
1931 return parseDirectivePurgeMacro(IDLoc);
1933 return parseDirectiveEnd(IDLoc);
1935 return parseDirectiveError(IDLoc, false);
1937 return parseDirectiveError(IDLoc, true);
1939 return parseDirectiveWarning(IDLoc);
1941 return parseDirectiveReloc(IDLoc);
1944 return parseDirectiveDCB(IDVal, 2);
1946 return parseDirectiveDCB(IDVal, 1);
1948 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
1950 return parseDirectiveDCB(IDVal, 4);
1952 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
1955 return TokError(Twine(IDVal) +
1956 " not currently supported for this target");
1959 return parseDirectiveDS(IDVal, 2);
1961 return parseDirectiveDS(IDVal, 1);
1963 return parseDirectiveDS(IDVal, 8);
1966 return parseDirectiveDS(IDVal, 4);
1969 return parseDirectiveDS(IDVal, 12);
1972 return Error(IDLoc, "unknown directive");
1975 // __asm _emit or __asm __emit
1976 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1977 IDVal == "_EMIT" || IDVal == "__EMIT"))
1978 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1981 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1982 return parseDirectiveMSAlign(IDLoc, Info);
1984 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
1985 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1986 if (checkForValidSection())
1989 // Canonicalize the opcode to lower case.
1990 std::string OpcodeStr = IDVal.lower();
1991 ParseInstructionInfo IInfo(Info.AsmRewrites);
1992 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1993 Info.ParsedOperands);
1994 Info.ParseError = ParseHadError;
1996 // Dump the parsed representation, if requested.
1997 if (getShowParsedOperands()) {
1998 SmallString<256> Str;
1999 raw_svector_ostream OS(Str);
2000 OS << "parsed instruction: [";
2001 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2004 Info.ParsedOperands[i]->print(OS);
2008 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2011 // Fail even if ParseInstruction erroneously returns false.
2012 if (hasPendingError() || ParseHadError)
2015 // If we are generating dwarf for the current section then generate a .loc
2016 // directive for the instruction.
2017 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
2018 getContext().getGenDwarfSectionSyms().count(
2019 getStreamer().getCurrentSectionOnly())) {
2021 if (ActiveMacros.empty())
2022 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2024 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2025 ActiveMacros.front()->ExitBuffer);
2027 // If we previously parsed a cpp hash file line comment then make sure the
2028 // current Dwarf File is for the CppHashFilename if not then emit the
2029 // Dwarf File table for it and adjust the line number for the .loc.
2030 if (!CppHashInfo.Filename.empty()) {
2031 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2032 0, StringRef(), CppHashInfo.Filename);
2033 getContext().setGenDwarfFileNumber(FileNumber);
2035 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2036 // cache with the different Loc from the call above we save the last
2037 // info we queried here with SrcMgr.FindLineNumber().
2038 unsigned CppHashLocLineNo;
2039 if (LastQueryIDLoc == CppHashInfo.Loc &&
2040 LastQueryBuffer == CppHashInfo.Buf)
2041 CppHashLocLineNo = LastQueryLine;
2044 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2045 LastQueryLine = CppHashLocLineNo;
2046 LastQueryIDLoc = CppHashInfo.Loc;
2047 LastQueryBuffer = CppHashInfo.Buf;
2049 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2052 getStreamer().EmitDwarfLocDirective(
2053 getContext().getGenDwarfFileNumber(), Line, 0,
2054 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2058 // If parsing succeeded, match the instruction.
2059 if (!ParseHadError) {
2061 if (getTargetParser().MatchAndEmitInstruction(
2062 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2063 getTargetParser().isParsingInlineAsm()))
2069 // Parse and erase curly braces marking block start/end
2071 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2072 // Identify curly brace marking block start/end
2073 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2076 SMLoc StartLoc = Lexer.getLoc();
2077 Lex(); // Eat the brace
2078 if (Lexer.is(AsmToken::EndOfStatement))
2079 Lex(); // Eat EndOfStatement following the brace
2081 // Erase the block start/end brace from the output asm string
2082 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2083 StartLoc.getPointer());
2087 /// parseCppHashLineFilenameComment as this:
2088 /// ::= # number "filename"
2089 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2090 Lex(); // Eat the hash token.
2091 // Lexer only ever emits HashDirective if it fully formed if it's
2092 // done the checking already so this is an internal error.
2093 assert(getTok().is(AsmToken::Integer) &&
2094 "Lexing Cpp line comment: Expected Integer");
2095 int64_t LineNumber = getTok().getIntVal();
2097 assert(getTok().is(AsmToken::String) &&
2098 "Lexing Cpp line comment: Expected String");
2099 StringRef Filename = getTok().getString();
2102 // Get rid of the enclosing quotes.
2103 Filename = Filename.substr(1, Filename.size() - 2);
2105 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2106 CppHashInfo.Loc = L;
2107 CppHashInfo.Filename = Filename;
2108 CppHashInfo.LineNumber = LineNumber;
2109 CppHashInfo.Buf = CurBuffer;
2113 /// \brief will use the last parsed cpp hash line filename comment
2114 /// for the Filename and LineNo if any in the diagnostic.
2115 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2116 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2117 raw_ostream &OS = errs();
2119 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2120 SMLoc DiagLoc = Diag.getLoc();
2121 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2122 unsigned CppHashBuf =
2123 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2125 // Like SourceMgr::printMessage() we need to print the include stack if any
2126 // before printing the message.
2127 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2128 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2129 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2130 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2131 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2134 // If we have not parsed a cpp hash line filename comment or the source
2135 // manager changed or buffer changed (like in a nested include) then just
2136 // print the normal diagnostic using its Filename and LineNo.
2137 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2138 DiagBuf != CppHashBuf) {
2139 if (Parser->SavedDiagHandler)
2140 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2142 Diag.print(nullptr, OS);
2146 // Use the CppHashFilename and calculate a line number based on the
2147 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2148 // for the diagnostic.
2149 const std::string &Filename = Parser->CppHashInfo.Filename;
2151 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2152 int CppHashLocLineNo =
2153 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2155 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2157 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2158 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2159 Diag.getLineContents(), Diag.getRanges());
2161 if (Parser->SavedDiagHandler)
2162 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2164 NewDiag.print(nullptr, OS);
2167 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2168 // difference being that that function accepts '@' as part of identifiers and
2169 // we can't do that. AsmLexer.cpp should probably be changed to handle
2170 // '@' as a special case when needed.
2171 static bool isIdentifierChar(char c) {
2172 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2176 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2177 ArrayRef<MCAsmMacroParameter> Parameters,
2178 ArrayRef<MCAsmMacroArgument> A,
2179 bool EnableAtPseudoVariable, SMLoc L) {
2180 unsigned NParameters = Parameters.size();
2181 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2182 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2183 return Error(L, "Wrong number of arguments");
2185 // A macro without parameters is handled differently on Darwin:
2186 // gas accepts no arguments and does no substitutions
2187 while (!Body.empty()) {
2188 // Scan for the next substitution.
2189 std::size_t End = Body.size(), Pos = 0;
2190 for (; Pos != End; ++Pos) {
2191 // Check for a substitution or escape.
2192 if (IsDarwin && !NParameters) {
2193 // This macro has no parameters, look for $0, $1, etc.
2194 if (Body[Pos] != '$' || Pos + 1 == End)
2197 char Next = Body[Pos + 1];
2198 if (Next == '$' || Next == 'n' ||
2199 isdigit(static_cast<unsigned char>(Next)))
2202 // This macro has parameters, look for \foo, \bar, etc.
2203 if (Body[Pos] == '\\' && Pos + 1 != End)
2209 OS << Body.slice(0, Pos);
2211 // Check if we reached the end.
2215 if (IsDarwin && !NParameters) {
2216 switch (Body[Pos + 1]) {
2222 // $n => number of arguments
2227 // $[0-9] => argument
2229 // Missing arguments are ignored.
2230 unsigned Index = Body[Pos + 1] - '0';
2231 if (Index >= A.size())
2234 // Otherwise substitute with the token values, with spaces eliminated.
2235 for (const AsmToken &Token : A[Index])
2236 OS << Token.getString();
2242 unsigned I = Pos + 1;
2244 // Check for the \@ pseudo-variable.
2245 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2248 while (isIdentifierChar(Body[I]) && I + 1 != End)
2251 const char *Begin = Body.data() + Pos + 1;
2252 StringRef Argument(Begin, I - (Pos + 1));
2255 if (Argument == "@") {
2256 OS << NumOfMacroInstantiations;
2259 for (; Index < NParameters; ++Index)
2260 if (Parameters[Index].Name == Argument)
2263 if (Index == NParameters) {
2264 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2267 OS << '\\' << Argument;
2271 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2272 for (const AsmToken &Token : A[Index])
2273 // We expect no quotes around the string's contents when
2274 // parsing for varargs.
2275 if (Token.getKind() != AsmToken::String || VarargParameter)
2276 OS << Token.getString();
2278 OS << Token.getStringContents();
2280 Pos += 1 + Argument.size();
2284 // Update the scan point.
2285 Body = Body.substr(Pos);
2291 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2292 size_t CondStackDepth)
2293 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2294 CondStackDepth(CondStackDepth) {}
2296 static bool isOperator(AsmToken::TokenKind kind) {
2300 case AsmToken::Plus:
2301 case AsmToken::Minus:
2302 case AsmToken::Tilde:
2303 case AsmToken::Slash:
2304 case AsmToken::Star:
2306 case AsmToken::Equal:
2307 case AsmToken::EqualEqual:
2308 case AsmToken::Pipe:
2309 case AsmToken::PipePipe:
2310 case AsmToken::Caret:
2312 case AsmToken::AmpAmp:
2313 case AsmToken::Exclaim:
2314 case AsmToken::ExclaimEqual:
2315 case AsmToken::Less:
2316 case AsmToken::LessEqual:
2317 case AsmToken::LessLess:
2318 case AsmToken::LessGreater:
2319 case AsmToken::Greater:
2320 case AsmToken::GreaterEqual:
2321 case AsmToken::GreaterGreater:
2328 class AsmLexerSkipSpaceRAII {
2330 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2331 Lexer.setSkipSpace(SkipSpace);
2334 ~AsmLexerSkipSpaceRAII() {
2335 Lexer.setSkipSpace(true);
2342 } // end anonymous namespace
2344 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2347 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2348 StringRef Str = parseStringToEndOfStatement();
2349 MA.emplace_back(AsmToken::String, Str);
2354 unsigned ParenLevel = 0;
2356 // Darwin doesn't use spaces to delmit arguments.
2357 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2363 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2364 return TokError("unexpected token in macro instantiation");
2366 if (ParenLevel == 0) {
2368 if (Lexer.is(AsmToken::Comma))
2371 if (Lexer.is(AsmToken::Space)) {
2373 Lexer.Lex(); // Eat spaces
2376 // Spaces can delimit parameters, but could also be part an expression.
2377 // If the token after a space is an operator, add the token and the next
2378 // one into this argument
2380 if (isOperator(Lexer.getKind())) {
2381 MA.push_back(getTok());
2384 // Whitespace after an operator can be ignored.
2385 if (Lexer.is(AsmToken::Space))
2395 // handleMacroEntry relies on not advancing the lexer here
2396 // to be able to fill in the remaining default parameter values
2397 if (Lexer.is(AsmToken::EndOfStatement))
2400 // Adjust the current parentheses level.
2401 if (Lexer.is(AsmToken::LParen))
2403 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2406 // Append the token to the current argument list.
2407 MA.push_back(getTok());
2411 if (ParenLevel != 0)
2412 return TokError("unbalanced parentheses in macro argument");
2416 // Parse the macro instantiation arguments.
2417 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2418 MCAsmMacroArguments &A) {
2419 const unsigned NParameters = M ? M->Parameters.size() : 0;
2420 bool NamedParametersFound = false;
2421 SmallVector<SMLoc, 4> FALocs;
2423 A.resize(NParameters);
2424 FALocs.resize(NParameters);
2426 // Parse two kinds of macro invocations:
2427 // - macros defined without any parameters accept an arbitrary number of them
2428 // - macros defined with parameters accept at most that many of them
2429 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2430 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2432 SMLoc IDLoc = Lexer.getLoc();
2433 MCAsmMacroParameter FA;
2435 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2436 if (parseIdentifier(FA.Name))
2437 return Error(IDLoc, "invalid argument identifier for formal argument");
2439 if (Lexer.isNot(AsmToken::Equal))
2440 return TokError("expected '=' after formal parameter identifier");
2444 NamedParametersFound = true;
2447 if (NamedParametersFound && FA.Name.empty())
2448 return Error(IDLoc, "cannot mix positional and keyword arguments");
2450 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2451 if (parseMacroArgument(FA.Value, Vararg))
2454 unsigned PI = Parameter;
2455 if (!FA.Name.empty()) {
2457 for (FAI = 0; FAI < NParameters; ++FAI)
2458 if (M->Parameters[FAI].Name == FA.Name)
2461 if (FAI >= NParameters) {
2462 assert(M && "expected macro to be defined");
2463 return Error(IDLoc, "parameter named '" + FA.Name +
2464 "' does not exist for macro '" + M->Name + "'");
2469 if (!FA.Value.empty()) {
2474 if (FALocs.size() <= PI)
2475 FALocs.resize(PI + 1);
2477 FALocs[PI] = Lexer.getLoc();
2480 // At the end of the statement, fill in remaining arguments that have
2481 // default values. If there aren't any, then the next argument is
2482 // required but missing
2483 if (Lexer.is(AsmToken::EndOfStatement)) {
2484 bool Failure = false;
2485 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2486 if (A[FAI].empty()) {
2487 if (M->Parameters[FAI].Required) {
2488 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2489 "missing value for required parameter "
2490 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2494 if (!M->Parameters[FAI].Value.empty())
2495 A[FAI] = M->Parameters[FAI].Value;
2501 if (Lexer.is(AsmToken::Comma))
2505 return TokError("too many positional arguments");
2508 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2509 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2510 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2513 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2514 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2517 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2519 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2520 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2521 // eliminate this, although we should protect against infinite loops.
2522 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2523 if (ActiveMacros.size() == MaxNestingDepth) {
2524 std::ostringstream MaxNestingDepthError;
2525 MaxNestingDepthError << "macros cannot be nested more than "
2526 << MaxNestingDepth << " levels deep."
2527 << " Use -asm-macro-max-nesting-depth to increase "
2529 return TokError(MaxNestingDepthError.str());
2532 MCAsmMacroArguments A;
2533 if (parseMacroArguments(M, A))
2536 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2537 // to hold the macro body with substitutions.
2538 SmallString<256> Buf;
2539 StringRef Body = M->Body;
2540 raw_svector_ostream OS(Buf);
2542 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2545 // We include the .endmacro in the buffer as our cue to exit the macro
2547 OS << ".endmacro\n";
2549 std::unique_ptr<MemoryBuffer> Instantiation =
2550 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2552 // Create the macro instantiation object and add to the current macro
2553 // instantiation stack.
2554 MacroInstantiation *MI = new MacroInstantiation(
2555 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2556 ActiveMacros.push_back(MI);
2558 ++NumOfMacroInstantiations;
2560 // Jump to the macro instantiation and prime the lexer.
2561 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2562 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2568 void AsmParser::handleMacroExit() {
2569 // Jump to the EndOfStatement we should return to, and consume it.
2570 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2573 // Pop the instantiation entry.
2574 delete ActiveMacros.back();
2575 ActiveMacros.pop_back();
2578 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2581 const MCExpr *Value;
2582 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2587 // In the case where we parse an expression starting with a '.', we will
2588 // not generate an error, nor will we create a symbol. In this case we
2589 // should just return out.
2593 // Do the assignment.
2594 Out.EmitAssignment(Sym, Value);
2596 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2601 /// parseIdentifier:
2604 bool AsmParser::parseIdentifier(StringRef &Res) {
2605 // The assembler has relaxed rules for accepting identifiers, in particular we
2606 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2607 // separate tokens. At this level, we have already lexed so we cannot (currently)
2608 // handle this as a context dependent token, instead we detect adjacent tokens
2609 // and return the combined identifier.
2610 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2611 SMLoc PrefixLoc = getLexer().getLoc();
2613 // Consume the prefix character, and check for a following identifier.
2616 Lexer.peekTokens(Buf, false);
2618 if (Buf[0].isNot(AsmToken::Identifier))
2621 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2622 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2626 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2627 // Construct the joined identifier and consume the token.
2629 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2630 Lex(); // Parser Lex to maintain invariants.
2634 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2637 Res = getTok().getIdentifier();
2639 Lex(); // Consume the identifier token.
2644 /// parseDirectiveSet:
2645 /// ::= .equ identifier ',' expression
2646 /// ::= .equiv identifier ',' expression
2647 /// ::= .set identifier ',' expression
2648 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2650 if (check(parseIdentifier(Name), "expected identifier") ||
2651 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2652 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2656 bool AsmParser::parseEscapedString(std::string &Data) {
2657 if (check(getTok().isNot(AsmToken::String), "expected string"))
2661 StringRef Str = getTok().getStringContents();
2662 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2663 if (Str[i] != '\\') {
2668 // Recognize escaped characters. Note that this escape semantics currently
2669 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2672 return TokError("unexpected backslash at end of string");
2674 // Recognize octal sequences.
2675 if ((unsigned)(Str[i] - '0') <= 7) {
2676 // Consume up to three octal characters.
2677 unsigned Value = Str[i] - '0';
2679 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2681 Value = Value * 8 + (Str[i] - '0');
2683 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2685 Value = Value * 8 + (Str[i] - '0');
2690 return TokError("invalid octal escape sequence (out of range)");
2692 Data += (unsigned char)Value;
2696 // Otherwise recognize individual escapes.
2699 // Just reject invalid escape sequences for now.
2700 return TokError("invalid escape sequence (unrecognized character)");
2702 case 'b': Data += '\b'; break;
2703 case 'f': Data += '\f'; break;
2704 case 'n': Data += '\n'; break;
2705 case 'r': Data += '\r'; break;
2706 case 't': Data += '\t'; break;
2707 case '"': Data += '"'; break;
2708 case '\\': Data += '\\'; break;
2716 /// parseDirectiveAscii:
2717 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2718 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2719 auto parseOp = [&]() -> bool {
2721 if (checkForValidSection() || parseEscapedString(Data))
2723 getStreamer().EmitBytes(Data);
2725 getStreamer().EmitBytes(StringRef("\0", 1));
2729 if (parseMany(parseOp))
2730 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2734 /// parseDirectiveReloc
2735 /// ::= .reloc expression , identifier [ , expression ]
2736 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2737 const MCExpr *Offset;
2738 const MCExpr *Expr = nullptr;
2740 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2741 int64_t OffsetValue;
2742 // We can only deal with constant expressions at the moment.
2744 if (parseExpression(Offset))
2747 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2748 "expression is not a constant value") ||
2749 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2750 parseToken(AsmToken::Comma, "expected comma") ||
2751 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2754 SMLoc NameLoc = Lexer.getTok().getLoc();
2755 StringRef Name = Lexer.getTok().getIdentifier();
2758 if (Lexer.is(AsmToken::Comma)) {
2760 SMLoc ExprLoc = Lexer.getLoc();
2761 if (parseExpression(Expr))
2765 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2766 return Error(ExprLoc, "expression must be relocatable");
2769 if (parseToken(AsmToken::EndOfStatement,
2770 "unexpected token in .reloc directive"))
2773 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2774 return Error(NameLoc, "unknown relocation name");
2779 /// parseDirectiveValue
2780 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2781 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2782 auto parseOp = [&]() -> bool {
2783 const MCExpr *Value;
2784 SMLoc ExprLoc = getLexer().getLoc();
2785 if (checkForValidSection() || parseExpression(Value))
2787 // Special case constant expressions to match code generator.
2788 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2789 assert(Size <= 8 && "Invalid size");
2790 uint64_t IntValue = MCE->getValue();
2791 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2792 return Error(ExprLoc, "out of range literal value");
2793 getStreamer().EmitIntValue(IntValue, Size);
2795 getStreamer().EmitValue(Value, Size, ExprLoc);
2799 if (parseMany(parseOp))
2800 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2804 /// ParseDirectiveOctaValue
2805 /// ::= .octa [ hexconstant (, hexconstant)* ]
2807 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2808 auto parseOp = [&]() -> bool {
2809 if (checkForValidSection())
2811 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2812 return TokError("unknown token in expression");
2813 SMLoc ExprLoc = getTok().getLoc();
2814 APInt IntValue = getTok().getAPIntVal();
2817 if (!IntValue.isIntN(128))
2818 return Error(ExprLoc, "out of range literal value");
2819 if (!IntValue.isIntN(64)) {
2820 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2821 lo = IntValue.getLoBits(64).getZExtValue();
2824 lo = IntValue.getZExtValue();
2826 if (MAI.isLittleEndian()) {
2827 getStreamer().EmitIntValue(lo, 8);
2828 getStreamer().EmitIntValue(hi, 8);
2830 getStreamer().EmitIntValue(hi, 8);
2831 getStreamer().EmitIntValue(lo, 8);
2836 if (parseMany(parseOp))
2837 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2841 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2842 // We don't truly support arithmetic on floating point expressions, so we
2843 // have to manually parse unary prefixes.
2845 if (getLexer().is(AsmToken::Minus)) {
2848 } else if (getLexer().is(AsmToken::Plus))
2851 if (Lexer.is(AsmToken::Error))
2852 return TokError(Lexer.getErr());
2853 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2854 Lexer.isNot(AsmToken::Identifier))
2855 return TokError("unexpected token in directive");
2857 // Convert to an APFloat.
2858 APFloat Value(Semantics);
2859 StringRef IDVal = getTok().getString();
2860 if (getLexer().is(AsmToken::Identifier)) {
2861 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2862 Value = APFloat::getInf(Semantics);
2863 else if (!IDVal.compare_lower("nan"))
2864 Value = APFloat::getNaN(Semantics, false, ~0);
2866 return TokError("invalid floating point literal");
2867 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2868 APFloat::opInvalidOp)
2869 return TokError("invalid floating point literal");
2873 // Consume the numeric token.
2876 Res = Value.bitcastToAPInt();
2881 /// parseDirectiveRealValue
2882 /// ::= (.single | .double) [ expression (, expression)* ]
2883 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2884 const fltSemantics &Semantics) {
2885 auto parseOp = [&]() -> bool {
2887 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
2889 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2890 AsInt.getBitWidth() / 8);
2894 if (parseMany(parseOp))
2895 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2899 /// parseDirectiveZero
2900 /// ::= .zero expression
2901 bool AsmParser::parseDirectiveZero() {
2902 SMLoc NumBytesLoc = Lexer.getLoc();
2903 const MCExpr *NumBytes;
2904 if (checkForValidSection() || parseExpression(NumBytes))
2908 if (getLexer().is(AsmToken::Comma)) {
2910 if (parseAbsoluteExpression(Val))
2914 if (parseToken(AsmToken::EndOfStatement,
2915 "unexpected token in '.zero' directive"))
2917 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
2922 /// parseDirectiveFill
2923 /// ::= .fill expression [ , expression [ , expression ] ]
2924 bool AsmParser::parseDirectiveFill() {
2925 SMLoc NumValuesLoc = Lexer.getLoc();
2926 const MCExpr *NumValues;
2927 if (checkForValidSection() || parseExpression(NumValues))
2930 int64_t FillSize = 1;
2931 int64_t FillExpr = 0;
2933 SMLoc SizeLoc, ExprLoc;
2935 if (parseOptionalToken(AsmToken::Comma)) {
2936 SizeLoc = getTok().getLoc();
2937 if (parseAbsoluteExpression(FillSize))
2939 if (parseOptionalToken(AsmToken::Comma)) {
2940 ExprLoc = getTok().getLoc();
2941 if (parseAbsoluteExpression(FillExpr))
2945 if (parseToken(AsmToken::EndOfStatement,
2946 "unexpected token in '.fill' directive"))
2950 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2954 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2958 if (!isUInt<32>(FillExpr) && FillSize > 4)
2959 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2961 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
2966 /// parseDirectiveOrg
2967 /// ::= .org expression [ , expression ]
2968 bool AsmParser::parseDirectiveOrg() {
2969 const MCExpr *Offset;
2970 SMLoc OffsetLoc = Lexer.getLoc();
2971 if (checkForValidSection() || parseExpression(Offset))
2974 // Parse optional fill expression.
2975 int64_t FillExpr = 0;
2976 if (parseOptionalToken(AsmToken::Comma))
2977 if (parseAbsoluteExpression(FillExpr))
2978 return addErrorSuffix(" in '.org' directive");
2979 if (parseToken(AsmToken::EndOfStatement))
2980 return addErrorSuffix(" in '.org' directive");
2982 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
2986 /// parseDirectiveAlign
2987 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2988 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2989 SMLoc AlignmentLoc = getLexer().getLoc();
2992 bool HasFillExpr = false;
2993 int64_t FillExpr = 0;
2994 int64_t MaxBytesToFill = 0;
2996 auto parseAlign = [&]() -> bool {
2997 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
2999 if (parseOptionalToken(AsmToken::Comma)) {
3000 // The fill expression can be omitted while specifying a maximum number of
3001 // alignment bytes, e.g:
3003 if (getTok().isNot(AsmToken::Comma)) {
3005 if (parseAbsoluteExpression(FillExpr))
3008 if (parseOptionalToken(AsmToken::Comma))
3009 if (parseTokenLoc(MaxBytesLoc) ||
3010 parseAbsoluteExpression(MaxBytesToFill))
3013 return parseToken(AsmToken::EndOfStatement);
3017 return addErrorSuffix(" in directive");
3019 // Always emit an alignment here even if we thrown an error.
3020 bool ReturnVal = false;
3022 // Compute alignment in bytes.
3024 // FIXME: Diagnose overflow.
3025 if (Alignment >= 32) {
3026 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3030 Alignment = 1ULL << Alignment;
3032 // Reject alignments that aren't either a power of two or zero,
3033 // for gas compatibility. Alignment of zero is silently rounded
3037 if (!isPowerOf2_64(Alignment))
3038 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3041 // Diagnose non-sensical max bytes to align.
3042 if (MaxBytesLoc.isValid()) {
3043 if (MaxBytesToFill < 1) {
3044 ReturnVal |= Error(MaxBytesLoc,
3045 "alignment directive can never be satisfied in this "
3046 "many bytes, ignoring maximum bytes expression");
3050 if (MaxBytesToFill >= Alignment) {
3051 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3057 // Check whether we should use optimal code alignment for this .align
3059 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3060 assert(Section && "must have section to emit alignment");
3061 bool UseCodeAlign = Section->UseCodeAlign();
3062 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3063 ValueSize == 1 && UseCodeAlign) {
3064 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3066 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3067 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3074 /// parseDirectiveFile
3075 /// ::= .file [number] filename
3076 /// ::= .file number directory filename
3077 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3078 // FIXME: I'm not sure what this is.
3079 int64_t FileNumber = -1;
3080 SMLoc FileNumberLoc = getLexer().getLoc();
3081 if (getLexer().is(AsmToken::Integer)) {
3082 FileNumber = getTok().getIntVal();
3086 return TokError("file number less than one");
3089 std::string Path = getTok().getString();
3091 // Usually the directory and filename together, otherwise just the directory.
3092 // Allow the strings to have escaped octal character sequence.
3093 if (check(getTok().isNot(AsmToken::String),
3094 "unexpected token in '.file' directive") ||
3095 parseEscapedString(Path))
3098 StringRef Directory;
3100 std::string FilenameData;
3101 if (getLexer().is(AsmToken::String)) {
3102 if (check(FileNumber == -1,
3103 "explicit path specified, but no file number") ||
3104 parseEscapedString(FilenameData))
3106 Filename = FilenameData;
3112 if (parseToken(AsmToken::EndOfStatement,
3113 "unexpected token in '.file' directive"))
3116 if (FileNumber == -1)
3117 getStreamer().EmitFileDirective(Filename);
3119 // If there is -g option as well as debug info from directive file,
3120 // we turn off -g option, directly use the existing debug info instead.
3121 if (getContext().getGenDwarfForAssembly())
3122 getContext().setGenDwarfForAssembly(false);
3123 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3125 return Error(FileNumberLoc, "file number already allocated");
3131 /// parseDirectiveLine
3132 /// ::= .line [number]
3133 bool AsmParser::parseDirectiveLine() {
3135 if (getLexer().is(AsmToken::Integer)) {
3136 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3139 // FIXME: Do something with the .line.
3141 if (parseToken(AsmToken::EndOfStatement,
3142 "unexpected token in '.line' directive"))
3148 /// parseDirectiveLoc
3149 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3150 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3151 /// The first number is a file number, must have been previously assigned with
3152 /// a .file directive, the second number is the line number and optionally the
3153 /// third number is a column position (zero if not specified). The remaining
3154 /// optional items are .loc sub-directives.
3155 bool AsmParser::parseDirectiveLoc() {
3156 int64_t FileNumber = 0, LineNumber = 0;
3157 SMLoc Loc = getTok().getLoc();
3158 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3159 check(FileNumber < 1, Loc,
3160 "file number less than one in '.loc' directive") ||
3161 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3162 "unassigned file number in '.loc' directive"))
3166 if (getLexer().is(AsmToken::Integer)) {
3167 LineNumber = getTok().getIntVal();
3169 return TokError("line number less than zero in '.loc' directive");
3173 int64_t ColumnPos = 0;
3174 if (getLexer().is(AsmToken::Integer)) {
3175 ColumnPos = getTok().getIntVal();
3177 return TokError("column position less than zero in '.loc' directive");
3181 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3183 int64_t Discriminator = 0;
3185 auto parseLocOp = [&]() -> bool {
3187 SMLoc Loc = getTok().getLoc();
3188 if (parseIdentifier(Name))
3189 return TokError("unexpected token in '.loc' directive");
3191 if (Name == "basic_block")
3192 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3193 else if (Name == "prologue_end")
3194 Flags |= DWARF2_FLAG_PROLOGUE_END;
3195 else if (Name == "epilogue_begin")
3196 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3197 else if (Name == "is_stmt") {
3198 Loc = getTok().getLoc();
3199 const MCExpr *Value;
3200 if (parseExpression(Value))
3202 // The expression must be the constant 0 or 1.
3203 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3204 int Value = MCE->getValue();
3206 Flags &= ~DWARF2_FLAG_IS_STMT;
3207 else if (Value == 1)
3208 Flags |= DWARF2_FLAG_IS_STMT;
3210 return Error(Loc, "is_stmt value not 0 or 1");
3212 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3214 } else if (Name == "isa") {
3215 Loc = getTok().getLoc();
3216 const MCExpr *Value;
3217 if (parseExpression(Value))
3219 // The expression must be a constant greater or equal to 0.
3220 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3221 int Value = MCE->getValue();
3223 return Error(Loc, "isa number less than zero");
3226 return Error(Loc, "isa number not a constant value");
3228 } else if (Name == "discriminator") {
3229 if (parseAbsoluteExpression(Discriminator))
3232 return Error(Loc, "unknown sub-directive in '.loc' directive");
3237 if (parseMany(parseLocOp, false /*hasComma*/))
3240 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3241 Isa, Discriminator, StringRef());
3246 /// parseDirectiveStabs
3247 /// ::= .stabs string, number, number, number
3248 bool AsmParser::parseDirectiveStabs() {
3249 return TokError("unsupported directive '.stabs'");
3252 /// parseDirectiveCVFile
3253 /// ::= .cv_file number filename
3254 bool AsmParser::parseDirectiveCVFile() {
3255 SMLoc FileNumberLoc = getTok().getLoc();
3257 std::string Filename;
3259 if (parseIntToken(FileNumber,
3260 "expected file number in '.cv_file' directive") ||
3261 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3262 check(getTok().isNot(AsmToken::String),
3263 "unexpected token in '.cv_file' directive") ||
3264 // Usually directory and filename are together, otherwise just
3265 // directory. Allow the strings to have escaped octal character sequence.
3266 parseEscapedString(Filename) ||
3267 parseToken(AsmToken::EndOfStatement,
3268 "unexpected token in '.cv_file' directive"))
3271 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
3272 return Error(FileNumberLoc, "file number already allocated");
3277 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3278 StringRef DirectiveName) {
3280 return parseTokenLoc(Loc) ||
3281 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3283 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3284 "expected function id within range [0, UINT_MAX)");
3287 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3289 return parseTokenLoc(Loc) ||
3290 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3292 check(FileNumber < 1, Loc, "file number less than one in '" +
3293 DirectiveName + "' directive") ||
3294 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3295 "unassigned file number in '" + DirectiveName + "' directive");
3298 /// parseDirectiveCVFuncId
3299 /// ::= .cv_func_id FunctionId
3301 /// Introduces a function ID that can be used with .cv_loc.
3302 bool AsmParser::parseDirectiveCVFuncId() {
3303 SMLoc FunctionIdLoc = getTok().getLoc();
3306 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3307 parseToken(AsmToken::EndOfStatement,
3308 "unexpected token in '.cv_func_id' directive"))
3311 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3312 return Error(FunctionIdLoc, "function id already allocated");
3317 /// parseDirectiveCVInlineSiteId
3318 /// ::= .cv_inline_site_id FunctionId
3320 /// "inlined_at" IAFile IALine [IACol]
3322 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3323 /// at" source location information for use in the line table of the caller,
3324 /// whether the caller is a real function or another inlined call site.
3325 bool AsmParser::parseDirectiveCVInlineSiteId() {
3326 SMLoc FunctionIdLoc = getTok().getLoc();
3334 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3338 if (check((getLexer().isNot(AsmToken::Identifier) ||
3339 getTok().getIdentifier() != "within"),
3340 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3345 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3349 if (check((getLexer().isNot(AsmToken::Identifier) ||
3350 getTok().getIdentifier() != "inlined_at"),
3351 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3357 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3358 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3362 if (getLexer().is(AsmToken::Integer)) {
3363 IACol = getTok().getIntVal();
3367 if (parseToken(AsmToken::EndOfStatement,
3368 "unexpected token in '.cv_inline_site_id' directive"))
3371 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3372 IALine, IACol, FunctionIdLoc))
3373 return Error(FunctionIdLoc, "function id already allocated");
3378 /// parseDirectiveCVLoc
3379 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3381 /// The first number is a file number, must have been previously assigned with
3382 /// a .file directive, the second number is the line number and optionally the
3383 /// third number is a column position (zero if not specified). The remaining
3384 /// optional items are .loc sub-directives.
3385 bool AsmParser::parseDirectiveCVLoc() {
3386 SMLoc DirectiveLoc = getTok().getLoc();
3388 int64_t FunctionId, FileNumber;
3389 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3390 parseCVFileId(FileNumber, ".cv_loc"))
3393 int64_t LineNumber = 0;
3394 if (getLexer().is(AsmToken::Integer)) {
3395 LineNumber = getTok().getIntVal();
3397 return TokError("line number less than zero in '.cv_loc' directive");
3401 int64_t ColumnPos = 0;
3402 if (getLexer().is(AsmToken::Integer)) {
3403 ColumnPos = getTok().getIntVal();
3405 return TokError("column position less than zero in '.cv_loc' directive");
3409 bool PrologueEnd = false;
3410 uint64_t IsStmt = 0;
3412 auto parseOp = [&]() -> bool {
3414 SMLoc Loc = getTok().getLoc();
3415 if (parseIdentifier(Name))
3416 return TokError("unexpected token in '.cv_loc' directive");
3417 if (Name == "prologue_end")
3419 else if (Name == "is_stmt") {
3420 Loc = getTok().getLoc();
3421 const MCExpr *Value;
3422 if (parseExpression(Value))
3424 // The expression must be the constant 0 or 1.
3426 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3427 IsStmt = MCE->getValue();
3430 return Error(Loc, "is_stmt value not 0 or 1");
3432 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3437 if (parseMany(parseOp, false /*hasComma*/))
3440 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3441 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3446 /// parseDirectiveCVLinetable
3447 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3448 bool AsmParser::parseDirectiveCVLinetable() {
3450 StringRef FnStartName, FnEndName;
3451 SMLoc Loc = getTok().getLoc();
3452 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3453 parseToken(AsmToken::Comma,
3454 "unexpected token in '.cv_linetable' directive") ||
3455 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3456 "expected identifier in directive") ||
3457 parseToken(AsmToken::Comma,
3458 "unexpected token in '.cv_linetable' directive") ||
3459 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3460 "expected identifier in directive"))
3463 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3464 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3466 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3470 /// parseDirectiveCVInlineLinetable
3471 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3472 bool AsmParser::parseDirectiveCVInlineLinetable() {
3473 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3474 StringRef FnStartName, FnEndName;
3475 SMLoc Loc = getTok().getLoc();
3476 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3477 parseTokenLoc(Loc) ||
3480 "expected SourceField in '.cv_inline_linetable' directive") ||
3481 check(SourceFileId <= 0, Loc,
3482 "File id less than zero in '.cv_inline_linetable' directive") ||
3483 parseTokenLoc(Loc) ||
3486 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3487 check(SourceLineNum < 0, Loc,
3488 "Line number less than zero in '.cv_inline_linetable' directive") ||
3489 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3490 "expected identifier in directive") ||
3491 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3492 "expected identifier in directive"))
3495 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3498 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3499 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3500 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3501 SourceLineNum, FnStartSym,
3506 /// parseDirectiveCVDefRange
3507 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3508 bool AsmParser::parseDirectiveCVDefRange() {
3510 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3511 while (getLexer().is(AsmToken::Identifier)) {
3512 Loc = getLexer().getLoc();
3513 StringRef GapStartName;
3514 if (parseIdentifier(GapStartName))
3515 return Error(Loc, "expected identifier in directive");
3516 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3518 Loc = getLexer().getLoc();
3519 StringRef GapEndName;
3520 if (parseIdentifier(GapEndName))
3521 return Error(Loc, "expected identifier in directive");
3522 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3524 Ranges.push_back({GapStartSym, GapEndSym});
3527 std::string FixedSizePortion;
3528 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3529 parseEscapedString(FixedSizePortion))
3532 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3536 /// parseDirectiveCVStringTable
3537 /// ::= .cv_stringtable
3538 bool AsmParser::parseDirectiveCVStringTable() {
3539 getStreamer().EmitCVStringTableDirective();
3543 /// parseDirectiveCVFileChecksums
3544 /// ::= .cv_filechecksums
3545 bool AsmParser::parseDirectiveCVFileChecksums() {
3546 getStreamer().EmitCVFileChecksumsDirective();
3550 /// parseDirectiveCFISections
3551 /// ::= .cfi_sections section [, section]
3552 bool AsmParser::parseDirectiveCFISections() {
3557 if (parseIdentifier(Name))
3558 return TokError("Expected an identifier");
3560 if (Name == ".eh_frame")
3562 else if (Name == ".debug_frame")
3565 if (getLexer().is(AsmToken::Comma)) {
3568 if (parseIdentifier(Name))
3569 return TokError("Expected an identifier");
3571 if (Name == ".eh_frame")
3573 else if (Name == ".debug_frame")
3577 getStreamer().EmitCFISections(EH, Debug);
3581 /// parseDirectiveCFIStartProc
3582 /// ::= .cfi_startproc [simple]
3583 bool AsmParser::parseDirectiveCFIStartProc() {
3585 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3586 if (check(parseIdentifier(Simple) || Simple != "simple",
3587 "unexpected token") ||
3588 parseToken(AsmToken::EndOfStatement))
3589 return addErrorSuffix(" in '.cfi_startproc' directive");
3592 getStreamer().EmitCFIStartProc(!Simple.empty());
3596 /// parseDirectiveCFIEndProc
3597 /// ::= .cfi_endproc
3598 bool AsmParser::parseDirectiveCFIEndProc() {
3599 getStreamer().EmitCFIEndProc();
3603 /// \brief parse register name or number.
3604 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3605 SMLoc DirectiveLoc) {
3608 if (getLexer().isNot(AsmToken::Integer)) {
3609 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3611 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3613 return parseAbsoluteExpression(Register);
3618 /// parseDirectiveCFIDefCfa
3619 /// ::= .cfi_def_cfa register, offset
3620 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3621 int64_t Register = 0, Offset = 0;
3622 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3623 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3624 parseAbsoluteExpression(Offset))
3627 getStreamer().EmitCFIDefCfa(Register, Offset);
3631 /// parseDirectiveCFIDefCfaOffset
3632 /// ::= .cfi_def_cfa_offset offset
3633 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3635 if (parseAbsoluteExpression(Offset))
3638 getStreamer().EmitCFIDefCfaOffset(Offset);
3642 /// parseDirectiveCFIRegister
3643 /// ::= .cfi_register register, register
3644 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3645 int64_t Register1 = 0, Register2 = 0;
3646 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3647 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3648 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3651 getStreamer().EmitCFIRegister(Register1, Register2);
3655 /// parseDirectiveCFIWindowSave
3656 /// ::= .cfi_window_save
3657 bool AsmParser::parseDirectiveCFIWindowSave() {
3658 getStreamer().EmitCFIWindowSave();
3662 /// parseDirectiveCFIAdjustCfaOffset
3663 /// ::= .cfi_adjust_cfa_offset adjustment
3664 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3665 int64_t Adjustment = 0;
3666 if (parseAbsoluteExpression(Adjustment))
3669 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3673 /// parseDirectiveCFIDefCfaRegister
3674 /// ::= .cfi_def_cfa_register register
3675 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3676 int64_t Register = 0;
3677 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3680 getStreamer().EmitCFIDefCfaRegister(Register);
3684 /// parseDirectiveCFIOffset
3685 /// ::= .cfi_offset register, offset
3686 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3687 int64_t Register = 0;
3690 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3691 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3692 parseAbsoluteExpression(Offset))
3695 getStreamer().EmitCFIOffset(Register, Offset);
3699 /// parseDirectiveCFIRelOffset
3700 /// ::= .cfi_rel_offset register, offset
3701 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3702 int64_t Register = 0, Offset = 0;
3704 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3705 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3706 parseAbsoluteExpression(Offset))
3709 getStreamer().EmitCFIRelOffset(Register, Offset);
3713 static bool isValidEncoding(int64_t Encoding) {
3714 if (Encoding & ~0xff)
3717 if (Encoding == dwarf::DW_EH_PE_omit)
3720 const unsigned Format = Encoding & 0xf;
3721 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3722 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3723 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3724 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3727 const unsigned Application = Encoding & 0x70;
3728 if (Application != dwarf::DW_EH_PE_absptr &&
3729 Application != dwarf::DW_EH_PE_pcrel)
3735 /// parseDirectiveCFIPersonalityOrLsda
3736 /// IsPersonality true for cfi_personality, false for cfi_lsda
3737 /// ::= .cfi_personality encoding, [symbol_name]
3738 /// ::= .cfi_lsda encoding, [symbol_name]
3739 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3740 int64_t Encoding = 0;
3741 if (parseAbsoluteExpression(Encoding))
3743 if (Encoding == dwarf::DW_EH_PE_omit)
3747 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3748 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3749 check(parseIdentifier(Name), "expected identifier in directive"))
3752 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3755 getStreamer().EmitCFIPersonality(Sym, Encoding);
3757 getStreamer().EmitCFILsda(Sym, Encoding);
3761 /// parseDirectiveCFIRememberState
3762 /// ::= .cfi_remember_state
3763 bool AsmParser::parseDirectiveCFIRememberState() {
3764 getStreamer().EmitCFIRememberState();
3768 /// parseDirectiveCFIRestoreState
3769 /// ::= .cfi_remember_state
3770 bool AsmParser::parseDirectiveCFIRestoreState() {
3771 getStreamer().EmitCFIRestoreState();
3775 /// parseDirectiveCFISameValue
3776 /// ::= .cfi_same_value register
3777 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3778 int64_t Register = 0;
3780 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3783 getStreamer().EmitCFISameValue(Register);
3787 /// parseDirectiveCFIRestore
3788 /// ::= .cfi_restore register
3789 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3790 int64_t Register = 0;
3791 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3794 getStreamer().EmitCFIRestore(Register);
3798 /// parseDirectiveCFIEscape
3799 /// ::= .cfi_escape expression[,...]
3800 bool AsmParser::parseDirectiveCFIEscape() {
3803 if (parseAbsoluteExpression(CurrValue))
3806 Values.push_back((uint8_t)CurrValue);
3808 while (getLexer().is(AsmToken::Comma)) {
3811 if (parseAbsoluteExpression(CurrValue))
3814 Values.push_back((uint8_t)CurrValue);
3817 getStreamer().EmitCFIEscape(Values);
3821 /// parseDirectiveCFISignalFrame
3822 /// ::= .cfi_signal_frame
3823 bool AsmParser::parseDirectiveCFISignalFrame() {
3824 if (parseToken(AsmToken::EndOfStatement,
3825 "unexpected token in '.cfi_signal_frame'"))
3828 getStreamer().EmitCFISignalFrame();
3832 /// parseDirectiveCFIUndefined
3833 /// ::= .cfi_undefined register
3834 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3835 int64_t Register = 0;
3837 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3840 getStreamer().EmitCFIUndefined(Register);
3844 /// parseDirectiveMacrosOnOff
3847 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3848 if (parseToken(AsmToken::EndOfStatement,
3849 "unexpected token in '" + Directive + "' directive"))
3852 setMacrosEnabled(Directive == ".macros_on");
3856 /// parseDirectiveMacro
3857 /// ::= .macro name[,] [parameters]
3858 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3860 if (parseIdentifier(Name))
3861 return TokError("expected identifier in '.macro' directive");
3863 if (getLexer().is(AsmToken::Comma))
3866 MCAsmMacroParameters Parameters;
3867 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3869 if (!Parameters.empty() && Parameters.back().Vararg)
3870 return Error(Lexer.getLoc(),
3871 "Vararg parameter '" + Parameters.back().Name +
3872 "' should be last one in the list of parameters.");
3874 MCAsmMacroParameter Parameter;
3875 if (parseIdentifier(Parameter.Name))
3876 return TokError("expected identifier in '.macro' directive");
3878 // Emit an error if two (or more) named parameters share the same name
3879 for (const MCAsmMacroParameter& CurrParam : Parameters)
3880 if (CurrParam.Name.equals(Parameter.Name))
3881 return TokError("macro '" + Name + "' has multiple parameters"
3882 " named '" + Parameter.Name + "'");
3884 if (Lexer.is(AsmToken::Colon)) {
3885 Lex(); // consume ':'
3888 StringRef Qualifier;
3890 QualLoc = Lexer.getLoc();
3891 if (parseIdentifier(Qualifier))
3892 return Error(QualLoc, "missing parameter qualifier for "
3893 "'" + Parameter.Name + "' in macro '" + Name + "'");
3895 if (Qualifier == "req")
3896 Parameter.Required = true;
3897 else if (Qualifier == "vararg")
3898 Parameter.Vararg = true;
3900 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3901 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3904 if (getLexer().is(AsmToken::Equal)) {
3909 ParamLoc = Lexer.getLoc();
3910 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3913 if (Parameter.Required)
3914 Warning(ParamLoc, "pointless default value for required parameter "
3915 "'" + Parameter.Name + "' in macro '" + Name + "'");
3918 Parameters.push_back(std::move(Parameter));
3920 if (getLexer().is(AsmToken::Comma))
3924 // Eat just the end of statement.
3927 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
3928 AsmToken EndToken, StartToken = getTok();
3929 unsigned MacroDepth = 0;
3930 // Lex the macro definition.
3932 // Ignore Lexing errors in macros.
3933 while (Lexer.is(AsmToken::Error)) {
3937 // Check whether we have reached the end of the file.
3938 if (getLexer().is(AsmToken::Eof))
3939 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3941 // Otherwise, check whether we have reach the .endmacro.
3942 if (getLexer().is(AsmToken::Identifier)) {
3943 if (getTok().getIdentifier() == ".endm" ||
3944 getTok().getIdentifier() == ".endmacro") {
3945 if (MacroDepth == 0) { // Outermost macro.
3946 EndToken = getTok();
3948 if (getLexer().isNot(AsmToken::EndOfStatement))
3949 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3953 // Otherwise we just found the end of an inner macro.
3956 } else if (getTok().getIdentifier() == ".macro") {
3957 // We allow nested macros. Those aren't instantiated until the outermost
3958 // macro is expanded so just ignore them for now.
3963 // Otherwise, scan til the end of the statement.
3964 eatToEndOfStatement();
3967 if (lookupMacro(Name)) {
3968 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3971 const char *BodyStart = StartToken.getLoc().getPointer();
3972 const char *BodyEnd = EndToken.getLoc().getPointer();
3973 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3974 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3975 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3979 /// checkForBadMacro
3981 /// With the support added for named parameters there may be code out there that
3982 /// is transitioning from positional parameters. In versions of gas that did
3983 /// not support named parameters they would be ignored on the macro definition.
3984 /// But to support both styles of parameters this is not possible so if a macro
3985 /// definition has named parameters but does not use them and has what appears
3986 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3987 /// warning that the positional parameter found in body which have no effect.
3988 /// Hoping the developer will either remove the named parameters from the macro
3989 /// definition so the positional parameters get used if that was what was
3990 /// intended or change the macro to use the named parameters. It is possible
3991 /// this warning will trigger when the none of the named parameters are used
3992 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3993 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3995 ArrayRef<MCAsmMacroParameter> Parameters) {
3996 // If this macro is not defined with named parameters the warning we are
3997 // checking for here doesn't apply.
3998 unsigned NParameters = Parameters.size();
3999 if (NParameters == 0)
4002 bool NamedParametersFound = false;
4003 bool PositionalParametersFound = false;
4005 // Look at the body of the macro for use of both the named parameters and what
4006 // are likely to be positional parameters. This is what expandMacro() is
4007 // doing when it finds the parameters in the body.
4008 while (!Body.empty()) {
4009 // Scan for the next possible parameter.
4010 std::size_t End = Body.size(), Pos = 0;
4011 for (; Pos != End; ++Pos) {
4012 // Check for a substitution or escape.
4013 // This macro is defined with parameters, look for \foo, \bar, etc.
4014 if (Body[Pos] == '\\' && Pos + 1 != End)
4017 // This macro should have parameters, but look for $0, $1, ..., $n too.
4018 if (Body[Pos] != '$' || Pos + 1 == End)
4020 char Next = Body[Pos + 1];
4021 if (Next == '$' || Next == 'n' ||
4022 isdigit(static_cast<unsigned char>(Next)))
4026 // Check if we reached the end.
4030 if (Body[Pos] == '$') {
4031 switch (Body[Pos + 1]) {
4036 // $n => number of arguments
4038 PositionalParametersFound = true;
4041 // $[0-9] => argument
4043 PositionalParametersFound = true;
4049 unsigned I = Pos + 1;
4050 while (isIdentifierChar(Body[I]) && I + 1 != End)
4053 const char *Begin = Body.data() + Pos + 1;
4054 StringRef Argument(Begin, I - (Pos + 1));
4056 for (; Index < NParameters; ++Index)
4057 if (Parameters[Index].Name == Argument)
4060 if (Index == NParameters) {
4061 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4067 NamedParametersFound = true;
4068 Pos += 1 + Argument.size();
4071 // Update the scan point.
4072 Body = Body.substr(Pos);
4075 if (!NamedParametersFound && PositionalParametersFound)
4076 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4077 "used in macro body, possible positional parameter "
4078 "found in body which will have no effect");
4081 /// parseDirectiveExitMacro
4083 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4084 if (parseToken(AsmToken::EndOfStatement,
4085 "unexpected token in '" + Directive + "' directive"))
4088 if (!isInsideMacroInstantiation())
4089 return TokError("unexpected '" + Directive + "' in file, "
4090 "no current macro definition");
4092 // Exit all conditionals that are active in the current macro.
4093 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4094 TheCondState = TheCondStack.back();
4095 TheCondStack.pop_back();
4102 /// parseDirectiveEndMacro
4105 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4106 if (getLexer().isNot(AsmToken::EndOfStatement))
4107 return TokError("unexpected token in '" + Directive + "' directive");
4109 // If we are inside a macro instantiation, terminate the current
4111 if (isInsideMacroInstantiation()) {
4116 // Otherwise, this .endmacro is a stray entry in the file; well formed
4117 // .endmacro directives are handled during the macro definition parsing.
4118 return TokError("unexpected '" + Directive + "' in file, "
4119 "no current macro definition");
4122 /// parseDirectivePurgeMacro
4124 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4127 if (parseTokenLoc(Loc) ||
4128 check(parseIdentifier(Name), Loc,
4129 "expected identifier in '.purgem' directive") ||
4130 parseToken(AsmToken::EndOfStatement,
4131 "unexpected token in '.purgem' directive"))
4134 if (!lookupMacro(Name))
4135 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4137 undefineMacro(Name);
4141 /// parseDirectiveBundleAlignMode
4142 /// ::= {.bundle_align_mode} expression
4143 bool AsmParser::parseDirectiveBundleAlignMode() {
4144 // Expect a single argument: an expression that evaluates to a constant
4145 // in the inclusive range 0-30.
4146 SMLoc ExprLoc = getLexer().getLoc();
4147 int64_t AlignSizePow2;
4148 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4149 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4150 "in '.bundle_align_mode' "
4152 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4153 "invalid bundle alignment size (expected between 0 and 30)"))
4156 // Because of AlignSizePow2's verified range we can safely truncate it to
4158 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4162 /// parseDirectiveBundleLock
4163 /// ::= {.bundle_lock} [align_to_end]
4164 bool AsmParser::parseDirectiveBundleLock() {
4165 if (checkForValidSection())
4167 bool AlignToEnd = false;
4170 SMLoc Loc = getTok().getLoc();
4171 const char *kInvalidOptionError =
4172 "invalid option for '.bundle_lock' directive";
4174 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4175 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4176 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4177 parseToken(AsmToken::EndOfStatement,
4178 "unexpected token after '.bundle_lock' directive option"))
4183 getStreamer().EmitBundleLock(AlignToEnd);
4187 /// parseDirectiveBundleLock
4188 /// ::= {.bundle_lock}
4189 bool AsmParser::parseDirectiveBundleUnlock() {
4190 if (checkForValidSection() ||
4191 parseToken(AsmToken::EndOfStatement,
4192 "unexpected token in '.bundle_unlock' directive"))
4195 getStreamer().EmitBundleUnlock();
4199 /// parseDirectiveSpace
4200 /// ::= (.skip | .space) expression [ , expression ]
4201 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4202 SMLoc NumBytesLoc = Lexer.getLoc();
4203 const MCExpr *NumBytes;
4204 if (checkForValidSection() || parseExpression(NumBytes))
4207 int64_t FillExpr = 0;
4208 if (parseOptionalToken(AsmToken::Comma))
4209 if (parseAbsoluteExpression(FillExpr))
4210 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4211 if (parseToken(AsmToken::EndOfStatement))
4212 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4214 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4215 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4220 /// parseDirectiveDCB
4221 /// ::= .dcb.{b, l, w} expression, expression
4222 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4223 SMLoc NumValuesLoc = Lexer.getLoc();
4225 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4228 if (NumValues < 0) {
4229 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4233 if (parseToken(AsmToken::Comma,
4234 "unexpected token in '" + Twine(IDVal) + "' directive"))
4237 const MCExpr *Value;
4238 SMLoc ExprLoc = getLexer().getLoc();
4239 if (parseExpression(Value))
4242 // Special case constant expressions to match code generator.
4243 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4244 assert(Size <= 8 && "Invalid size");
4245 uint64_t IntValue = MCE->getValue();
4246 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4247 return Error(ExprLoc, "literal value out of range for directive");
4248 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4249 getStreamer().EmitIntValue(IntValue, Size);
4251 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4252 getStreamer().EmitValue(Value, Size, ExprLoc);
4255 if (parseToken(AsmToken::EndOfStatement,
4256 "unexpected token in '" + Twine(IDVal) + "' directive"))
4262 /// parseDirectiveRealDCB
4263 /// ::= .dcb.{d, s} expression, expression
4264 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4265 SMLoc NumValuesLoc = Lexer.getLoc();
4267 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4270 if (NumValues < 0) {
4271 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4275 if (parseToken(AsmToken::Comma,
4276 "unexpected token in '" + Twine(IDVal) + "' directive"))
4280 if (parseRealValue(Semantics, AsInt))
4283 if (parseToken(AsmToken::EndOfStatement,
4284 "unexpected token in '" + Twine(IDVal) + "' directive"))
4287 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4288 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4289 AsInt.getBitWidth() / 8);
4294 /// parseDirectiveDS
4295 /// ::= .ds.{b, d, l, p, s, w, x} expression
4296 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4297 SMLoc NumValuesLoc = Lexer.getLoc();
4299 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4302 if (NumValues < 0) {
4303 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4307 if (parseToken(AsmToken::EndOfStatement,
4308 "unexpected token in '" + Twine(IDVal) + "' directive"))
4311 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4312 getStreamer().emitFill(Size, 0);
4317 /// parseDirectiveLEB128
4318 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4319 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4320 if (checkForValidSection())
4323 auto parseOp = [&]() -> bool {
4324 const MCExpr *Value;
4325 if (parseExpression(Value))
4328 getStreamer().EmitSLEB128Value(Value);
4330 getStreamer().EmitULEB128Value(Value);
4334 if (parseMany(parseOp))
4335 return addErrorSuffix(" in directive");
4340 /// parseDirectiveSymbolAttribute
4341 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4342 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4343 auto parseOp = [&]() -> bool {
4345 SMLoc Loc = getTok().getLoc();
4346 if (parseIdentifier(Name))
4347 return Error(Loc, "expected identifier");
4348 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4350 // Assembler local symbols don't make any sense here. Complain loudly.
4351 if (Sym->isTemporary())
4352 return Error(Loc, "non-local symbol required");
4354 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4355 return Error(Loc, "unable to emit symbol attribute");
4359 if (parseMany(parseOp))
4360 return addErrorSuffix(" in directive");
4364 /// parseDirectiveComm
4365 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4366 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4367 if (checkForValidSection())
4370 SMLoc IDLoc = getLexer().getLoc();
4372 if (parseIdentifier(Name))
4373 return TokError("expected identifier in directive");
4375 // Handle the identifier as the key symbol.
4376 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4378 if (getLexer().isNot(AsmToken::Comma))
4379 return TokError("unexpected token in directive");
4383 SMLoc SizeLoc = getLexer().getLoc();
4384 if (parseAbsoluteExpression(Size))
4387 int64_t Pow2Alignment = 0;
4388 SMLoc Pow2AlignmentLoc;
4389 if (getLexer().is(AsmToken::Comma)) {
4391 Pow2AlignmentLoc = getLexer().getLoc();
4392 if (parseAbsoluteExpression(Pow2Alignment))
4395 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4396 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4397 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4399 // If this target takes alignments in bytes (not log) validate and convert.
4400 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4401 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4402 if (!isPowerOf2_64(Pow2Alignment))
4403 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4404 Pow2Alignment = Log2_64(Pow2Alignment);
4408 if (parseToken(AsmToken::EndOfStatement,
4409 "unexpected token in '.comm' or '.lcomm' directive"))
4412 // NOTE: a size of zero for a .comm should create a undefined symbol
4413 // but a size of .lcomm creates a bss symbol of size zero.
4415 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4416 "be less than zero");
4418 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4419 // may internally end up wanting an alignment in bytes.
4420 // FIXME: Diagnose overflow.
4421 if (Pow2Alignment < 0)
4422 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4423 "alignment, can't be less than zero");
4425 Sym->redefineIfPossible();
4426 if (!Sym->isUndefined())
4427 return Error(IDLoc, "invalid symbol redefinition");
4429 // Create the Symbol as a common or local common with Size and Pow2Alignment
4431 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4435 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4439 /// parseDirectiveAbort
4440 /// ::= .abort [... message ...]
4441 bool AsmParser::parseDirectiveAbort() {
4442 // FIXME: Use loc from directive.
4443 SMLoc Loc = getLexer().getLoc();
4445 StringRef Str = parseStringToEndOfStatement();
4446 if (parseToken(AsmToken::EndOfStatement,
4447 "unexpected token in '.abort' directive"))
4451 return Error(Loc, ".abort detected. Assembly stopping.");
4453 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4454 // FIXME: Actually abort assembly here.
4459 /// parseDirectiveInclude
4460 /// ::= .include "filename"
4461 bool AsmParser::parseDirectiveInclude() {
4462 // Allow the strings to have escaped octal character sequence.
4463 std::string Filename;
4464 SMLoc IncludeLoc = getTok().getLoc();
4466 if (check(getTok().isNot(AsmToken::String),
4467 "expected string in '.include' directive") ||
4468 parseEscapedString(Filename) ||
4469 check(getTok().isNot(AsmToken::EndOfStatement),
4470 "unexpected token in '.include' directive") ||
4471 // Attempt to switch the lexer to the included file before consuming the
4472 // end of statement to avoid losing it when we switch.
4473 check(enterIncludeFile(Filename), IncludeLoc,
4474 "Could not find include file '" + Filename + "'"))
4480 /// parseDirectiveIncbin
4481 /// ::= .incbin "filename" [ , skip [ , count ] ]
4482 bool AsmParser::parseDirectiveIncbin() {
4483 // Allow the strings to have escaped octal character sequence.
4484 std::string Filename;
4485 SMLoc IncbinLoc = getTok().getLoc();
4486 if (check(getTok().isNot(AsmToken::String),
4487 "expected string in '.incbin' directive") ||
4488 parseEscapedString(Filename))
4492 const MCExpr *Count = nullptr;
4493 SMLoc SkipLoc, CountLoc;
4494 if (parseOptionalToken(AsmToken::Comma)) {
4495 // The skip expression can be omitted while specifying the count, e.g:
4496 // .incbin "filename",,4
4497 if (getTok().isNot(AsmToken::Comma)) {
4498 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4501 if (parseOptionalToken(AsmToken::Comma)) {
4502 CountLoc = getTok().getLoc();
4503 if (parseExpression(Count))
4508 if (parseToken(AsmToken::EndOfStatement,
4509 "unexpected token in '.incbin' directive"))
4512 if (check(Skip < 0, SkipLoc, "skip is negative"))
4515 // Attempt to process the included file.
4516 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4517 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4521 /// parseDirectiveIf
4522 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4523 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4524 TheCondStack.push_back(TheCondState);
4525 TheCondState.TheCond = AsmCond::IfCond;
4526 if (TheCondState.Ignore) {
4527 eatToEndOfStatement();
4530 if (parseAbsoluteExpression(ExprValue) ||
4531 parseToken(AsmToken::EndOfStatement,
4532 "unexpected token in '.if' directive"))
4537 llvm_unreachable("unsupported directive");
4542 ExprValue = ExprValue == 0;
4545 ExprValue = ExprValue >= 0;
4548 ExprValue = ExprValue > 0;
4551 ExprValue = ExprValue <= 0;
4554 ExprValue = ExprValue < 0;
4558 TheCondState.CondMet = ExprValue;
4559 TheCondState.Ignore = !TheCondState.CondMet;
4565 /// parseDirectiveIfb
4567 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4568 TheCondStack.push_back(TheCondState);
4569 TheCondState.TheCond = AsmCond::IfCond;
4571 if (TheCondState.Ignore) {
4572 eatToEndOfStatement();
4574 StringRef Str = parseStringToEndOfStatement();
4576 if (parseToken(AsmToken::EndOfStatement,
4577 "unexpected token in '.ifb' directive"))
4580 TheCondState.CondMet = ExpectBlank == Str.empty();
4581 TheCondState.Ignore = !TheCondState.CondMet;
4587 /// parseDirectiveIfc
4588 /// ::= .ifc string1, string2
4589 /// ::= .ifnc string1, string2
4590 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4591 TheCondStack.push_back(TheCondState);
4592 TheCondState.TheCond = AsmCond::IfCond;
4594 if (TheCondState.Ignore) {
4595 eatToEndOfStatement();
4597 StringRef Str1 = parseStringToComma();
4599 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4602 StringRef Str2 = parseStringToEndOfStatement();
4604 if (parseToken(AsmToken::EndOfStatement,
4605 "unexpected token in '.ifc' directive"))
4608 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4609 TheCondState.Ignore = !TheCondState.CondMet;
4615 /// parseDirectiveIfeqs
4616 /// ::= .ifeqs string1, string2
4617 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4618 if (Lexer.isNot(AsmToken::String)) {
4620 return TokError("expected string parameter for '.ifeqs' directive");
4621 return TokError("expected string parameter for '.ifnes' directive");
4624 StringRef String1 = getTok().getStringContents();
4627 if (Lexer.isNot(AsmToken::Comma)) {
4630 "expected comma after first string for '.ifeqs' directive");
4631 return TokError("expected comma after first string for '.ifnes' directive");
4636 if (Lexer.isNot(AsmToken::String)) {
4638 return TokError("expected string parameter for '.ifeqs' directive");
4639 return TokError("expected string parameter for '.ifnes' directive");
4642 StringRef String2 = getTok().getStringContents();
4645 TheCondStack.push_back(TheCondState);
4646 TheCondState.TheCond = AsmCond::IfCond;
4647 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4648 TheCondState.Ignore = !TheCondState.CondMet;
4653 /// parseDirectiveIfdef
4654 /// ::= .ifdef symbol
4655 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4657 TheCondStack.push_back(TheCondState);
4658 TheCondState.TheCond = AsmCond::IfCond;
4660 if (TheCondState.Ignore) {
4661 eatToEndOfStatement();
4663 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4664 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4667 MCSymbol *Sym = getContext().lookupSymbol(Name);
4670 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4672 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4673 TheCondState.Ignore = !TheCondState.CondMet;
4679 /// parseDirectiveElseIf
4680 /// ::= .elseif expression
4681 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4682 if (TheCondState.TheCond != AsmCond::IfCond &&
4683 TheCondState.TheCond != AsmCond::ElseIfCond)
4684 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4685 " .if or an .elseif");
4686 TheCondState.TheCond = AsmCond::ElseIfCond;
4688 bool LastIgnoreState = false;
4689 if (!TheCondStack.empty())
4690 LastIgnoreState = TheCondStack.back().Ignore;
4691 if (LastIgnoreState || TheCondState.CondMet) {
4692 TheCondState.Ignore = true;
4693 eatToEndOfStatement();
4696 if (parseAbsoluteExpression(ExprValue))
4699 if (parseToken(AsmToken::EndOfStatement,
4700 "unexpected token in '.elseif' directive"))
4703 TheCondState.CondMet = ExprValue;
4704 TheCondState.Ignore = !TheCondState.CondMet;
4710 /// parseDirectiveElse
4712 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4713 if (parseToken(AsmToken::EndOfStatement,
4714 "unexpected token in '.else' directive"))
4717 if (TheCondState.TheCond != AsmCond::IfCond &&
4718 TheCondState.TheCond != AsmCond::ElseIfCond)
4719 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4720 " an .if or an .elseif");
4721 TheCondState.TheCond = AsmCond::ElseCond;
4722 bool LastIgnoreState = false;
4723 if (!TheCondStack.empty())
4724 LastIgnoreState = TheCondStack.back().Ignore;
4725 if (LastIgnoreState || TheCondState.CondMet)
4726 TheCondState.Ignore = true;
4728 TheCondState.Ignore = false;
4733 /// parseDirectiveEnd
4735 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4736 if (parseToken(AsmToken::EndOfStatement,
4737 "unexpected token in '.end' directive"))
4740 while (Lexer.isNot(AsmToken::Eof))
4746 /// parseDirectiveError
4748 /// ::= .error [string]
4749 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4750 if (!TheCondStack.empty()) {
4751 if (TheCondStack.back().Ignore) {
4752 eatToEndOfStatement();
4758 return Error(L, ".err encountered");
4760 StringRef Message = ".error directive invoked in source file";
4761 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4762 if (Lexer.isNot(AsmToken::String))
4763 return TokError(".error argument must be a string");
4765 Message = getTok().getStringContents();
4769 return Error(L, Message);
4772 /// parseDirectiveWarning
4773 /// ::= .warning [string]
4774 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4775 if (!TheCondStack.empty()) {
4776 if (TheCondStack.back().Ignore) {
4777 eatToEndOfStatement();
4782 StringRef Message = ".warning directive invoked in source file";
4784 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4785 if (Lexer.isNot(AsmToken::String))
4786 return TokError(".warning argument must be a string");
4788 Message = getTok().getStringContents();
4790 if (parseToken(AsmToken::EndOfStatement,
4791 "expected end of statement in '.warning' directive"))
4795 return Warning(L, Message);
4798 /// parseDirectiveEndIf
4800 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4801 if (parseToken(AsmToken::EndOfStatement,
4802 "unexpected token in '.endif' directive"))
4805 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4806 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4808 if (!TheCondStack.empty()) {
4809 TheCondState = TheCondStack.back();
4810 TheCondStack.pop_back();
4816 void AsmParser::initializeDirectiveKindMap() {
4817 DirectiveKindMap[".set"] = DK_SET;
4818 DirectiveKindMap[".equ"] = DK_EQU;
4819 DirectiveKindMap[".equiv"] = DK_EQUIV;
4820 DirectiveKindMap[".ascii"] = DK_ASCII;
4821 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4822 DirectiveKindMap[".string"] = DK_STRING;
4823 DirectiveKindMap[".byte"] = DK_BYTE;
4824 DirectiveKindMap[".short"] = DK_SHORT;
4825 DirectiveKindMap[".value"] = DK_VALUE;
4826 DirectiveKindMap[".2byte"] = DK_2BYTE;
4827 DirectiveKindMap[".long"] = DK_LONG;
4828 DirectiveKindMap[".int"] = DK_INT;
4829 DirectiveKindMap[".4byte"] = DK_4BYTE;
4830 DirectiveKindMap[".quad"] = DK_QUAD;
4831 DirectiveKindMap[".8byte"] = DK_8BYTE;
4832 DirectiveKindMap[".octa"] = DK_OCTA;
4833 DirectiveKindMap[".single"] = DK_SINGLE;
4834 DirectiveKindMap[".float"] = DK_FLOAT;
4835 DirectiveKindMap[".double"] = DK_DOUBLE;
4836 DirectiveKindMap[".align"] = DK_ALIGN;
4837 DirectiveKindMap[".align32"] = DK_ALIGN32;
4838 DirectiveKindMap[".balign"] = DK_BALIGN;
4839 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4840 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4841 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4842 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4843 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4844 DirectiveKindMap[".org"] = DK_ORG;
4845 DirectiveKindMap[".fill"] = DK_FILL;
4846 DirectiveKindMap[".zero"] = DK_ZERO;
4847 DirectiveKindMap[".extern"] = DK_EXTERN;
4848 DirectiveKindMap[".globl"] = DK_GLOBL;
4849 DirectiveKindMap[".global"] = DK_GLOBAL;
4850 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4851 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4852 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4853 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4854 DirectiveKindMap[".reference"] = DK_REFERENCE;
4855 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4856 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4857 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4858 DirectiveKindMap[".comm"] = DK_COMM;
4859 DirectiveKindMap[".common"] = DK_COMMON;
4860 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4861 DirectiveKindMap[".abort"] = DK_ABORT;
4862 DirectiveKindMap[".include"] = DK_INCLUDE;
4863 DirectiveKindMap[".incbin"] = DK_INCBIN;
4864 DirectiveKindMap[".code16"] = DK_CODE16;
4865 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4866 DirectiveKindMap[".rept"] = DK_REPT;
4867 DirectiveKindMap[".rep"] = DK_REPT;
4868 DirectiveKindMap[".irp"] = DK_IRP;
4869 DirectiveKindMap[".irpc"] = DK_IRPC;
4870 DirectiveKindMap[".endr"] = DK_ENDR;
4871 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4872 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4873 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4874 DirectiveKindMap[".if"] = DK_IF;
4875 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4876 DirectiveKindMap[".ifge"] = DK_IFGE;
4877 DirectiveKindMap[".ifgt"] = DK_IFGT;
4878 DirectiveKindMap[".ifle"] = DK_IFLE;
4879 DirectiveKindMap[".iflt"] = DK_IFLT;
4880 DirectiveKindMap[".ifne"] = DK_IFNE;
4881 DirectiveKindMap[".ifb"] = DK_IFB;
4882 DirectiveKindMap[".ifnb"] = DK_IFNB;
4883 DirectiveKindMap[".ifc"] = DK_IFC;
4884 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4885 DirectiveKindMap[".ifnc"] = DK_IFNC;
4886 DirectiveKindMap[".ifnes"] = DK_IFNES;
4887 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4888 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4889 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4890 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4891 DirectiveKindMap[".else"] = DK_ELSE;
4892 DirectiveKindMap[".end"] = DK_END;
4893 DirectiveKindMap[".endif"] = DK_ENDIF;
4894 DirectiveKindMap[".skip"] = DK_SKIP;
4895 DirectiveKindMap[".space"] = DK_SPACE;
4896 DirectiveKindMap[".file"] = DK_FILE;
4897 DirectiveKindMap[".line"] = DK_LINE;
4898 DirectiveKindMap[".loc"] = DK_LOC;
4899 DirectiveKindMap[".stabs"] = DK_STABS;
4900 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4901 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
4902 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4903 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4904 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
4905 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
4906 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
4907 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4908 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
4909 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4910 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4911 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4912 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4913 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4914 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4915 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4916 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4917 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4918 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4919 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4920 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4921 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4922 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4923 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4924 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4925 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4926 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4927 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4928 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4929 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4930 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4931 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4932 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4933 DirectiveKindMap[".macro"] = DK_MACRO;
4934 DirectiveKindMap[".exitm"] = DK_EXITM;
4935 DirectiveKindMap[".endm"] = DK_ENDM;
4936 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4937 DirectiveKindMap[".purgem"] = DK_PURGEM;
4938 DirectiveKindMap[".err"] = DK_ERR;
4939 DirectiveKindMap[".error"] = DK_ERROR;
4940 DirectiveKindMap[".warning"] = DK_WARNING;
4941 DirectiveKindMap[".reloc"] = DK_RELOC;
4942 DirectiveKindMap[".dc"] = DK_DC;
4943 DirectiveKindMap[".dc.a"] = DK_DC_A;
4944 DirectiveKindMap[".dc.b"] = DK_DC_B;
4945 DirectiveKindMap[".dc.d"] = DK_DC_D;
4946 DirectiveKindMap[".dc.l"] = DK_DC_L;
4947 DirectiveKindMap[".dc.s"] = DK_DC_S;
4948 DirectiveKindMap[".dc.w"] = DK_DC_W;
4949 DirectiveKindMap[".dc.x"] = DK_DC_X;
4950 DirectiveKindMap[".dcb"] = DK_DCB;
4951 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4952 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4953 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4954 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4955 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4956 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
4957 DirectiveKindMap[".ds"] = DK_DS;
4958 DirectiveKindMap[".ds.b"] = DK_DS_B;
4959 DirectiveKindMap[".ds.d"] = DK_DS_D;
4960 DirectiveKindMap[".ds.l"] = DK_DS_L;
4961 DirectiveKindMap[".ds.p"] = DK_DS_P;
4962 DirectiveKindMap[".ds.s"] = DK_DS_S;
4963 DirectiveKindMap[".ds.w"] = DK_DS_W;
4964 DirectiveKindMap[".ds.x"] = DK_DS_X;
4967 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4968 AsmToken EndToken, StartToken = getTok();
4970 unsigned NestLevel = 0;
4972 // Check whether we have reached the end of the file.
4973 if (getLexer().is(AsmToken::Eof)) {
4974 printError(DirectiveLoc, "no matching '.endr' in definition");
4978 if (Lexer.is(AsmToken::Identifier) &&
4979 (getTok().getIdentifier() == ".rept" ||
4980 getTok().getIdentifier() == ".irp" ||
4981 getTok().getIdentifier() == ".irpc")) {
4985 // Otherwise, check whether we have reached the .endr.
4986 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4987 if (NestLevel == 0) {
4988 EndToken = getTok();
4990 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4991 printError(getTok().getLoc(),
4992 "unexpected token in '.endr' directive");
5000 // Otherwise, scan till the end of the statement.
5001 eatToEndOfStatement();
5004 const char *BodyStart = StartToken.getLoc().getPointer();
5005 const char *BodyEnd = EndToken.getLoc().getPointer();
5006 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5008 // We Are Anonymous.
5009 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5010 return &MacroLikeBodies.back();
5013 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5014 raw_svector_ostream &OS) {
5017 std::unique_ptr<MemoryBuffer> Instantiation =
5018 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5020 // Create the macro instantiation object and add to the current macro
5021 // instantiation stack.
5022 MacroInstantiation *MI = new MacroInstantiation(
5023 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5024 ActiveMacros.push_back(MI);
5026 // Jump to the macro instantiation and prime the lexer.
5027 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5028 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5032 /// parseDirectiveRept
5033 /// ::= .rep | .rept count
5034 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5035 const MCExpr *CountExpr;
5036 SMLoc CountLoc = getTok().getLoc();
5037 if (parseExpression(CountExpr))
5041 if (!CountExpr->evaluateAsAbsolute(Count)) {
5042 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5045 if (check(Count < 0, CountLoc, "Count is negative") ||
5046 parseToken(AsmToken::EndOfStatement,
5047 "unexpected token in '" + Dir + "' directive"))
5050 // Lex the rept definition.
5051 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5055 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5056 // to hold the macro body with substitutions.
5057 SmallString<256> Buf;
5058 raw_svector_ostream OS(Buf);
5060 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5061 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5064 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5069 /// parseDirectiveIrp
5070 /// ::= .irp symbol,values
5071 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5072 MCAsmMacroParameter Parameter;
5073 MCAsmMacroArguments A;
5074 if (check(parseIdentifier(Parameter.Name),
5075 "expected identifier in '.irp' directive") ||
5076 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5077 parseMacroArguments(nullptr, A) ||
5078 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5081 // Lex the irp definition.
5082 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5086 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5087 // to hold the macro body with substitutions.
5088 SmallString<256> Buf;
5089 raw_svector_ostream OS(Buf);
5091 for (const MCAsmMacroArgument &Arg : A) {
5092 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5093 // This is undocumented, but GAS seems to support it.
5094 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5098 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5103 /// parseDirectiveIrpc
5104 /// ::= .irpc symbol,values
5105 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5106 MCAsmMacroParameter Parameter;
5107 MCAsmMacroArguments A;
5109 if (check(parseIdentifier(Parameter.Name),
5110 "expected identifier in '.irpc' directive") ||
5111 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5112 parseMacroArguments(nullptr, A))
5115 if (A.size() != 1 || A.front().size() != 1)
5116 return TokError("unexpected token in '.irpc' directive");
5118 // Eat the end of statement.
5119 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5122 // Lex the irpc definition.
5123 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5127 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5128 // to hold the macro body with substitutions.
5129 SmallString<256> Buf;
5130 raw_svector_ostream OS(Buf);
5132 StringRef Values = A.front().front().getString();
5133 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5134 MCAsmMacroArgument Arg;
5135 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5137 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5138 // This is undocumented, but GAS seems to support it.
5139 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5143 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5148 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5149 if (ActiveMacros.empty())
5150 return TokError("unmatched '.endr' directive");
5152 // The only .repl that should get here are the ones created by
5153 // instantiateMacroLikeBody.
5154 assert(getLexer().is(AsmToken::EndOfStatement));
5160 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5162 const MCExpr *Value;
5163 SMLoc ExprLoc = getLexer().getLoc();
5164 if (parseExpression(Value))
5166 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5168 return Error(ExprLoc, "unexpected expression in _emit");
5169 uint64_t IntValue = MCE->getValue();
5170 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5171 return Error(ExprLoc, "literal value out of range for directive");
5173 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5177 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5178 const MCExpr *Value;
5179 SMLoc ExprLoc = getLexer().getLoc();
5180 if (parseExpression(Value))
5182 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5184 return Error(ExprLoc, "unexpected expression in align");
5185 uint64_t IntValue = MCE->getValue();
5186 if (!isPowerOf2_64(IntValue))
5187 return Error(ExprLoc, "literal value not a power of two greater then zero");
5189 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5193 // We are comparing pointers, but the pointers are relative to a single string.
5194 // Thus, this should always be deterministic.
5195 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5196 const AsmRewrite *AsmRewriteB) {
5197 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5199 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5202 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5203 // rewrite to the same location. Make sure the SizeDirective rewrite is
5204 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5205 // ensures the sort algorithm is stable.
5206 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5207 AsmRewritePrecedence[AsmRewriteB->Kind])
5210 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5211 AsmRewritePrecedence[AsmRewriteB->Kind])
5213 llvm_unreachable("Unstable rewrite sort.");
5216 bool AsmParser::parseMSInlineAsm(
5217 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5218 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5219 SmallVectorImpl<std::string> &Constraints,
5220 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5221 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5222 SmallVector<void *, 4> InputDecls;
5223 SmallVector<void *, 4> OutputDecls;
5224 SmallVector<bool, 4> InputDeclsAddressOf;
5225 SmallVector<bool, 4> OutputDeclsAddressOf;
5226 SmallVector<std::string, 4> InputConstraints;
5227 SmallVector<std::string, 4> OutputConstraints;
5228 SmallVector<unsigned, 4> ClobberRegs;
5230 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5235 // While we have input, parse each statement.
5236 unsigned InputIdx = 0;
5237 unsigned OutputIdx = 0;
5238 while (getLexer().isNot(AsmToken::Eof)) {
5239 // Parse curly braces marking block start/end
5240 if (parseCurlyBlockScope(AsmStrRewrites))
5243 ParseStatementInfo Info(&AsmStrRewrites);
5244 bool StatementErr = parseStatement(Info, &SI);
5246 if (StatementErr || Info.ParseError) {
5247 // Emit pending errors if any exist.
5248 printPendingErrors();
5252 // No pending error should exist here.
5253 assert(!hasPendingError() && "unexpected error from parseStatement");
5255 if (Info.Opcode == ~0U)
5258 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5260 // Build the list of clobbers, outputs and inputs.
5261 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5262 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5265 if (Operand.isImm())
5268 // Register operand.
5269 if (Operand.isReg() && !Operand.needAddressOf() &&
5270 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5271 unsigned NumDefs = Desc.getNumDefs();
5273 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5274 ClobberRegs.push_back(Operand.getReg());
5278 // Expr/Input or Output.
5279 StringRef SymName = Operand.getSymName();
5280 if (SymName.empty())
5283 void *OpDecl = Operand.getOpDecl();
5287 bool isOutput = (i == 1) && Desc.mayStore();
5288 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5291 OutputDecls.push_back(OpDecl);
5292 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5293 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5294 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5296 InputDecls.push_back(OpDecl);
5297 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5298 InputConstraints.push_back(Operand.getConstraint().str());
5299 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5303 // Consider implicit defs to be clobbers. Think of cpuid and push.
5304 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5305 Desc.getNumImplicitDefs());
5306 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5309 // Set the number of Outputs and Inputs.
5310 NumOutputs = OutputDecls.size();
5311 NumInputs = InputDecls.size();
5313 // Set the unique clobbers.
5314 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5315 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5317 Clobbers.assign(ClobberRegs.size(), std::string());
5318 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5319 raw_string_ostream OS(Clobbers[I]);
5320 IP->printRegName(OS, ClobberRegs[I]);
5323 // Merge the various outputs and inputs. Output are expected first.
5324 if (NumOutputs || NumInputs) {
5325 unsigned NumExprs = NumOutputs + NumInputs;
5326 OpDecls.resize(NumExprs);
5327 Constraints.resize(NumExprs);
5328 for (unsigned i = 0; i < NumOutputs; ++i) {
5329 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5330 Constraints[i] = OutputConstraints[i];
5332 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5333 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5334 Constraints[j] = InputConstraints[i];
5338 // Build the IR assembly string.
5339 std::string AsmStringIR;
5340 raw_string_ostream OS(AsmStringIR);
5341 StringRef ASMString =
5342 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5343 const char *AsmStart = ASMString.begin();
5344 const char *AsmEnd = ASMString.end();
5345 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5346 for (const AsmRewrite &AR : AsmStrRewrites) {
5347 AsmRewriteKind Kind = AR.Kind;
5348 if (Kind == AOK_Delete)
5351 const char *Loc = AR.Loc.getPointer();
5352 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5354 // Emit everything up to the immediate/expression.
5355 if (unsigned Len = Loc - AsmStart)
5356 OS << StringRef(AsmStart, Len);
5358 // Skip the original expression.
5359 if (Kind == AOK_Skip) {
5360 AsmStart = Loc + AR.Len;
5364 unsigned AdditionalSkip = 0;
5365 // Rewrite expressions in $N notation.
5370 OS << "$$" << AR.Val;
5376 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5379 OS << '$' << InputIdx++;
5382 OS << '$' << OutputIdx++;
5384 case AOK_SizeDirective:
5387 case 8: OS << "byte ptr "; break;
5388 case 16: OS << "word ptr "; break;
5389 case 32: OS << "dword ptr "; break;
5390 case 64: OS << "qword ptr "; break;
5391 case 80: OS << "xword ptr "; break;
5392 case 128: OS << "xmmword ptr "; break;
5393 case 256: OS << "ymmword ptr "; break;
5400 // MS alignment directives are measured in bytes. If the native assembler
5401 // measures alignment in bytes, we can pass it straight through.
5403 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5406 // Alignment is in log2 form, so print that instead and skip the original
5408 unsigned Val = AR.Val;
5410 assert(Val < 10 && "Expected alignment less then 2^10.");
5411 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5417 case AOK_DotOperator:
5418 // Insert the dot if the user omitted it.
5420 if (AsmStringIR.back() != '.')
5424 case AOK_EndOfStatement:
5429 // Skip the original expression.
5430 AsmStart = Loc + AR.Len + AdditionalSkip;
5433 // Emit the remainder of the asm string.
5434 if (AsmStart != AsmEnd)
5435 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5437 AsmString = OS.str();
5442 namespace MCParserUtils {
5444 /// Returns whether the given symbol is used anywhere in the given expression,
5445 /// or subexpressions.
5446 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5447 switch (Value->getKind()) {
5448 case MCExpr::Binary: {
5449 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5450 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5451 isSymbolUsedInExpression(Sym, BE->getRHS());
5453 case MCExpr::Target:
5454 case MCExpr::Constant:
5456 case MCExpr::SymbolRef: {
5458 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5460 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5464 return isSymbolUsedInExpression(
5465 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5468 llvm_unreachable("Unknown expr kind!");
5471 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5472 MCAsmParser &Parser, MCSymbol *&Sym,
5473 const MCExpr *&Value) {
5475 // FIXME: Use better location, we should use proper tokens.
5476 SMLoc EqualLoc = Parser.getTok().getLoc();
5478 if (Parser.parseExpression(Value)) {
5479 return Parser.TokError("missing expression");
5482 // Note: we don't count b as used in "a = b". This is to allow
5486 if (Parser.parseToken(AsmToken::EndOfStatement))
5489 // Validate that the LHS is allowed to be a variable (either it has not been
5490 // used as a symbol, or it is an absolute symbol).
5491 Sym = Parser.getContext().lookupSymbol(Name);
5493 // Diagnose assignment to a label.
5495 // FIXME: Diagnostics. Note the location of the definition as a label.
5496 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5497 if (isSymbolUsedInExpression(Sym, Value))
5498 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5499 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5501 ; // Allow redefinitions of undefined symbols only used in directives.
5502 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5503 ; // Allow redefinitions of variables that haven't yet been used.
5504 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5505 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5506 else if (!Sym->isVariable())
5507 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5508 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5509 return Parser.Error(EqualLoc,
5510 "invalid reassignment of non-absolute variable '" +
5512 } else if (Name == ".") {
5513 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5516 Sym = Parser.getContext().getOrCreateSymbol(Name);
5518 Sym->setRedefinable(allow_redef);
5523 } // end namespace MCParserUtils
5524 } // end namespace llvm
5526 /// \brief Create an MCAsmParser instance.
5527 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5528 MCStreamer &Out, const MCAsmInfo &MAI,
5530 return new AsmParser(SM, C, Out, MAI, CB);