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() = default;
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;
741 // If we are generating dwarf for assembly source files save the initial text
742 // section and generate a .file directive.
743 if (getContext().getGenDwarfForAssembly()) {
744 MCSection *Sec = getStreamer().getCurrentSectionOnly();
745 if (!Sec->getBeginSymbol()) {
746 MCSymbol *SectionStartSym = getContext().createTempSymbol();
747 getStreamer().EmitLabel(SectionStartSym);
748 Sec->setBeginSymbol(SectionStartSym);
750 bool InsertResult = getContext().addGenDwarfSection(Sec);
751 assert(InsertResult && ".text section should not have debug info yet");
753 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
754 0, StringRef(), getContext().getMainFileName()));
757 // While we have input, parse each statement.
758 while (Lexer.isNot(AsmToken::Eof)) {
759 ParseStatementInfo Info;
760 if (!parseStatement(Info, nullptr))
763 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
764 // for printing ErrMsg via Lex() only if no (presumably better) parser error
766 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
770 // parseStatement returned true so may need to emit an error.
771 printPendingErrors();
773 // Skipping to the next line if needed.
774 if (!getLexer().isAtStartOfStatement())
775 eatToEndOfStatement();
778 // All errors should have been emitted.
779 assert(!hasPendingError() && "unexpected error from parseStatement");
781 getTargetParser().flushPendingInstructions(getStreamer());
783 if (TheCondState.TheCond != StartingCondState.TheCond ||
784 TheCondState.Ignore != StartingCondState.Ignore)
785 printError(getTok().getLoc(), "unmatched .ifs or .elses");
786 // Check to see there are no empty DwarfFile slots.
787 const auto &LineTables = getContext().getMCDwarfLineTables();
788 if (!LineTables.empty()) {
790 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
791 if (File.Name.empty() && Index != 0)
792 printError(getTok().getLoc(), "unassigned file number: " +
794 " for .file directives");
799 // Check to see that all assembler local symbols were actually defined.
800 // Targets that don't do subsections via symbols may not want this, though,
801 // so conservatively exclude them. Only do this if we're finalizing, though,
802 // as otherwise we won't necessarilly have seen everything yet.
804 if (MAI.hasSubsectionsViaSymbols()) {
805 for (const auto &TableEntry : getContext().getSymbols()) {
806 MCSymbol *Sym = TableEntry.getValue();
807 // Variable symbols may not be marked as defined, so check those
808 // explicitly. If we know it's a variable, we have a definition for
809 // the purposes of this check.
810 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
811 // FIXME: We would really like to refer back to where the symbol was
812 // first referenced for a source location. We need to add something
813 // to track that. Currently, we just point to the end of the file.
814 printError(getTok().getLoc(), "assembler local symbol '" +
815 Sym->getName() + "' not defined");
819 // Temporary symbols like the ones for directional jumps don't go in the
820 // symbol table. They also need to be diagnosed in all (final) cases.
821 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
822 if (std::get<2>(LocSym)->isUndefined()) {
823 // Reset the state of any "# line file" directives we've seen to the
824 // context as it was at the diagnostic site.
825 CppHashInfo = std::get<1>(LocSym);
826 printError(std::get<0>(LocSym), "directional label undefined");
831 // Finalize the output stream if there are no errors and if the client wants
833 if (!HadError && !NoFinalize)
836 return HadError || getContext().hadError();
839 bool AsmParser::checkForValidSection() {
840 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
841 Out.InitSections(false);
842 return Error(getTok().getLoc(),
843 "expected section directive before assembly directive");
848 /// \brief Throw away the rest of the line for testing purposes.
849 void AsmParser::eatToEndOfStatement() {
850 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
854 if (Lexer.is(AsmToken::EndOfStatement))
858 StringRef AsmParser::parseStringToEndOfStatement() {
859 const char *Start = getTok().getLoc().getPointer();
861 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
864 const char *End = getTok().getLoc().getPointer();
865 return StringRef(Start, End - Start);
868 StringRef AsmParser::parseStringToComma() {
869 const char *Start = getTok().getLoc().getPointer();
871 while (Lexer.isNot(AsmToken::EndOfStatement) &&
872 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
875 const char *End = getTok().getLoc().getPointer();
876 return StringRef(Start, End - Start);
879 /// \brief Parse a paren expression and return it.
880 /// NOTE: This assumes the leading '(' has already been consumed.
882 /// parenexpr ::= expr)
884 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
885 if (parseExpression(Res))
887 if (Lexer.isNot(AsmToken::RParen))
888 return TokError("expected ')' in parentheses expression");
889 EndLoc = Lexer.getTok().getEndLoc();
894 /// \brief Parse a bracket expression and return it.
895 /// NOTE: This assumes the leading '[' has already been consumed.
897 /// bracketexpr ::= expr]
899 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
900 if (parseExpression(Res))
902 EndLoc = getTok().getEndLoc();
903 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
908 /// \brief Parse a primary expression and return it.
909 /// primaryexpr ::= (parenexpr
910 /// primaryexpr ::= symbol
911 /// primaryexpr ::= number
912 /// primaryexpr ::= '.'
913 /// primaryexpr ::= ~,+,- primaryexpr
914 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
915 SMLoc FirstTokenLoc = getLexer().getLoc();
916 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
917 switch (FirstTokenKind) {
919 return TokError("unknown token in expression");
920 // If we have an error assume that we've already handled it.
921 case AsmToken::Error:
923 case AsmToken::Exclaim:
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
929 case AsmToken::Dollar:
931 case AsmToken::String:
932 case AsmToken::Identifier: {
933 StringRef Identifier;
934 if (parseIdentifier(Identifier)) {
935 // We may have failed but $ may be a valid token.
936 if (getTok().is(AsmToken::Dollar)) {
937 if (Lexer.getMAI().getDollarIsPC()) {
939 // This is a '$' reference, which references the current PC. Emit a
940 // temporary label to the streamer and refer to it.
941 MCSymbol *Sym = Ctx.createTempSymbol();
943 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
945 EndLoc = FirstTokenLoc;
948 return Error(FirstTokenLoc, "invalid token in expression");
951 // Parse symbol variant
952 std::pair<StringRef, StringRef> Split;
953 if (!MAI.useParensForSymbolVariant()) {
954 if (FirstTokenKind == AsmToken::String) {
955 if (Lexer.is(AsmToken::At)) {
957 SMLoc AtLoc = getLexer().getLoc();
959 if (parseIdentifier(VName))
960 return Error(AtLoc, "expected symbol variant after '@'");
962 Split = std::make_pair(Identifier, VName);
965 Split = Identifier.split('@');
967 } else if (Lexer.is(AsmToken::LParen)) {
970 parseIdentifier(VName);
972 if (parseToken(AsmToken::RParen,
973 "unexpected token in variant, expected ')'"))
975 Split = std::make_pair(Identifier, VName);
978 EndLoc = SMLoc::getFromPointer(Identifier.end());
980 // This is a symbol reference.
981 StringRef SymbolName = Identifier;
982 if (SymbolName.empty())
985 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
987 // Lookup the symbol variant if used.
988 if (!Split.second.empty()) {
989 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
990 if (Variant != MCSymbolRefExpr::VK_Invalid) {
991 SymbolName = Split.first;
992 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
993 Variant = MCSymbolRefExpr::VK_None;
995 return Error(SMLoc::getFromPointer(Split.second.begin()),
996 "invalid variant '" + Split.second + "'");
1000 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
1002 // If this is an absolute variable reference, substitute it now to preserve
1003 // semantics in the face of reassignment.
1004 if (Sym->isVariable() &&
1005 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
1007 return Error(EndLoc, "unexpected modifier on variable reference");
1009 Res = Sym->getVariableValue(/*SetUsed*/ false);
1013 // Otherwise create a symbol ref.
1014 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1017 case AsmToken::BigNum:
1018 return TokError("literal value out of range for directive");
1019 case AsmToken::Integer: {
1020 SMLoc Loc = getTok().getLoc();
1021 int64_t IntVal = getTok().getIntVal();
1022 Res = MCConstantExpr::create(IntVal, getContext());
1023 EndLoc = Lexer.getTok().getEndLoc();
1024 Lex(); // Eat token.
1025 // Look for 'b' or 'f' following an Integer as a directional label
1026 if (Lexer.getKind() == AsmToken::Identifier) {
1027 StringRef IDVal = getTok().getString();
1028 // Lookup the symbol variant if used.
1029 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1030 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1031 if (Split.first.size() != IDVal.size()) {
1032 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1033 if (Variant == MCSymbolRefExpr::VK_Invalid)
1034 return TokError("invalid variant '" + Split.second + "'");
1035 IDVal = Split.first;
1037 if (IDVal == "f" || IDVal == "b") {
1039 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1040 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1041 if (IDVal == "b" && Sym->isUndefined())
1042 return Error(Loc, "directional label undefined");
1043 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1044 EndLoc = Lexer.getTok().getEndLoc();
1045 Lex(); // Eat identifier.
1050 case AsmToken::Real: {
1051 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1052 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1053 Res = MCConstantExpr::create(IntVal, getContext());
1054 EndLoc = Lexer.getTok().getEndLoc();
1055 Lex(); // Eat token.
1058 case AsmToken::Dot: {
1059 // This is a '.' reference, which references the current PC. Emit a
1060 // temporary label to the streamer and refer to it.
1061 MCSymbol *Sym = Ctx.createTempSymbol();
1063 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1064 EndLoc = Lexer.getTok().getEndLoc();
1065 Lex(); // Eat identifier.
1068 case AsmToken::LParen:
1069 Lex(); // Eat the '('.
1070 return parseParenExpr(Res, EndLoc);
1071 case AsmToken::LBrac:
1072 if (!PlatformParser->HasBracketExpressions())
1073 return TokError("brackets expression not supported on this target");
1074 Lex(); // Eat the '['.
1075 return parseBracketExpr(Res, EndLoc);
1076 case AsmToken::Minus:
1077 Lex(); // Eat the operator.
1078 if (parsePrimaryExpr(Res, EndLoc))
1080 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1082 case AsmToken::Plus:
1083 Lex(); // Eat the operator.
1084 if (parsePrimaryExpr(Res, EndLoc))
1086 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1088 case AsmToken::Tilde:
1089 Lex(); // Eat the operator.
1090 if (parsePrimaryExpr(Res, EndLoc))
1092 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1094 // MIPS unary expression operators. The lexer won't generate these tokens if
1095 // MCAsmInfo::HasMipsExpressions is false for the target.
1096 case AsmToken::PercentCall16:
1097 case AsmToken::PercentCall_Hi:
1098 case AsmToken::PercentCall_Lo:
1099 case AsmToken::PercentDtprel_Hi:
1100 case AsmToken::PercentDtprel_Lo:
1101 case AsmToken::PercentGot:
1102 case AsmToken::PercentGot_Disp:
1103 case AsmToken::PercentGot_Hi:
1104 case AsmToken::PercentGot_Lo:
1105 case AsmToken::PercentGot_Ofst:
1106 case AsmToken::PercentGot_Page:
1107 case AsmToken::PercentGottprel:
1108 case AsmToken::PercentGp_Rel:
1109 case AsmToken::PercentHi:
1110 case AsmToken::PercentHigher:
1111 case AsmToken::PercentHighest:
1112 case AsmToken::PercentLo:
1113 case AsmToken::PercentNeg:
1114 case AsmToken::PercentPcrel_Hi:
1115 case AsmToken::PercentPcrel_Lo:
1116 case AsmToken::PercentTlsgd:
1117 case AsmToken::PercentTlsldm:
1118 case AsmToken::PercentTprel_Hi:
1119 case AsmToken::PercentTprel_Lo:
1120 Lex(); // Eat the operator.
1121 if (Lexer.isNot(AsmToken::LParen))
1122 return TokError("expected '(' after operator");
1123 Lex(); // Eat the operator.
1124 if (parseExpression(Res, EndLoc))
1126 if (Lexer.isNot(AsmToken::RParen))
1127 return TokError("expected ')'");
1128 Lex(); // Eat the operator.
1129 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1134 bool AsmParser::parseExpression(const MCExpr *&Res) {
1136 return parseExpression(Res, EndLoc);
1140 AsmParser::applyModifierToExpr(const MCExpr *E,
1141 MCSymbolRefExpr::VariantKind Variant) {
1142 // Ask the target implementation about this expression first.
1143 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1146 // Recurse over the given expression, rebuilding it to apply the given variant
1147 // if there is exactly one symbol.
1148 switch (E->getKind()) {
1149 case MCExpr::Target:
1150 case MCExpr::Constant:
1153 case MCExpr::SymbolRef: {
1154 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1156 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1157 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1158 "' (already modified)");
1162 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1165 case MCExpr::Unary: {
1166 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1167 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1170 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1173 case MCExpr::Binary: {
1174 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1175 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1176 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1186 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1190 llvm_unreachable("Invalid expression kind!");
1193 /// \brief Parse an expression and return it.
1195 /// expr ::= expr &&,|| expr -> lowest.
1196 /// expr ::= expr |,^,&,! expr
1197 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1198 /// expr ::= expr <<,>> expr
1199 /// expr ::= expr +,- expr
1200 /// expr ::= expr *,/,% expr -> highest.
1201 /// expr ::= primaryexpr
1203 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1204 // Parse the expression.
1206 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1209 // As a special case, we support 'a op b @ modifier' by rewriting the
1210 // expression to include the modifier. This is inefficient, but in general we
1211 // expect users to use 'a@modifier op b'.
1212 if (Lexer.getKind() == AsmToken::At) {
1215 if (Lexer.isNot(AsmToken::Identifier))
1216 return TokError("unexpected symbol modifier following '@'");
1218 MCSymbolRefExpr::VariantKind Variant =
1219 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1220 if (Variant == MCSymbolRefExpr::VK_Invalid)
1221 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1223 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1225 return TokError("invalid modifier '" + getTok().getIdentifier() +
1226 "' (no symbols present)");
1233 // Try to constant fold it up front, if possible.
1235 if (Res->evaluateAsAbsolute(Value))
1236 Res = MCConstantExpr::create(Value, getContext());
1241 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1243 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1246 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1248 if (parseParenExpr(Res, EndLoc))
1251 for (; ParenDepth > 0; --ParenDepth) {
1252 if (parseBinOpRHS(1, Res, EndLoc))
1255 // We don't Lex() the last RParen.
1256 // This is the same behavior as parseParenExpression().
1257 if (ParenDepth - 1 > 0) {
1258 EndLoc = getTok().getEndLoc();
1259 if (parseToken(AsmToken::RParen,
1260 "expected ')' in parentheses expression"))
1267 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1270 SMLoc StartLoc = Lexer.getLoc();
1271 if (parseExpression(Expr))
1274 if (!Expr->evaluateAsAbsolute(Res))
1275 return Error(StartLoc, "expected absolute expression");
1280 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1281 MCBinaryExpr::Opcode &Kind,
1282 bool ShouldUseLogicalShr) {
1285 return 0; // not a binop.
1287 // Lowest Precedence: &&, ||
1288 case AsmToken::AmpAmp:
1289 Kind = MCBinaryExpr::LAnd;
1291 case AsmToken::PipePipe:
1292 Kind = MCBinaryExpr::LOr;
1295 // Low Precedence: |, &, ^
1297 // FIXME: gas seems to support '!' as an infix operator?
1298 case AsmToken::Pipe:
1299 Kind = MCBinaryExpr::Or;
1301 case AsmToken::Caret:
1302 Kind = MCBinaryExpr::Xor;
1305 Kind = MCBinaryExpr::And;
1308 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1309 case AsmToken::EqualEqual:
1310 Kind = MCBinaryExpr::EQ;
1312 case AsmToken::ExclaimEqual:
1313 case AsmToken::LessGreater:
1314 Kind = MCBinaryExpr::NE;
1316 case AsmToken::Less:
1317 Kind = MCBinaryExpr::LT;
1319 case AsmToken::LessEqual:
1320 Kind = MCBinaryExpr::LTE;
1322 case AsmToken::Greater:
1323 Kind = MCBinaryExpr::GT;
1325 case AsmToken::GreaterEqual:
1326 Kind = MCBinaryExpr::GTE;
1329 // Intermediate Precedence: <<, >>
1330 case AsmToken::LessLess:
1331 Kind = MCBinaryExpr::Shl;
1333 case AsmToken::GreaterGreater:
1334 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1337 // High Intermediate Precedence: +, -
1338 case AsmToken::Plus:
1339 Kind = MCBinaryExpr::Add;
1341 case AsmToken::Minus:
1342 Kind = MCBinaryExpr::Sub;
1345 // Highest Precedence: *, /, %
1346 case AsmToken::Star:
1347 Kind = MCBinaryExpr::Mul;
1349 case AsmToken::Slash:
1350 Kind = MCBinaryExpr::Div;
1352 case AsmToken::Percent:
1353 Kind = MCBinaryExpr::Mod;
1358 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1359 MCBinaryExpr::Opcode &Kind,
1360 bool ShouldUseLogicalShr) {
1363 return 0; // not a binop.
1365 // Lowest Precedence: &&, ||
1366 case AsmToken::AmpAmp:
1367 Kind = MCBinaryExpr::LAnd;
1369 case AsmToken::PipePipe:
1370 Kind = MCBinaryExpr::LOr;
1373 // Low Precedence: ==, !=, <>, <, <=, >, >=
1374 case AsmToken::EqualEqual:
1375 Kind = MCBinaryExpr::EQ;
1377 case AsmToken::ExclaimEqual:
1378 case AsmToken::LessGreater:
1379 Kind = MCBinaryExpr::NE;
1381 case AsmToken::Less:
1382 Kind = MCBinaryExpr::LT;
1384 case AsmToken::LessEqual:
1385 Kind = MCBinaryExpr::LTE;
1387 case AsmToken::Greater:
1388 Kind = MCBinaryExpr::GT;
1390 case AsmToken::GreaterEqual:
1391 Kind = MCBinaryExpr::GTE;
1394 // Low Intermediate Precedence: +, -
1395 case AsmToken::Plus:
1396 Kind = MCBinaryExpr::Add;
1398 case AsmToken::Minus:
1399 Kind = MCBinaryExpr::Sub;
1402 // High Intermediate Precedence: |, &, ^
1404 // FIXME: gas seems to support '!' as an infix operator?
1405 case AsmToken::Pipe:
1406 Kind = MCBinaryExpr::Or;
1408 case AsmToken::Caret:
1409 Kind = MCBinaryExpr::Xor;
1412 Kind = MCBinaryExpr::And;
1415 // Highest Precedence: *, /, %, <<, >>
1416 case AsmToken::Star:
1417 Kind = MCBinaryExpr::Mul;
1419 case AsmToken::Slash:
1420 Kind = MCBinaryExpr::Div;
1422 case AsmToken::Percent:
1423 Kind = MCBinaryExpr::Mod;
1425 case AsmToken::LessLess:
1426 Kind = MCBinaryExpr::Shl;
1428 case AsmToken::GreaterGreater:
1429 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1434 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1435 MCBinaryExpr::Opcode &Kind) {
1436 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1437 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1438 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1441 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1442 /// Res contains the LHS of the expression on input.
1443 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1445 SMLoc StartLoc = Lexer.getLoc();
1447 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1448 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1450 // If the next token is lower precedence than we are allowed to eat, return
1451 // successfully with what we ate already.
1452 if (TokPrec < Precedence)
1457 // Eat the next primary expression.
1459 if (parsePrimaryExpr(RHS, EndLoc))
1462 // If BinOp binds less tightly with RHS than the operator after RHS, let
1463 // the pending operator take RHS as its LHS.
1464 MCBinaryExpr::Opcode Dummy;
1465 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1466 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1469 // Merge LHS and RHS according to operator.
1470 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1475 /// ::= EndOfStatement
1476 /// ::= Label* Directive ...Operands... EndOfStatement
1477 /// ::= Label* Identifier OperandList* EndOfStatement
1478 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1479 MCAsmParserSemaCallback *SI) {
1480 assert(!hasPendingError() && "parseStatement started with pending error");
1481 // Eat initial spaces and comments
1482 while (Lexer.is(AsmToken::Space))
1484 if (Lexer.is(AsmToken::EndOfStatement)) {
1485 // if this is a line comment we can drop it safely
1486 if (getTok().getString().front() == '\r' ||
1487 getTok().getString().front() == '\n')
1492 if (Lexer.is(AsmToken::Hash)) {
1493 // Seeing a hash here means that it was an end-of-line comment in
1494 // an asm syntax where hash's are not comment and the previous
1495 // statement parser did not check the end of statement. Relex as
1497 StringRef CommentStr = parseStringToEndOfStatement();
1499 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1502 // Statements always start with an identifier.
1503 AsmToken ID = getTok();
1504 SMLoc IDLoc = ID.getLoc();
1506 int64_t LocalLabelVal = -1;
1507 if (Lexer.is(AsmToken::HashDirective))
1508 return parseCppHashLineFilenameComment(IDLoc);
1509 // Allow an integer followed by a ':' as a directional local label.
1510 if (Lexer.is(AsmToken::Integer)) {
1511 LocalLabelVal = getTok().getIntVal();
1512 if (LocalLabelVal < 0) {
1513 if (!TheCondState.Ignore) {
1514 Lex(); // always eat a token
1515 return Error(IDLoc, "unexpected token at start of statement");
1519 IDVal = getTok().getString();
1520 Lex(); // Consume the integer token to be used as an identifier token.
1521 if (Lexer.getKind() != AsmToken::Colon) {
1522 if (!TheCondState.Ignore) {
1523 Lex(); // always eat a token
1524 return Error(IDLoc, "unexpected token at start of statement");
1528 } else if (Lexer.is(AsmToken::Dot)) {
1529 // Treat '.' as a valid identifier in this context.
1532 } else if (Lexer.is(AsmToken::LCurly)) {
1533 // Treat '{' as a valid identifier in this context.
1537 } else if (Lexer.is(AsmToken::RCurly)) {
1538 // Treat '}' as a valid identifier in this context.
1541 } else if (parseIdentifier(IDVal)) {
1542 if (!TheCondState.Ignore) {
1543 Lex(); // always eat a token
1544 return Error(IDLoc, "unexpected token at start of statement");
1549 // Handle conditional assembly here before checking for skipping. We
1550 // have to do this so that .endif isn't skipped in a ".if 0" block for
1552 StringMap<DirectiveKind>::const_iterator DirKindIt =
1553 DirectiveKindMap.find(IDVal);
1554 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1556 : DirKindIt->getValue();
1567 return parseDirectiveIf(IDLoc, DirKind);
1569 return parseDirectiveIfb(IDLoc, true);
1571 return parseDirectiveIfb(IDLoc, false);
1573 return parseDirectiveIfc(IDLoc, true);
1575 return parseDirectiveIfeqs(IDLoc, true);
1577 return parseDirectiveIfc(IDLoc, false);
1579 return parseDirectiveIfeqs(IDLoc, false);
1581 return parseDirectiveIfdef(IDLoc, true);
1584 return parseDirectiveIfdef(IDLoc, false);
1586 return parseDirectiveElseIf(IDLoc);
1588 return parseDirectiveElse(IDLoc);
1590 return parseDirectiveEndIf(IDLoc);
1593 // Ignore the statement if in the middle of inactive conditional
1595 if (TheCondState.Ignore) {
1596 eatToEndOfStatement();
1600 // FIXME: Recurse on local labels?
1602 // See what kind of statement we have.
1603 switch (Lexer.getKind()) {
1604 case AsmToken::Colon: {
1605 if (!getTargetParser().isLabel(ID))
1607 if (checkForValidSection())
1610 // identifier ':' -> Label.
1613 // Diagnose attempt to use '.' as a label.
1615 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1617 // Diagnose attempt to use a variable as a label.
1619 // FIXME: Diagnostics. Note the location of the definition as a label.
1620 // FIXME: This doesn't diagnose assignment to a symbol which has been
1621 // implicitly marked as external.
1623 if (LocalLabelVal == -1) {
1624 if (ParsingInlineAsm && SI) {
1625 StringRef RewrittenLabel =
1626 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1627 assert(!RewrittenLabel.empty() &&
1628 "We should have an internal name here.");
1629 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1631 IDVal = RewrittenLabel;
1633 Sym = getContext().getOrCreateSymbol(IDVal);
1635 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1636 // End of Labels should be treated as end of line for lexing
1637 // purposes but that information is not available to the Lexer who
1638 // does not understand Labels. This may cause us to see a Hash
1639 // here instead of a preprocessor line comment.
1640 if (getTok().is(AsmToken::Hash)) {
1641 StringRef CommentStr = parseStringToEndOfStatement();
1643 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1646 // Consume any end of statement token, if present, to avoid spurious
1647 // AddBlankLine calls().
1648 if (getTok().is(AsmToken::EndOfStatement)) {
1653 if (!ParsingInlineAsm)
1654 Out.EmitLabel(Sym, IDLoc);
1656 // If we are generating dwarf for assembly source files then gather the
1657 // info to make a dwarf label entry for this label if needed.
1658 if (getContext().getGenDwarfForAssembly())
1659 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1662 getTargetParser().onLabelParsed(Sym);
1667 case AsmToken::Equal:
1668 if (!getTargetParser().equalIsAsmAssignment())
1670 // identifier '=' ... -> assignment statement
1673 return parseAssignment(IDVal, true);
1675 default: // Normal instruction or directive.
1679 // If macros are enabled, check to see if this is a macro instantiation.
1680 if (areMacrosEnabled())
1681 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1682 return handleMacroEntry(M, IDLoc);
1685 // Otherwise, we have a normal instruction or directive.
1687 // Directives start with "."
1688 if (IDVal[0] == '.' && IDVal != ".") {
1689 // There are several entities interested in parsing directives:
1691 // 1. The target-specific assembly parser. Some directives are target
1692 // specific or may potentially behave differently on certain targets.
1693 // 2. Asm parser extensions. For example, platform-specific parsers
1694 // (like the ELF parser) register themselves as extensions.
1695 // 3. The generic directive parser implemented by this class. These are
1696 // all the directives that behave in a target and platform independent
1697 // manner, or at least have a default behavior that's shared between
1698 // all targets and platforms.
1700 getTargetParser().flushPendingInstructions(getStreamer());
1702 SMLoc StartTokLoc = getTok().getLoc();
1703 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1705 if (hasPendingError())
1707 // Currently the return value should be true if we are
1708 // uninterested but as this is at odds with the standard parsing
1709 // convention (return true = error) we have instances of a parsed
1710 // directive that fails returning true as an error. Catch these
1711 // cases as best as possible errors here.
1712 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1714 // Return if we did some parsing or believe we succeeded.
1715 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1718 // Next, check the extension directive map to see if any extension has
1719 // registered itself to parse this directive.
1720 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1721 ExtensionDirectiveMap.lookup(IDVal);
1723 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1725 // Finally, if no one else is interested in this directive, it must be
1726 // generic and familiar to this class.
1732 return parseDirectiveSet(IDVal, true);
1734 return parseDirectiveSet(IDVal, false);
1736 return parseDirectiveAscii(IDVal, false);
1739 return parseDirectiveAscii(IDVal, true);
1742 return parseDirectiveValue(IDVal, 1);
1748 return parseDirectiveValue(IDVal, 2);
1753 return parseDirectiveValue(IDVal, 4);
1756 return parseDirectiveValue(IDVal, 8);
1758 return parseDirectiveValue(
1759 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1761 return parseDirectiveOctaValue(IDVal);
1765 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1768 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1770 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1771 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1774 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1775 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1778 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1780 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1782 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1784 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1786 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1788 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1790 return parseDirectiveOrg();
1792 return parseDirectiveFill();
1794 return parseDirectiveZero();
1796 eatToEndOfStatement(); // .extern is the default, ignore it.
1800 return parseDirectiveSymbolAttribute(MCSA_Global);
1801 case DK_LAZY_REFERENCE:
1802 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1803 case DK_NO_DEAD_STRIP:
1804 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1805 case DK_SYMBOL_RESOLVER:
1806 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1807 case DK_PRIVATE_EXTERN:
1808 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1810 return parseDirectiveSymbolAttribute(MCSA_Reference);
1811 case DK_WEAK_DEFINITION:
1812 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1813 case DK_WEAK_REFERENCE:
1814 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1815 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1816 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1819 return parseDirectiveComm(/*IsLocal=*/false);
1821 return parseDirectiveComm(/*IsLocal=*/true);
1823 return parseDirectiveAbort();
1825 return parseDirectiveInclude();
1827 return parseDirectiveIncbin();
1830 return TokError(Twine(IDVal) +
1831 " not currently supported for this target");
1833 return parseDirectiveRept(IDLoc, IDVal);
1835 return parseDirectiveIrp(IDLoc);
1837 return parseDirectiveIrpc(IDLoc);
1839 return parseDirectiveEndr(IDLoc);
1840 case DK_BUNDLE_ALIGN_MODE:
1841 return parseDirectiveBundleAlignMode();
1842 case DK_BUNDLE_LOCK:
1843 return parseDirectiveBundleLock();
1844 case DK_BUNDLE_UNLOCK:
1845 return parseDirectiveBundleUnlock();
1847 return parseDirectiveLEB128(true);
1849 return parseDirectiveLEB128(false);
1852 return parseDirectiveSpace(IDVal);
1854 return parseDirectiveFile(IDLoc);
1856 return parseDirectiveLine();
1858 return parseDirectiveLoc();
1860 return parseDirectiveStabs();
1862 return parseDirectiveCVFile();
1864 return parseDirectiveCVFuncId();
1865 case DK_CV_INLINE_SITE_ID:
1866 return parseDirectiveCVInlineSiteId();
1868 return parseDirectiveCVLoc();
1869 case DK_CV_LINETABLE:
1870 return parseDirectiveCVLinetable();
1871 case DK_CV_INLINE_LINETABLE:
1872 return parseDirectiveCVInlineLinetable();
1873 case DK_CV_DEF_RANGE:
1874 return parseDirectiveCVDefRange();
1875 case DK_CV_STRINGTABLE:
1876 return parseDirectiveCVStringTable();
1877 case DK_CV_FILECHECKSUMS:
1878 return parseDirectiveCVFileChecksums();
1879 case DK_CFI_SECTIONS:
1880 return parseDirectiveCFISections();
1881 case DK_CFI_STARTPROC:
1882 return parseDirectiveCFIStartProc();
1883 case DK_CFI_ENDPROC:
1884 return parseDirectiveCFIEndProc();
1885 case DK_CFI_DEF_CFA:
1886 return parseDirectiveCFIDefCfa(IDLoc);
1887 case DK_CFI_DEF_CFA_OFFSET:
1888 return parseDirectiveCFIDefCfaOffset();
1889 case DK_CFI_ADJUST_CFA_OFFSET:
1890 return parseDirectiveCFIAdjustCfaOffset();
1891 case DK_CFI_DEF_CFA_REGISTER:
1892 return parseDirectiveCFIDefCfaRegister(IDLoc);
1894 return parseDirectiveCFIOffset(IDLoc);
1895 case DK_CFI_REL_OFFSET:
1896 return parseDirectiveCFIRelOffset(IDLoc);
1897 case DK_CFI_PERSONALITY:
1898 return parseDirectiveCFIPersonalityOrLsda(true);
1900 return parseDirectiveCFIPersonalityOrLsda(false);
1901 case DK_CFI_REMEMBER_STATE:
1902 return parseDirectiveCFIRememberState();
1903 case DK_CFI_RESTORE_STATE:
1904 return parseDirectiveCFIRestoreState();
1905 case DK_CFI_SAME_VALUE:
1906 return parseDirectiveCFISameValue(IDLoc);
1907 case DK_CFI_RESTORE:
1908 return parseDirectiveCFIRestore(IDLoc);
1910 return parseDirectiveCFIEscape();
1911 case DK_CFI_SIGNAL_FRAME:
1912 return parseDirectiveCFISignalFrame();
1913 case DK_CFI_UNDEFINED:
1914 return parseDirectiveCFIUndefined(IDLoc);
1915 case DK_CFI_REGISTER:
1916 return parseDirectiveCFIRegister(IDLoc);
1917 case DK_CFI_WINDOW_SAVE:
1918 return parseDirectiveCFIWindowSave();
1921 return parseDirectiveMacrosOnOff(IDVal);
1923 return parseDirectiveMacro(IDLoc);
1925 return parseDirectiveExitMacro(IDVal);
1928 return parseDirectiveEndMacro(IDVal);
1930 return parseDirectivePurgeMacro(IDLoc);
1932 return parseDirectiveEnd(IDLoc);
1934 return parseDirectiveError(IDLoc, false);
1936 return parseDirectiveError(IDLoc, true);
1938 return parseDirectiveWarning(IDLoc);
1940 return parseDirectiveReloc(IDLoc);
1943 return parseDirectiveDCB(IDVal, 2);
1945 return parseDirectiveDCB(IDVal, 1);
1947 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
1949 return parseDirectiveDCB(IDVal, 4);
1951 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
1954 return TokError(Twine(IDVal) +
1955 " not currently supported for this target");
1958 return parseDirectiveDS(IDVal, 2);
1960 return parseDirectiveDS(IDVal, 1);
1962 return parseDirectiveDS(IDVal, 8);
1965 return parseDirectiveDS(IDVal, 4);
1968 return parseDirectiveDS(IDVal, 12);
1971 return Error(IDLoc, "unknown directive");
1974 // __asm _emit or __asm __emit
1975 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1976 IDVal == "_EMIT" || IDVal == "__EMIT"))
1977 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1980 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1981 return parseDirectiveMSAlign(IDLoc, Info);
1983 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
1984 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1985 if (checkForValidSection())
1988 // Canonicalize the opcode to lower case.
1989 std::string OpcodeStr = IDVal.lower();
1990 ParseInstructionInfo IInfo(Info.AsmRewrites);
1991 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1992 Info.ParsedOperands);
1993 Info.ParseError = ParseHadError;
1995 // Dump the parsed representation, if requested.
1996 if (getShowParsedOperands()) {
1997 SmallString<256> Str;
1998 raw_svector_ostream OS(Str);
1999 OS << "parsed instruction: [";
2000 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2003 Info.ParsedOperands[i]->print(OS);
2007 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2010 // Fail even if ParseInstruction erroneously returns false.
2011 if (hasPendingError() || ParseHadError)
2014 // If we are generating dwarf for the current section then generate a .loc
2015 // directive for the instruction.
2016 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
2017 getContext().getGenDwarfSectionSyms().count(
2018 getStreamer().getCurrentSectionOnly())) {
2020 if (ActiveMacros.empty())
2021 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2023 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2024 ActiveMacros.front()->ExitBuffer);
2026 // If we previously parsed a cpp hash file line comment then make sure the
2027 // current Dwarf File is for the CppHashFilename if not then emit the
2028 // Dwarf File table for it and adjust the line number for the .loc.
2029 if (!CppHashInfo.Filename.empty()) {
2030 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2031 0, StringRef(), CppHashInfo.Filename);
2032 getContext().setGenDwarfFileNumber(FileNumber);
2034 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2035 // cache with the different Loc from the call above we save the last
2036 // info we queried here with SrcMgr.FindLineNumber().
2037 unsigned CppHashLocLineNo;
2038 if (LastQueryIDLoc == CppHashInfo.Loc &&
2039 LastQueryBuffer == CppHashInfo.Buf)
2040 CppHashLocLineNo = LastQueryLine;
2043 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2044 LastQueryLine = CppHashLocLineNo;
2045 LastQueryIDLoc = CppHashInfo.Loc;
2046 LastQueryBuffer = CppHashInfo.Buf;
2048 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2051 getStreamer().EmitDwarfLocDirective(
2052 getContext().getGenDwarfFileNumber(), Line, 0,
2053 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2057 // If parsing succeeded, match the instruction.
2058 if (!ParseHadError) {
2060 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2061 Info.ParsedOperands, Out,
2062 ErrorInfo, ParsingInlineAsm))
2068 // Parse and erase curly braces marking block start/end
2070 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2071 // Identify curly brace marking block start/end
2072 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2075 SMLoc StartLoc = Lexer.getLoc();
2076 Lex(); // Eat the brace
2077 if (Lexer.is(AsmToken::EndOfStatement))
2078 Lex(); // Eat EndOfStatement following the brace
2080 // Erase the block start/end brace from the output asm string
2081 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2082 StartLoc.getPointer());
2086 /// parseCppHashLineFilenameComment as this:
2087 /// ::= # number "filename"
2088 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2089 Lex(); // Eat the hash token.
2090 // Lexer only ever emits HashDirective if it fully formed if it's
2091 // done the checking already so this is an internal error.
2092 assert(getTok().is(AsmToken::Integer) &&
2093 "Lexing Cpp line comment: Expected Integer");
2094 int64_t LineNumber = getTok().getIntVal();
2096 assert(getTok().is(AsmToken::String) &&
2097 "Lexing Cpp line comment: Expected String");
2098 StringRef Filename = getTok().getString();
2101 // Get rid of the enclosing quotes.
2102 Filename = Filename.substr(1, Filename.size() - 2);
2104 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2105 CppHashInfo.Loc = L;
2106 CppHashInfo.Filename = Filename;
2107 CppHashInfo.LineNumber = LineNumber;
2108 CppHashInfo.Buf = CurBuffer;
2112 /// \brief will use the last parsed cpp hash line filename comment
2113 /// for the Filename and LineNo if any in the diagnostic.
2114 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2115 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2116 raw_ostream &OS = errs();
2118 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2119 SMLoc DiagLoc = Diag.getLoc();
2120 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2121 unsigned CppHashBuf =
2122 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2124 // Like SourceMgr::printMessage() we need to print the include stack if any
2125 // before printing the message.
2126 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2127 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2128 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2129 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2130 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2133 // If we have not parsed a cpp hash line filename comment or the source
2134 // manager changed or buffer changed (like in a nested include) then just
2135 // print the normal diagnostic using its Filename and LineNo.
2136 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2137 DiagBuf != CppHashBuf) {
2138 if (Parser->SavedDiagHandler)
2139 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2141 Diag.print(nullptr, OS);
2145 // Use the CppHashFilename and calculate a line number based on the
2146 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2147 // for the diagnostic.
2148 const std::string &Filename = Parser->CppHashInfo.Filename;
2150 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2151 int CppHashLocLineNo =
2152 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2154 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2156 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2157 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2158 Diag.getLineContents(), Diag.getRanges());
2160 if (Parser->SavedDiagHandler)
2161 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2163 NewDiag.print(nullptr, OS);
2166 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2167 // difference being that that function accepts '@' as part of identifiers and
2168 // we can't do that. AsmLexer.cpp should probably be changed to handle
2169 // '@' as a special case when needed.
2170 static bool isIdentifierChar(char c) {
2171 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2175 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2176 ArrayRef<MCAsmMacroParameter> Parameters,
2177 ArrayRef<MCAsmMacroArgument> A,
2178 bool EnableAtPseudoVariable, SMLoc L) {
2179 unsigned NParameters = Parameters.size();
2180 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2181 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2182 return Error(L, "Wrong number of arguments");
2184 // A macro without parameters is handled differently on Darwin:
2185 // gas accepts no arguments and does no substitutions
2186 while (!Body.empty()) {
2187 // Scan for the next substitution.
2188 std::size_t End = Body.size(), Pos = 0;
2189 for (; Pos != End; ++Pos) {
2190 // Check for a substitution or escape.
2191 if (IsDarwin && !NParameters) {
2192 // This macro has no parameters, look for $0, $1, etc.
2193 if (Body[Pos] != '$' || Pos + 1 == End)
2196 char Next = Body[Pos + 1];
2197 if (Next == '$' || Next == 'n' ||
2198 isdigit(static_cast<unsigned char>(Next)))
2201 // This macro has parameters, look for \foo, \bar, etc.
2202 if (Body[Pos] == '\\' && Pos + 1 != End)
2208 OS << Body.slice(0, Pos);
2210 // Check if we reached the end.
2214 if (IsDarwin && !NParameters) {
2215 switch (Body[Pos + 1]) {
2221 // $n => number of arguments
2226 // $[0-9] => argument
2228 // Missing arguments are ignored.
2229 unsigned Index = Body[Pos + 1] - '0';
2230 if (Index >= A.size())
2233 // Otherwise substitute with the token values, with spaces eliminated.
2234 for (const AsmToken &Token : A[Index])
2235 OS << Token.getString();
2241 unsigned I = Pos + 1;
2243 // Check for the \@ pseudo-variable.
2244 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2247 while (isIdentifierChar(Body[I]) && I + 1 != End)
2250 const char *Begin = Body.data() + Pos + 1;
2251 StringRef Argument(Begin, I - (Pos + 1));
2254 if (Argument == "@") {
2255 OS << NumOfMacroInstantiations;
2258 for (; Index < NParameters; ++Index)
2259 if (Parameters[Index].Name == Argument)
2262 if (Index == NParameters) {
2263 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2266 OS << '\\' << Argument;
2270 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2271 for (const AsmToken &Token : A[Index])
2272 // We expect no quotes around the string's contents when
2273 // parsing for varargs.
2274 if (Token.getKind() != AsmToken::String || VarargParameter)
2275 OS << Token.getString();
2277 OS << Token.getStringContents();
2279 Pos += 1 + Argument.size();
2283 // Update the scan point.
2284 Body = Body.substr(Pos);
2290 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2291 size_t CondStackDepth)
2292 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2293 CondStackDepth(CondStackDepth) {}
2295 static bool isOperator(AsmToken::TokenKind kind) {
2299 case AsmToken::Plus:
2300 case AsmToken::Minus:
2301 case AsmToken::Tilde:
2302 case AsmToken::Slash:
2303 case AsmToken::Star:
2305 case AsmToken::Equal:
2306 case AsmToken::EqualEqual:
2307 case AsmToken::Pipe:
2308 case AsmToken::PipePipe:
2309 case AsmToken::Caret:
2311 case AsmToken::AmpAmp:
2312 case AsmToken::Exclaim:
2313 case AsmToken::ExclaimEqual:
2314 case AsmToken::Less:
2315 case AsmToken::LessEqual:
2316 case AsmToken::LessLess:
2317 case AsmToken::LessGreater:
2318 case AsmToken::Greater:
2319 case AsmToken::GreaterEqual:
2320 case AsmToken::GreaterGreater:
2327 class AsmLexerSkipSpaceRAII {
2329 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2330 Lexer.setSkipSpace(SkipSpace);
2333 ~AsmLexerSkipSpaceRAII() {
2334 Lexer.setSkipSpace(true);
2341 } // end anonymous namespace
2343 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2346 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2347 StringRef Str = parseStringToEndOfStatement();
2348 MA.emplace_back(AsmToken::String, Str);
2353 unsigned ParenLevel = 0;
2355 // Darwin doesn't use spaces to delmit arguments.
2356 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2362 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2363 return TokError("unexpected token in macro instantiation");
2365 if (ParenLevel == 0) {
2367 if (Lexer.is(AsmToken::Comma))
2370 if (Lexer.is(AsmToken::Space)) {
2372 Lexer.Lex(); // Eat spaces
2375 // Spaces can delimit parameters, but could also be part an expression.
2376 // If the token after a space is an operator, add the token and the next
2377 // one into this argument
2379 if (isOperator(Lexer.getKind())) {
2380 MA.push_back(getTok());
2383 // Whitespace after an operator can be ignored.
2384 if (Lexer.is(AsmToken::Space))
2394 // handleMacroEntry relies on not advancing the lexer here
2395 // to be able to fill in the remaining default parameter values
2396 if (Lexer.is(AsmToken::EndOfStatement))
2399 // Adjust the current parentheses level.
2400 if (Lexer.is(AsmToken::LParen))
2402 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2405 // Append the token to the current argument list.
2406 MA.push_back(getTok());
2410 if (ParenLevel != 0)
2411 return TokError("unbalanced parentheses in macro argument");
2415 // Parse the macro instantiation arguments.
2416 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2417 MCAsmMacroArguments &A) {
2418 const unsigned NParameters = M ? M->Parameters.size() : 0;
2419 bool NamedParametersFound = false;
2420 SmallVector<SMLoc, 4> FALocs;
2422 A.resize(NParameters);
2423 FALocs.resize(NParameters);
2425 // Parse two kinds of macro invocations:
2426 // - macros defined without any parameters accept an arbitrary number of them
2427 // - macros defined with parameters accept at most that many of them
2428 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2429 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2431 SMLoc IDLoc = Lexer.getLoc();
2432 MCAsmMacroParameter FA;
2434 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2435 if (parseIdentifier(FA.Name))
2436 return Error(IDLoc, "invalid argument identifier for formal argument");
2438 if (Lexer.isNot(AsmToken::Equal))
2439 return TokError("expected '=' after formal parameter identifier");
2443 NamedParametersFound = true;
2446 if (NamedParametersFound && FA.Name.empty())
2447 return Error(IDLoc, "cannot mix positional and keyword arguments");
2449 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2450 if (parseMacroArgument(FA.Value, Vararg))
2453 unsigned PI = Parameter;
2454 if (!FA.Name.empty()) {
2456 for (FAI = 0; FAI < NParameters; ++FAI)
2457 if (M->Parameters[FAI].Name == FA.Name)
2460 if (FAI >= NParameters) {
2461 assert(M && "expected macro to be defined");
2462 return Error(IDLoc, "parameter named '" + FA.Name +
2463 "' does not exist for macro '" + M->Name + "'");
2468 if (!FA.Value.empty()) {
2473 if (FALocs.size() <= PI)
2474 FALocs.resize(PI + 1);
2476 FALocs[PI] = Lexer.getLoc();
2479 // At the end of the statement, fill in remaining arguments that have
2480 // default values. If there aren't any, then the next argument is
2481 // required but missing
2482 if (Lexer.is(AsmToken::EndOfStatement)) {
2483 bool Failure = false;
2484 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2485 if (A[FAI].empty()) {
2486 if (M->Parameters[FAI].Required) {
2487 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2488 "missing value for required parameter "
2489 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2493 if (!M->Parameters[FAI].Value.empty())
2494 A[FAI] = M->Parameters[FAI].Value;
2500 if (Lexer.is(AsmToken::Comma))
2504 return TokError("too many positional arguments");
2507 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2508 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2509 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2512 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2513 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2516 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2518 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2519 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2520 // eliminate this, although we should protect against infinite loops.
2521 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2522 if (ActiveMacros.size() == MaxNestingDepth) {
2523 std::ostringstream MaxNestingDepthError;
2524 MaxNestingDepthError << "macros cannot be nested more than "
2525 << MaxNestingDepth << " levels deep."
2526 << " Use -asm-macro-max-nesting-depth to increase "
2528 return TokError(MaxNestingDepthError.str());
2531 MCAsmMacroArguments A;
2532 if (parseMacroArguments(M, A))
2535 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2536 // to hold the macro body with substitutions.
2537 SmallString<256> Buf;
2538 StringRef Body = M->Body;
2539 raw_svector_ostream OS(Buf);
2541 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2544 // We include the .endmacro in the buffer as our cue to exit the macro
2546 OS << ".endmacro\n";
2548 std::unique_ptr<MemoryBuffer> Instantiation =
2549 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2551 // Create the macro instantiation object and add to the current macro
2552 // instantiation stack.
2553 MacroInstantiation *MI = new MacroInstantiation(
2554 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2555 ActiveMacros.push_back(MI);
2557 ++NumOfMacroInstantiations;
2559 // Jump to the macro instantiation and prime the lexer.
2560 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2567 void AsmParser::handleMacroExit() {
2568 // Jump to the EndOfStatement we should return to, and consume it.
2569 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2572 // Pop the instantiation entry.
2573 delete ActiveMacros.back();
2574 ActiveMacros.pop_back();
2577 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2580 const MCExpr *Value;
2581 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2586 // In the case where we parse an expression starting with a '.', we will
2587 // not generate an error, nor will we create a symbol. In this case we
2588 // should just return out.
2592 // Do the assignment.
2593 Out.EmitAssignment(Sym, Value);
2595 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2600 /// parseIdentifier:
2603 bool AsmParser::parseIdentifier(StringRef &Res) {
2604 // The assembler has relaxed rules for accepting identifiers, in particular we
2605 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2606 // separate tokens. At this level, we have already lexed so we cannot (currently)
2607 // handle this as a context dependent token, instead we detect adjacent tokens
2608 // and return the combined identifier.
2609 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2610 SMLoc PrefixLoc = getLexer().getLoc();
2612 // Consume the prefix character, and check for a following identifier.
2615 Lexer.peekTokens(Buf, false);
2617 if (Buf[0].isNot(AsmToken::Identifier))
2620 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2621 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2625 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2626 // Construct the joined identifier and consume the token.
2628 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2629 Lex(); // Parser Lex to maintain invariants.
2633 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2636 Res = getTok().getIdentifier();
2638 Lex(); // Consume the identifier token.
2643 /// parseDirectiveSet:
2644 /// ::= .equ identifier ',' expression
2645 /// ::= .equiv identifier ',' expression
2646 /// ::= .set identifier ',' expression
2647 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2649 if (check(parseIdentifier(Name), "expected identifier") ||
2650 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2651 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2655 bool AsmParser::parseEscapedString(std::string &Data) {
2656 if (check(getTok().isNot(AsmToken::String), "expected string"))
2660 StringRef Str = getTok().getStringContents();
2661 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2662 if (Str[i] != '\\') {
2667 // Recognize escaped characters. Note that this escape semantics currently
2668 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2671 return TokError("unexpected backslash at end of string");
2673 // Recognize octal sequences.
2674 if ((unsigned)(Str[i] - '0') <= 7) {
2675 // Consume up to three octal characters.
2676 unsigned Value = Str[i] - '0';
2678 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2680 Value = Value * 8 + (Str[i] - '0');
2682 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2684 Value = Value * 8 + (Str[i] - '0');
2689 return TokError("invalid octal escape sequence (out of range)");
2691 Data += (unsigned char)Value;
2695 // Otherwise recognize individual escapes.
2698 // Just reject invalid escape sequences for now.
2699 return TokError("invalid escape sequence (unrecognized character)");
2701 case 'b': Data += '\b'; break;
2702 case 'f': Data += '\f'; break;
2703 case 'n': Data += '\n'; break;
2704 case 'r': Data += '\r'; break;
2705 case 't': Data += '\t'; break;
2706 case '"': Data += '"'; break;
2707 case '\\': Data += '\\'; break;
2715 /// parseDirectiveAscii:
2716 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2717 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2718 auto parseOp = [&]() -> bool {
2720 if (checkForValidSection() || parseEscapedString(Data))
2722 getStreamer().EmitBytes(Data);
2724 getStreamer().EmitBytes(StringRef("\0", 1));
2728 if (parseMany(parseOp))
2729 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2733 /// parseDirectiveReloc
2734 /// ::= .reloc expression , identifier [ , expression ]
2735 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2736 const MCExpr *Offset;
2737 const MCExpr *Expr = nullptr;
2739 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2740 int64_t OffsetValue;
2741 // We can only deal with constant expressions at the moment.
2743 if (parseExpression(Offset))
2746 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2747 "expression is not a constant value") ||
2748 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2749 parseToken(AsmToken::Comma, "expected comma") ||
2750 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2753 SMLoc NameLoc = Lexer.getTok().getLoc();
2754 StringRef Name = Lexer.getTok().getIdentifier();
2757 if (Lexer.is(AsmToken::Comma)) {
2759 SMLoc ExprLoc = Lexer.getLoc();
2760 if (parseExpression(Expr))
2764 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2765 return Error(ExprLoc, "expression must be relocatable");
2768 if (parseToken(AsmToken::EndOfStatement,
2769 "unexpected token in .reloc directive"))
2772 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2773 return Error(NameLoc, "unknown relocation name");
2778 /// parseDirectiveValue
2779 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2780 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2781 auto parseOp = [&]() -> bool {
2782 const MCExpr *Value;
2783 SMLoc ExprLoc = getLexer().getLoc();
2784 if (checkForValidSection() || parseExpression(Value))
2786 // Special case constant expressions to match code generator.
2787 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2788 assert(Size <= 8 && "Invalid size");
2789 uint64_t IntValue = MCE->getValue();
2790 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2791 return Error(ExprLoc, "out of range literal value");
2792 getStreamer().EmitIntValue(IntValue, Size);
2794 getStreamer().EmitValue(Value, Size, ExprLoc);
2798 if (parseMany(parseOp))
2799 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2803 /// ParseDirectiveOctaValue
2804 /// ::= .octa [ hexconstant (, hexconstant)* ]
2806 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2807 auto parseOp = [&]() -> bool {
2808 if (checkForValidSection())
2810 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2811 return TokError("unknown token in expression");
2812 SMLoc ExprLoc = getTok().getLoc();
2813 APInt IntValue = getTok().getAPIntVal();
2816 if (!IntValue.isIntN(128))
2817 return Error(ExprLoc, "out of range literal value");
2818 if (!IntValue.isIntN(64)) {
2819 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2820 lo = IntValue.getLoBits(64).getZExtValue();
2823 lo = IntValue.getZExtValue();
2825 if (MAI.isLittleEndian()) {
2826 getStreamer().EmitIntValue(lo, 8);
2827 getStreamer().EmitIntValue(hi, 8);
2829 getStreamer().EmitIntValue(hi, 8);
2830 getStreamer().EmitIntValue(lo, 8);
2835 if (parseMany(parseOp))
2836 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2840 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2841 // We don't truly support arithmetic on floating point expressions, so we
2842 // have to manually parse unary prefixes.
2844 if (getLexer().is(AsmToken::Minus)) {
2847 } else if (getLexer().is(AsmToken::Plus))
2850 if (Lexer.is(AsmToken::Error))
2851 return TokError(Lexer.getErr());
2852 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2853 Lexer.isNot(AsmToken::Identifier))
2854 return TokError("unexpected token in directive");
2856 // Convert to an APFloat.
2857 APFloat Value(Semantics);
2858 StringRef IDVal = getTok().getString();
2859 if (getLexer().is(AsmToken::Identifier)) {
2860 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2861 Value = APFloat::getInf(Semantics);
2862 else if (!IDVal.compare_lower("nan"))
2863 Value = APFloat::getNaN(Semantics, false, ~0);
2865 return TokError("invalid floating point literal");
2866 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2867 APFloat::opInvalidOp)
2868 return TokError("invalid floating point literal");
2872 // Consume the numeric token.
2875 Res = Value.bitcastToAPInt();
2880 /// parseDirectiveRealValue
2881 /// ::= (.single | .double) [ expression (, expression)* ]
2882 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2883 const fltSemantics &Semantics) {
2884 auto parseOp = [&]() -> bool {
2886 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
2888 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2889 AsInt.getBitWidth() / 8);
2893 if (parseMany(parseOp))
2894 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2898 /// parseDirectiveZero
2899 /// ::= .zero expression
2900 bool AsmParser::parseDirectiveZero() {
2901 SMLoc NumBytesLoc = Lexer.getLoc();
2902 const MCExpr *NumBytes;
2903 if (checkForValidSection() || parseExpression(NumBytes))
2907 if (getLexer().is(AsmToken::Comma)) {
2909 if (parseAbsoluteExpression(Val))
2913 if (parseToken(AsmToken::EndOfStatement,
2914 "unexpected token in '.zero' directive"))
2916 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
2921 /// parseDirectiveFill
2922 /// ::= .fill expression [ , expression [ , expression ] ]
2923 bool AsmParser::parseDirectiveFill() {
2924 SMLoc NumValuesLoc = Lexer.getLoc();
2925 const MCExpr *NumValues;
2926 if (checkForValidSection() || parseExpression(NumValues))
2929 int64_t FillSize = 1;
2930 int64_t FillExpr = 0;
2932 SMLoc SizeLoc, ExprLoc;
2934 if (parseOptionalToken(AsmToken::Comma)) {
2935 SizeLoc = getTok().getLoc();
2936 if (parseAbsoluteExpression(FillSize))
2938 if (parseOptionalToken(AsmToken::Comma)) {
2939 ExprLoc = getTok().getLoc();
2940 if (parseAbsoluteExpression(FillExpr))
2944 if (parseToken(AsmToken::EndOfStatement,
2945 "unexpected token in '.fill' directive"))
2949 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2953 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2957 if (!isUInt<32>(FillExpr) && FillSize > 4)
2958 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2960 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
2965 /// parseDirectiveOrg
2966 /// ::= .org expression [ , expression ]
2967 bool AsmParser::parseDirectiveOrg() {
2968 const MCExpr *Offset;
2969 SMLoc OffsetLoc = Lexer.getLoc();
2970 if (checkForValidSection() || parseExpression(Offset))
2973 // Parse optional fill expression.
2974 int64_t FillExpr = 0;
2975 if (parseOptionalToken(AsmToken::Comma))
2976 if (parseAbsoluteExpression(FillExpr))
2977 return addErrorSuffix(" in '.org' directive");
2978 if (parseToken(AsmToken::EndOfStatement))
2979 return addErrorSuffix(" in '.org' directive");
2981 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
2985 /// parseDirectiveAlign
2986 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2987 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2988 SMLoc AlignmentLoc = getLexer().getLoc();
2991 bool HasFillExpr = false;
2992 int64_t FillExpr = 0;
2993 int64_t MaxBytesToFill = 0;
2995 auto parseAlign = [&]() -> bool {
2996 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
2998 if (parseOptionalToken(AsmToken::Comma)) {
2999 // The fill expression can be omitted while specifying a maximum number of
3000 // alignment bytes, e.g:
3002 if (getTok().isNot(AsmToken::Comma)) {
3004 if (parseAbsoluteExpression(FillExpr))
3007 if (parseOptionalToken(AsmToken::Comma))
3008 if (parseTokenLoc(MaxBytesLoc) ||
3009 parseAbsoluteExpression(MaxBytesToFill))
3012 return parseToken(AsmToken::EndOfStatement);
3016 return addErrorSuffix(" in directive");
3018 // Always emit an alignment here even if we thrown an error.
3019 bool ReturnVal = false;
3021 // Compute alignment in bytes.
3023 // FIXME: Diagnose overflow.
3024 if (Alignment >= 32) {
3025 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3029 Alignment = 1ULL << Alignment;
3031 // Reject alignments that aren't either a power of two or zero,
3032 // for gas compatibility. Alignment of zero is silently rounded
3036 if (!isPowerOf2_64(Alignment))
3037 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3040 // Diagnose non-sensical max bytes to align.
3041 if (MaxBytesLoc.isValid()) {
3042 if (MaxBytesToFill < 1) {
3043 ReturnVal |= Error(MaxBytesLoc,
3044 "alignment directive can never be satisfied in this "
3045 "many bytes, ignoring maximum bytes expression");
3049 if (MaxBytesToFill >= Alignment) {
3050 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3056 // Check whether we should use optimal code alignment for this .align
3058 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3059 assert(Section && "must have section to emit alignment");
3060 bool UseCodeAlign = Section->UseCodeAlign();
3061 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3062 ValueSize == 1 && UseCodeAlign) {
3063 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3065 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3066 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3073 /// parseDirectiveFile
3074 /// ::= .file [number] filename
3075 /// ::= .file number directory filename
3076 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3077 // FIXME: I'm not sure what this is.
3078 int64_t FileNumber = -1;
3079 SMLoc FileNumberLoc = getLexer().getLoc();
3080 if (getLexer().is(AsmToken::Integer)) {
3081 FileNumber = getTok().getIntVal();
3085 return TokError("file number less than one");
3088 std::string Path = getTok().getString();
3090 // Usually the directory and filename together, otherwise just the directory.
3091 // Allow the strings to have escaped octal character sequence.
3092 if (check(getTok().isNot(AsmToken::String),
3093 "unexpected token in '.file' directive") ||
3094 parseEscapedString(Path))
3097 StringRef Directory;
3099 std::string FilenameData;
3100 if (getLexer().is(AsmToken::String)) {
3101 if (check(FileNumber == -1,
3102 "explicit path specified, but no file number") ||
3103 parseEscapedString(FilenameData))
3105 Filename = FilenameData;
3111 if (parseToken(AsmToken::EndOfStatement,
3112 "unexpected token in '.file' directive"))
3115 if (FileNumber == -1)
3116 getStreamer().EmitFileDirective(Filename);
3118 // If there is -g option as well as debug info from directive file,
3119 // we turn off -g option, directly use the existing debug info instead.
3120 if (getContext().getGenDwarfForAssembly())
3121 getContext().setGenDwarfForAssembly(false);
3122 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3124 return Error(FileNumberLoc, "file number already allocated");
3130 /// parseDirectiveLine
3131 /// ::= .line [number]
3132 bool AsmParser::parseDirectiveLine() {
3134 if (getLexer().is(AsmToken::Integer)) {
3135 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3138 // FIXME: Do something with the .line.
3140 if (parseToken(AsmToken::EndOfStatement,
3141 "unexpected token in '.line' directive"))
3147 /// parseDirectiveLoc
3148 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3149 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3150 /// The first number is a file number, must have been previously assigned with
3151 /// a .file directive, the second number is the line number and optionally the
3152 /// third number is a column position (zero if not specified). The remaining
3153 /// optional items are .loc sub-directives.
3154 bool AsmParser::parseDirectiveLoc() {
3155 int64_t FileNumber = 0, LineNumber = 0;
3156 SMLoc Loc = getTok().getLoc();
3157 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3158 check(FileNumber < 1, Loc,
3159 "file number less than one in '.loc' directive") ||
3160 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3161 "unassigned file number in '.loc' directive"))
3165 if (getLexer().is(AsmToken::Integer)) {
3166 LineNumber = getTok().getIntVal();
3168 return TokError("line number less than zero in '.loc' directive");
3172 int64_t ColumnPos = 0;
3173 if (getLexer().is(AsmToken::Integer)) {
3174 ColumnPos = getTok().getIntVal();
3176 return TokError("column position less than zero in '.loc' directive");
3180 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3182 int64_t Discriminator = 0;
3184 auto parseLocOp = [&]() -> bool {
3186 SMLoc Loc = getTok().getLoc();
3187 if (parseIdentifier(Name))
3188 return TokError("unexpected token in '.loc' directive");
3190 if (Name == "basic_block")
3191 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3192 else if (Name == "prologue_end")
3193 Flags |= DWARF2_FLAG_PROLOGUE_END;
3194 else if (Name == "epilogue_begin")
3195 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3196 else if (Name == "is_stmt") {
3197 Loc = getTok().getLoc();
3198 const MCExpr *Value;
3199 if (parseExpression(Value))
3201 // The expression must be the constant 0 or 1.
3202 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3203 int Value = MCE->getValue();
3205 Flags &= ~DWARF2_FLAG_IS_STMT;
3206 else if (Value == 1)
3207 Flags |= DWARF2_FLAG_IS_STMT;
3209 return Error(Loc, "is_stmt value not 0 or 1");
3211 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3213 } else if (Name == "isa") {
3214 Loc = getTok().getLoc();
3215 const MCExpr *Value;
3216 if (parseExpression(Value))
3218 // The expression must be a constant greater or equal to 0.
3219 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3220 int Value = MCE->getValue();
3222 return Error(Loc, "isa number less than zero");
3225 return Error(Loc, "isa number not a constant value");
3227 } else if (Name == "discriminator") {
3228 if (parseAbsoluteExpression(Discriminator))
3231 return Error(Loc, "unknown sub-directive in '.loc' directive");
3236 if (parseMany(parseLocOp, false /*hasComma*/))
3239 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3240 Isa, Discriminator, StringRef());
3245 /// parseDirectiveStabs
3246 /// ::= .stabs string, number, number, number
3247 bool AsmParser::parseDirectiveStabs() {
3248 return TokError("unsupported directive '.stabs'");
3251 /// parseDirectiveCVFile
3252 /// ::= .cv_file number filename
3253 bool AsmParser::parseDirectiveCVFile() {
3254 SMLoc FileNumberLoc = getTok().getLoc();
3256 std::string Filename;
3258 if (parseIntToken(FileNumber,
3259 "expected file number in '.cv_file' directive") ||
3260 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3261 check(getTok().isNot(AsmToken::String),
3262 "unexpected token in '.cv_file' directive") ||
3263 // Usually directory and filename are together, otherwise just
3264 // directory. Allow the strings to have escaped octal character sequence.
3265 parseEscapedString(Filename) ||
3266 parseToken(AsmToken::EndOfStatement,
3267 "unexpected token in '.cv_file' directive"))
3270 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
3271 return Error(FileNumberLoc, "file number already allocated");
3276 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3277 StringRef DirectiveName) {
3279 return parseTokenLoc(Loc) ||
3280 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3282 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3283 "expected function id within range [0, UINT_MAX)");
3286 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3288 return parseTokenLoc(Loc) ||
3289 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3291 check(FileNumber < 1, Loc, "file number less than one in '" +
3292 DirectiveName + "' directive") ||
3293 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3294 "unassigned file number in '" + DirectiveName + "' directive");
3297 /// parseDirectiveCVFuncId
3298 /// ::= .cv_func_id FunctionId
3300 /// Introduces a function ID that can be used with .cv_loc.
3301 bool AsmParser::parseDirectiveCVFuncId() {
3302 SMLoc FunctionIdLoc = getTok().getLoc();
3305 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3306 parseToken(AsmToken::EndOfStatement,
3307 "unexpected token in '.cv_func_id' directive"))
3310 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3311 return Error(FunctionIdLoc, "function id already allocated");
3316 /// parseDirectiveCVInlineSiteId
3317 /// ::= .cv_inline_site_id FunctionId
3319 /// "inlined_at" IAFile IALine [IACol]
3321 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3322 /// at" source location information for use in the line table of the caller,
3323 /// whether the caller is a real function or another inlined call site.
3324 bool AsmParser::parseDirectiveCVInlineSiteId() {
3325 SMLoc FunctionIdLoc = getTok().getLoc();
3333 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3337 if (check((getLexer().isNot(AsmToken::Identifier) ||
3338 getTok().getIdentifier() != "within"),
3339 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3344 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3348 if (check((getLexer().isNot(AsmToken::Identifier) ||
3349 getTok().getIdentifier() != "inlined_at"),
3350 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3356 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3357 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3361 if (getLexer().is(AsmToken::Integer)) {
3362 IACol = getTok().getIntVal();
3366 if (parseToken(AsmToken::EndOfStatement,
3367 "unexpected token in '.cv_inline_site_id' directive"))
3370 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3371 IALine, IACol, FunctionIdLoc))
3372 return Error(FunctionIdLoc, "function id already allocated");
3377 /// parseDirectiveCVLoc
3378 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3380 /// The first number is a file number, must have been previously assigned with
3381 /// a .file directive, the second number is the line number and optionally the
3382 /// third number is a column position (zero if not specified). The remaining
3383 /// optional items are .loc sub-directives.
3384 bool AsmParser::parseDirectiveCVLoc() {
3385 SMLoc DirectiveLoc = getTok().getLoc();
3387 int64_t FunctionId, FileNumber;
3388 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3389 parseCVFileId(FileNumber, ".cv_loc"))
3392 int64_t LineNumber = 0;
3393 if (getLexer().is(AsmToken::Integer)) {
3394 LineNumber = getTok().getIntVal();
3396 return TokError("line number less than zero in '.cv_loc' directive");
3400 int64_t ColumnPos = 0;
3401 if (getLexer().is(AsmToken::Integer)) {
3402 ColumnPos = getTok().getIntVal();
3404 return TokError("column position less than zero in '.cv_loc' directive");
3408 bool PrologueEnd = false;
3409 uint64_t IsStmt = 0;
3411 auto parseOp = [&]() -> bool {
3413 SMLoc Loc = getTok().getLoc();
3414 if (parseIdentifier(Name))
3415 return TokError("unexpected token in '.cv_loc' directive");
3416 if (Name == "prologue_end")
3418 else if (Name == "is_stmt") {
3419 Loc = getTok().getLoc();
3420 const MCExpr *Value;
3421 if (parseExpression(Value))
3423 // The expression must be the constant 0 or 1.
3425 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3426 IsStmt = MCE->getValue();
3429 return Error(Loc, "is_stmt value not 0 or 1");
3431 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3436 if (parseMany(parseOp, false /*hasComma*/))
3439 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3440 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3445 /// parseDirectiveCVLinetable
3446 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3447 bool AsmParser::parseDirectiveCVLinetable() {
3449 StringRef FnStartName, FnEndName;
3450 SMLoc Loc = getTok().getLoc();
3451 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3452 parseToken(AsmToken::Comma,
3453 "unexpected token in '.cv_linetable' directive") ||
3454 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3455 "expected identifier in directive") ||
3456 parseToken(AsmToken::Comma,
3457 "unexpected token in '.cv_linetable' directive") ||
3458 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3459 "expected identifier in directive"))
3462 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3463 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3465 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3469 /// parseDirectiveCVInlineLinetable
3470 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3471 bool AsmParser::parseDirectiveCVInlineLinetable() {
3472 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3473 StringRef FnStartName, FnEndName;
3474 SMLoc Loc = getTok().getLoc();
3475 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3476 parseTokenLoc(Loc) ||
3479 "expected SourceField in '.cv_inline_linetable' directive") ||
3480 check(SourceFileId <= 0, Loc,
3481 "File id less than zero in '.cv_inline_linetable' directive") ||
3482 parseTokenLoc(Loc) ||
3485 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3486 check(SourceLineNum < 0, Loc,
3487 "Line number less than zero in '.cv_inline_linetable' directive") ||
3488 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3489 "expected identifier in directive") ||
3490 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3491 "expected identifier in directive"))
3494 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3497 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3498 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3499 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3500 SourceLineNum, FnStartSym,
3505 /// parseDirectiveCVDefRange
3506 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3507 bool AsmParser::parseDirectiveCVDefRange() {
3509 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3510 while (getLexer().is(AsmToken::Identifier)) {
3511 Loc = getLexer().getLoc();
3512 StringRef GapStartName;
3513 if (parseIdentifier(GapStartName))
3514 return Error(Loc, "expected identifier in directive");
3515 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3517 Loc = getLexer().getLoc();
3518 StringRef GapEndName;
3519 if (parseIdentifier(GapEndName))
3520 return Error(Loc, "expected identifier in directive");
3521 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3523 Ranges.push_back({GapStartSym, GapEndSym});
3526 std::string FixedSizePortion;
3527 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3528 parseEscapedString(FixedSizePortion))
3531 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3535 /// parseDirectiveCVStringTable
3536 /// ::= .cv_stringtable
3537 bool AsmParser::parseDirectiveCVStringTable() {
3538 getStreamer().EmitCVStringTableDirective();
3542 /// parseDirectiveCVFileChecksums
3543 /// ::= .cv_filechecksums
3544 bool AsmParser::parseDirectiveCVFileChecksums() {
3545 getStreamer().EmitCVFileChecksumsDirective();
3549 /// parseDirectiveCFISections
3550 /// ::= .cfi_sections section [, section]
3551 bool AsmParser::parseDirectiveCFISections() {
3556 if (parseIdentifier(Name))
3557 return TokError("Expected an identifier");
3559 if (Name == ".eh_frame")
3561 else if (Name == ".debug_frame")
3564 if (getLexer().is(AsmToken::Comma)) {
3567 if (parseIdentifier(Name))
3568 return TokError("Expected an identifier");
3570 if (Name == ".eh_frame")
3572 else if (Name == ".debug_frame")
3576 getStreamer().EmitCFISections(EH, Debug);
3580 /// parseDirectiveCFIStartProc
3581 /// ::= .cfi_startproc [simple]
3582 bool AsmParser::parseDirectiveCFIStartProc() {
3584 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3585 if (check(parseIdentifier(Simple) || Simple != "simple",
3586 "unexpected token") ||
3587 parseToken(AsmToken::EndOfStatement))
3588 return addErrorSuffix(" in '.cfi_startproc' directive");
3591 getStreamer().EmitCFIStartProc(!Simple.empty());
3595 /// parseDirectiveCFIEndProc
3596 /// ::= .cfi_endproc
3597 bool AsmParser::parseDirectiveCFIEndProc() {
3598 getStreamer().EmitCFIEndProc();
3602 /// \brief parse register name or number.
3603 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3604 SMLoc DirectiveLoc) {
3607 if (getLexer().isNot(AsmToken::Integer)) {
3608 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3610 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3612 return parseAbsoluteExpression(Register);
3617 /// parseDirectiveCFIDefCfa
3618 /// ::= .cfi_def_cfa register, offset
3619 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3620 int64_t Register = 0, Offset = 0;
3621 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3622 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3623 parseAbsoluteExpression(Offset))
3626 getStreamer().EmitCFIDefCfa(Register, Offset);
3630 /// parseDirectiveCFIDefCfaOffset
3631 /// ::= .cfi_def_cfa_offset offset
3632 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3634 if (parseAbsoluteExpression(Offset))
3637 getStreamer().EmitCFIDefCfaOffset(Offset);
3641 /// parseDirectiveCFIRegister
3642 /// ::= .cfi_register register, register
3643 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3644 int64_t Register1 = 0, Register2 = 0;
3645 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3646 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3647 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3650 getStreamer().EmitCFIRegister(Register1, Register2);
3654 /// parseDirectiveCFIWindowSave
3655 /// ::= .cfi_window_save
3656 bool AsmParser::parseDirectiveCFIWindowSave() {
3657 getStreamer().EmitCFIWindowSave();
3661 /// parseDirectiveCFIAdjustCfaOffset
3662 /// ::= .cfi_adjust_cfa_offset adjustment
3663 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3664 int64_t Adjustment = 0;
3665 if (parseAbsoluteExpression(Adjustment))
3668 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3672 /// parseDirectiveCFIDefCfaRegister
3673 /// ::= .cfi_def_cfa_register register
3674 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3675 int64_t Register = 0;
3676 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3679 getStreamer().EmitCFIDefCfaRegister(Register);
3683 /// parseDirectiveCFIOffset
3684 /// ::= .cfi_offset register, offset
3685 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3686 int64_t Register = 0;
3689 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3690 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3691 parseAbsoluteExpression(Offset))
3694 getStreamer().EmitCFIOffset(Register, Offset);
3698 /// parseDirectiveCFIRelOffset
3699 /// ::= .cfi_rel_offset register, offset
3700 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3701 int64_t Register = 0, Offset = 0;
3703 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3704 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3705 parseAbsoluteExpression(Offset))
3708 getStreamer().EmitCFIRelOffset(Register, Offset);
3712 static bool isValidEncoding(int64_t Encoding) {
3713 if (Encoding & ~0xff)
3716 if (Encoding == dwarf::DW_EH_PE_omit)
3719 const unsigned Format = Encoding & 0xf;
3720 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3721 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3722 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3723 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3726 const unsigned Application = Encoding & 0x70;
3727 if (Application != dwarf::DW_EH_PE_absptr &&
3728 Application != dwarf::DW_EH_PE_pcrel)
3734 /// parseDirectiveCFIPersonalityOrLsda
3735 /// IsPersonality true for cfi_personality, false for cfi_lsda
3736 /// ::= .cfi_personality encoding, [symbol_name]
3737 /// ::= .cfi_lsda encoding, [symbol_name]
3738 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3739 int64_t Encoding = 0;
3740 if (parseAbsoluteExpression(Encoding))
3742 if (Encoding == dwarf::DW_EH_PE_omit)
3746 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3747 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3748 check(parseIdentifier(Name), "expected identifier in directive"))
3751 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3754 getStreamer().EmitCFIPersonality(Sym, Encoding);
3756 getStreamer().EmitCFILsda(Sym, Encoding);
3760 /// parseDirectiveCFIRememberState
3761 /// ::= .cfi_remember_state
3762 bool AsmParser::parseDirectiveCFIRememberState() {
3763 getStreamer().EmitCFIRememberState();
3767 /// parseDirectiveCFIRestoreState
3768 /// ::= .cfi_remember_state
3769 bool AsmParser::parseDirectiveCFIRestoreState() {
3770 getStreamer().EmitCFIRestoreState();
3774 /// parseDirectiveCFISameValue
3775 /// ::= .cfi_same_value register
3776 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3777 int64_t Register = 0;
3779 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3782 getStreamer().EmitCFISameValue(Register);
3786 /// parseDirectiveCFIRestore
3787 /// ::= .cfi_restore register
3788 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3789 int64_t Register = 0;
3790 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3793 getStreamer().EmitCFIRestore(Register);
3797 /// parseDirectiveCFIEscape
3798 /// ::= .cfi_escape expression[,...]
3799 bool AsmParser::parseDirectiveCFIEscape() {
3802 if (parseAbsoluteExpression(CurrValue))
3805 Values.push_back((uint8_t)CurrValue);
3807 while (getLexer().is(AsmToken::Comma)) {
3810 if (parseAbsoluteExpression(CurrValue))
3813 Values.push_back((uint8_t)CurrValue);
3816 getStreamer().EmitCFIEscape(Values);
3820 /// parseDirectiveCFISignalFrame
3821 /// ::= .cfi_signal_frame
3822 bool AsmParser::parseDirectiveCFISignalFrame() {
3823 if (parseToken(AsmToken::EndOfStatement,
3824 "unexpected token in '.cfi_signal_frame'"))
3827 getStreamer().EmitCFISignalFrame();
3831 /// parseDirectiveCFIUndefined
3832 /// ::= .cfi_undefined register
3833 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3834 int64_t Register = 0;
3836 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3839 getStreamer().EmitCFIUndefined(Register);
3843 /// parseDirectiveMacrosOnOff
3846 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3847 if (parseToken(AsmToken::EndOfStatement,
3848 "unexpected token in '" + Directive + "' directive"))
3851 setMacrosEnabled(Directive == ".macros_on");
3855 /// parseDirectiveMacro
3856 /// ::= .macro name[,] [parameters]
3857 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3859 if (parseIdentifier(Name))
3860 return TokError("expected identifier in '.macro' directive");
3862 if (getLexer().is(AsmToken::Comma))
3865 MCAsmMacroParameters Parameters;
3866 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3868 if (!Parameters.empty() && Parameters.back().Vararg)
3869 return Error(Lexer.getLoc(),
3870 "Vararg parameter '" + Parameters.back().Name +
3871 "' should be last one in the list of parameters.");
3873 MCAsmMacroParameter Parameter;
3874 if (parseIdentifier(Parameter.Name))
3875 return TokError("expected identifier in '.macro' directive");
3877 // Emit an error if two (or more) named parameters share the same name
3878 for (const MCAsmMacroParameter& CurrParam : Parameters)
3879 if (CurrParam.Name.equals(Parameter.Name))
3880 return TokError("macro '" + Name + "' has multiple parameters"
3881 " named '" + Parameter.Name + "'");
3883 if (Lexer.is(AsmToken::Colon)) {
3884 Lex(); // consume ':'
3887 StringRef Qualifier;
3889 QualLoc = Lexer.getLoc();
3890 if (parseIdentifier(Qualifier))
3891 return Error(QualLoc, "missing parameter qualifier for "
3892 "'" + Parameter.Name + "' in macro '" + Name + "'");
3894 if (Qualifier == "req")
3895 Parameter.Required = true;
3896 else if (Qualifier == "vararg")
3897 Parameter.Vararg = true;
3899 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3900 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3903 if (getLexer().is(AsmToken::Equal)) {
3908 ParamLoc = Lexer.getLoc();
3909 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3912 if (Parameter.Required)
3913 Warning(ParamLoc, "pointless default value for required parameter "
3914 "'" + Parameter.Name + "' in macro '" + Name + "'");
3917 Parameters.push_back(std::move(Parameter));
3919 if (getLexer().is(AsmToken::Comma))
3923 // Eat just the end of statement.
3926 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
3927 AsmToken EndToken, StartToken = getTok();
3928 unsigned MacroDepth = 0;
3929 // Lex the macro definition.
3931 // Ignore Lexing errors in macros.
3932 while (Lexer.is(AsmToken::Error)) {
3936 // Check whether we have reached the end of the file.
3937 if (getLexer().is(AsmToken::Eof))
3938 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3940 // Otherwise, check whether we have reach the .endmacro.
3941 if (getLexer().is(AsmToken::Identifier)) {
3942 if (getTok().getIdentifier() == ".endm" ||
3943 getTok().getIdentifier() == ".endmacro") {
3944 if (MacroDepth == 0) { // Outermost macro.
3945 EndToken = getTok();
3947 if (getLexer().isNot(AsmToken::EndOfStatement))
3948 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3952 // Otherwise we just found the end of an inner macro.
3955 } else if (getTok().getIdentifier() == ".macro") {
3956 // We allow nested macros. Those aren't instantiated until the outermost
3957 // macro is expanded so just ignore them for now.
3962 // Otherwise, scan til the end of the statement.
3963 eatToEndOfStatement();
3966 if (lookupMacro(Name)) {
3967 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3970 const char *BodyStart = StartToken.getLoc().getPointer();
3971 const char *BodyEnd = EndToken.getLoc().getPointer();
3972 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3973 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3974 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3978 /// checkForBadMacro
3980 /// With the support added for named parameters there may be code out there that
3981 /// is transitioning from positional parameters. In versions of gas that did
3982 /// not support named parameters they would be ignored on the macro definition.
3983 /// But to support both styles of parameters this is not possible so if a macro
3984 /// definition has named parameters but does not use them and has what appears
3985 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3986 /// warning that the positional parameter found in body which have no effect.
3987 /// Hoping the developer will either remove the named parameters from the macro
3988 /// definition so the positional parameters get used if that was what was
3989 /// intended or change the macro to use the named parameters. It is possible
3990 /// this warning will trigger when the none of the named parameters are used
3991 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3992 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3994 ArrayRef<MCAsmMacroParameter> Parameters) {
3995 // If this macro is not defined with named parameters the warning we are
3996 // checking for here doesn't apply.
3997 unsigned NParameters = Parameters.size();
3998 if (NParameters == 0)
4001 bool NamedParametersFound = false;
4002 bool PositionalParametersFound = false;
4004 // Look at the body of the macro for use of both the named parameters and what
4005 // are likely to be positional parameters. This is what expandMacro() is
4006 // doing when it finds the parameters in the body.
4007 while (!Body.empty()) {
4008 // Scan for the next possible parameter.
4009 std::size_t End = Body.size(), Pos = 0;
4010 for (; Pos != End; ++Pos) {
4011 // Check for a substitution or escape.
4012 // This macro is defined with parameters, look for \foo, \bar, etc.
4013 if (Body[Pos] == '\\' && Pos + 1 != End)
4016 // This macro should have parameters, but look for $0, $1, ..., $n too.
4017 if (Body[Pos] != '$' || Pos + 1 == End)
4019 char Next = Body[Pos + 1];
4020 if (Next == '$' || Next == 'n' ||
4021 isdigit(static_cast<unsigned char>(Next)))
4025 // Check if we reached the end.
4029 if (Body[Pos] == '$') {
4030 switch (Body[Pos + 1]) {
4035 // $n => number of arguments
4037 PositionalParametersFound = true;
4040 // $[0-9] => argument
4042 PositionalParametersFound = true;
4048 unsigned I = Pos + 1;
4049 while (isIdentifierChar(Body[I]) && I + 1 != End)
4052 const char *Begin = Body.data() + Pos + 1;
4053 StringRef Argument(Begin, I - (Pos + 1));
4055 for (; Index < NParameters; ++Index)
4056 if (Parameters[Index].Name == Argument)
4059 if (Index == NParameters) {
4060 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4066 NamedParametersFound = true;
4067 Pos += 1 + Argument.size();
4070 // Update the scan point.
4071 Body = Body.substr(Pos);
4074 if (!NamedParametersFound && PositionalParametersFound)
4075 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4076 "used in macro body, possible positional parameter "
4077 "found in body which will have no effect");
4080 /// parseDirectiveExitMacro
4082 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4083 if (parseToken(AsmToken::EndOfStatement,
4084 "unexpected token in '" + Directive + "' directive"))
4087 if (!isInsideMacroInstantiation())
4088 return TokError("unexpected '" + Directive + "' in file, "
4089 "no current macro definition");
4091 // Exit all conditionals that are active in the current macro.
4092 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4093 TheCondState = TheCondStack.back();
4094 TheCondStack.pop_back();
4101 /// parseDirectiveEndMacro
4104 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4105 if (getLexer().isNot(AsmToken::EndOfStatement))
4106 return TokError("unexpected token in '" + Directive + "' directive");
4108 // If we are inside a macro instantiation, terminate the current
4110 if (isInsideMacroInstantiation()) {
4115 // Otherwise, this .endmacro is a stray entry in the file; well formed
4116 // .endmacro directives are handled during the macro definition parsing.
4117 return TokError("unexpected '" + Directive + "' in file, "
4118 "no current macro definition");
4121 /// parseDirectivePurgeMacro
4123 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4126 if (parseTokenLoc(Loc) ||
4127 check(parseIdentifier(Name), Loc,
4128 "expected identifier in '.purgem' directive") ||
4129 parseToken(AsmToken::EndOfStatement,
4130 "unexpected token in '.purgem' directive"))
4133 if (!lookupMacro(Name))
4134 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4136 undefineMacro(Name);
4140 /// parseDirectiveBundleAlignMode
4141 /// ::= {.bundle_align_mode} expression
4142 bool AsmParser::parseDirectiveBundleAlignMode() {
4143 // Expect a single argument: an expression that evaluates to a constant
4144 // in the inclusive range 0-30.
4145 SMLoc ExprLoc = getLexer().getLoc();
4146 int64_t AlignSizePow2;
4147 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4148 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4149 "in '.bundle_align_mode' "
4151 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4152 "invalid bundle alignment size (expected between 0 and 30)"))
4155 // Because of AlignSizePow2's verified range we can safely truncate it to
4157 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4161 /// parseDirectiveBundleLock
4162 /// ::= {.bundle_lock} [align_to_end]
4163 bool AsmParser::parseDirectiveBundleLock() {
4164 if (checkForValidSection())
4166 bool AlignToEnd = false;
4169 SMLoc Loc = getTok().getLoc();
4170 const char *kInvalidOptionError =
4171 "invalid option for '.bundle_lock' directive";
4173 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4174 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4175 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4176 parseToken(AsmToken::EndOfStatement,
4177 "unexpected token after '.bundle_lock' directive option"))
4182 getStreamer().EmitBundleLock(AlignToEnd);
4186 /// parseDirectiveBundleLock
4187 /// ::= {.bundle_lock}
4188 bool AsmParser::parseDirectiveBundleUnlock() {
4189 if (checkForValidSection() ||
4190 parseToken(AsmToken::EndOfStatement,
4191 "unexpected token in '.bundle_unlock' directive"))
4194 getStreamer().EmitBundleUnlock();
4198 /// parseDirectiveSpace
4199 /// ::= (.skip | .space) expression [ , expression ]
4200 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4201 SMLoc NumBytesLoc = Lexer.getLoc();
4202 const MCExpr *NumBytes;
4203 if (checkForValidSection() || parseExpression(NumBytes))
4206 int64_t FillExpr = 0;
4207 if (parseOptionalToken(AsmToken::Comma))
4208 if (parseAbsoluteExpression(FillExpr))
4209 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4210 if (parseToken(AsmToken::EndOfStatement))
4211 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4213 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4214 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4219 /// parseDirectiveDCB
4220 /// ::= .dcb.{b, l, w} expression, expression
4221 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4222 SMLoc NumValuesLoc = Lexer.getLoc();
4224 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4227 if (NumValues < 0) {
4228 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4232 if (parseToken(AsmToken::Comma,
4233 "unexpected token in '" + Twine(IDVal) + "' directive"))
4236 const MCExpr *Value;
4237 SMLoc ExprLoc = getLexer().getLoc();
4238 if (parseExpression(Value))
4241 // Special case constant expressions to match code generator.
4242 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4243 assert(Size <= 8 && "Invalid size");
4244 uint64_t IntValue = MCE->getValue();
4245 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4246 return Error(ExprLoc, "literal value out of range for directive");
4247 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4248 getStreamer().EmitIntValue(IntValue, Size);
4250 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4251 getStreamer().EmitValue(Value, Size, ExprLoc);
4254 if (parseToken(AsmToken::EndOfStatement,
4255 "unexpected token in '" + Twine(IDVal) + "' directive"))
4261 /// parseDirectiveRealDCB
4262 /// ::= .dcb.{d, s} expression, expression
4263 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4264 SMLoc NumValuesLoc = Lexer.getLoc();
4266 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4269 if (NumValues < 0) {
4270 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4274 if (parseToken(AsmToken::Comma,
4275 "unexpected token in '" + Twine(IDVal) + "' directive"))
4279 if (parseRealValue(Semantics, AsInt))
4282 if (parseToken(AsmToken::EndOfStatement,
4283 "unexpected token in '" + Twine(IDVal) + "' directive"))
4286 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4287 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4288 AsInt.getBitWidth() / 8);
4293 /// parseDirectiveDS
4294 /// ::= .ds.{b, d, l, p, s, w, x} expression
4295 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4296 SMLoc NumValuesLoc = Lexer.getLoc();
4298 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4301 if (NumValues < 0) {
4302 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4306 if (parseToken(AsmToken::EndOfStatement,
4307 "unexpected token in '" + Twine(IDVal) + "' directive"))
4310 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4311 getStreamer().emitFill(Size, 0);
4316 /// parseDirectiveLEB128
4317 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4318 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4319 if (checkForValidSection())
4322 auto parseOp = [&]() -> bool {
4323 const MCExpr *Value;
4324 if (parseExpression(Value))
4327 getStreamer().EmitSLEB128Value(Value);
4329 getStreamer().EmitULEB128Value(Value);
4333 if (parseMany(parseOp))
4334 return addErrorSuffix(" in directive");
4339 /// parseDirectiveSymbolAttribute
4340 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4341 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4342 auto parseOp = [&]() -> bool {
4344 SMLoc Loc = getTok().getLoc();
4345 if (parseIdentifier(Name))
4346 return Error(Loc, "expected identifier");
4347 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4349 // Assembler local symbols don't make any sense here. Complain loudly.
4350 if (Sym->isTemporary())
4351 return Error(Loc, "non-local symbol required");
4353 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4354 return Error(Loc, "unable to emit symbol attribute");
4358 if (parseMany(parseOp))
4359 return addErrorSuffix(" in directive");
4363 /// parseDirectiveComm
4364 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4365 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4366 if (checkForValidSection())
4369 SMLoc IDLoc = getLexer().getLoc();
4371 if (parseIdentifier(Name))
4372 return TokError("expected identifier in directive");
4374 // Handle the identifier as the key symbol.
4375 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4377 if (getLexer().isNot(AsmToken::Comma))
4378 return TokError("unexpected token in directive");
4382 SMLoc SizeLoc = getLexer().getLoc();
4383 if (parseAbsoluteExpression(Size))
4386 int64_t Pow2Alignment = 0;
4387 SMLoc Pow2AlignmentLoc;
4388 if (getLexer().is(AsmToken::Comma)) {
4390 Pow2AlignmentLoc = getLexer().getLoc();
4391 if (parseAbsoluteExpression(Pow2Alignment))
4394 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4395 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4396 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4398 // If this target takes alignments in bytes (not log) validate and convert.
4399 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4400 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4401 if (!isPowerOf2_64(Pow2Alignment))
4402 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4403 Pow2Alignment = Log2_64(Pow2Alignment);
4407 if (parseToken(AsmToken::EndOfStatement,
4408 "unexpected token in '.comm' or '.lcomm' directive"))
4411 // NOTE: a size of zero for a .comm should create a undefined symbol
4412 // but a size of .lcomm creates a bss symbol of size zero.
4414 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4415 "be less than zero");
4417 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4418 // may internally end up wanting an alignment in bytes.
4419 // FIXME: Diagnose overflow.
4420 if (Pow2Alignment < 0)
4421 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4422 "alignment, can't be less than zero");
4424 Sym->redefineIfPossible();
4425 if (!Sym->isUndefined())
4426 return Error(IDLoc, "invalid symbol redefinition");
4428 // Create the Symbol as a common or local common with Size and Pow2Alignment
4430 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4434 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4438 /// parseDirectiveAbort
4439 /// ::= .abort [... message ...]
4440 bool AsmParser::parseDirectiveAbort() {
4441 // FIXME: Use loc from directive.
4442 SMLoc Loc = getLexer().getLoc();
4444 StringRef Str = parseStringToEndOfStatement();
4445 if (parseToken(AsmToken::EndOfStatement,
4446 "unexpected token in '.abort' directive"))
4450 return Error(Loc, ".abort detected. Assembly stopping.");
4452 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4453 // FIXME: Actually abort assembly here.
4458 /// parseDirectiveInclude
4459 /// ::= .include "filename"
4460 bool AsmParser::parseDirectiveInclude() {
4461 // Allow the strings to have escaped octal character sequence.
4462 std::string Filename;
4463 SMLoc IncludeLoc = getTok().getLoc();
4465 if (check(getTok().isNot(AsmToken::String),
4466 "expected string in '.include' directive") ||
4467 parseEscapedString(Filename) ||
4468 check(getTok().isNot(AsmToken::EndOfStatement),
4469 "unexpected token in '.include' directive") ||
4470 // Attempt to switch the lexer to the included file before consuming the
4471 // end of statement to avoid losing it when we switch.
4472 check(enterIncludeFile(Filename), IncludeLoc,
4473 "Could not find include file '" + Filename + "'"))
4479 /// parseDirectiveIncbin
4480 /// ::= .incbin "filename" [ , skip [ , count ] ]
4481 bool AsmParser::parseDirectiveIncbin() {
4482 // Allow the strings to have escaped octal character sequence.
4483 std::string Filename;
4484 SMLoc IncbinLoc = getTok().getLoc();
4485 if (check(getTok().isNot(AsmToken::String),
4486 "expected string in '.incbin' directive") ||
4487 parseEscapedString(Filename))
4491 const MCExpr *Count = nullptr;
4492 SMLoc SkipLoc, CountLoc;
4493 if (parseOptionalToken(AsmToken::Comma)) {
4494 // The skip expression can be omitted while specifying the count, e.g:
4495 // .incbin "filename",,4
4496 if (getTok().isNot(AsmToken::Comma)) {
4497 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4500 if (parseOptionalToken(AsmToken::Comma)) {
4501 CountLoc = getTok().getLoc();
4502 if (parseExpression(Count))
4507 if (parseToken(AsmToken::EndOfStatement,
4508 "unexpected token in '.incbin' directive"))
4511 if (check(Skip < 0, SkipLoc, "skip is negative"))
4514 // Attempt to process the included file.
4515 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4516 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4520 /// parseDirectiveIf
4521 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4522 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4523 TheCondStack.push_back(TheCondState);
4524 TheCondState.TheCond = AsmCond::IfCond;
4525 if (TheCondState.Ignore) {
4526 eatToEndOfStatement();
4529 if (parseAbsoluteExpression(ExprValue) ||
4530 parseToken(AsmToken::EndOfStatement,
4531 "unexpected token in '.if' directive"))
4536 llvm_unreachable("unsupported directive");
4541 ExprValue = ExprValue == 0;
4544 ExprValue = ExprValue >= 0;
4547 ExprValue = ExprValue > 0;
4550 ExprValue = ExprValue <= 0;
4553 ExprValue = ExprValue < 0;
4557 TheCondState.CondMet = ExprValue;
4558 TheCondState.Ignore = !TheCondState.CondMet;
4564 /// parseDirectiveIfb
4566 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4567 TheCondStack.push_back(TheCondState);
4568 TheCondState.TheCond = AsmCond::IfCond;
4570 if (TheCondState.Ignore) {
4571 eatToEndOfStatement();
4573 StringRef Str = parseStringToEndOfStatement();
4575 if (parseToken(AsmToken::EndOfStatement,
4576 "unexpected token in '.ifb' directive"))
4579 TheCondState.CondMet = ExpectBlank == Str.empty();
4580 TheCondState.Ignore = !TheCondState.CondMet;
4586 /// parseDirectiveIfc
4587 /// ::= .ifc string1, string2
4588 /// ::= .ifnc string1, string2
4589 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4590 TheCondStack.push_back(TheCondState);
4591 TheCondState.TheCond = AsmCond::IfCond;
4593 if (TheCondState.Ignore) {
4594 eatToEndOfStatement();
4596 StringRef Str1 = parseStringToComma();
4598 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4601 StringRef Str2 = parseStringToEndOfStatement();
4603 if (parseToken(AsmToken::EndOfStatement,
4604 "unexpected token in '.ifc' directive"))
4607 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4608 TheCondState.Ignore = !TheCondState.CondMet;
4614 /// parseDirectiveIfeqs
4615 /// ::= .ifeqs string1, string2
4616 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4617 if (Lexer.isNot(AsmToken::String)) {
4619 return TokError("expected string parameter for '.ifeqs' directive");
4620 return TokError("expected string parameter for '.ifnes' directive");
4623 StringRef String1 = getTok().getStringContents();
4626 if (Lexer.isNot(AsmToken::Comma)) {
4629 "expected comma after first string for '.ifeqs' directive");
4630 return TokError("expected comma after first string for '.ifnes' directive");
4635 if (Lexer.isNot(AsmToken::String)) {
4637 return TokError("expected string parameter for '.ifeqs' directive");
4638 return TokError("expected string parameter for '.ifnes' directive");
4641 StringRef String2 = getTok().getStringContents();
4644 TheCondStack.push_back(TheCondState);
4645 TheCondState.TheCond = AsmCond::IfCond;
4646 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4647 TheCondState.Ignore = !TheCondState.CondMet;
4652 /// parseDirectiveIfdef
4653 /// ::= .ifdef symbol
4654 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4656 TheCondStack.push_back(TheCondState);
4657 TheCondState.TheCond = AsmCond::IfCond;
4659 if (TheCondState.Ignore) {
4660 eatToEndOfStatement();
4662 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4663 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4666 MCSymbol *Sym = getContext().lookupSymbol(Name);
4669 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4671 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4672 TheCondState.Ignore = !TheCondState.CondMet;
4678 /// parseDirectiveElseIf
4679 /// ::= .elseif expression
4680 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4681 if (TheCondState.TheCond != AsmCond::IfCond &&
4682 TheCondState.TheCond != AsmCond::ElseIfCond)
4683 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4684 " .if or an .elseif");
4685 TheCondState.TheCond = AsmCond::ElseIfCond;
4687 bool LastIgnoreState = false;
4688 if (!TheCondStack.empty())
4689 LastIgnoreState = TheCondStack.back().Ignore;
4690 if (LastIgnoreState || TheCondState.CondMet) {
4691 TheCondState.Ignore = true;
4692 eatToEndOfStatement();
4695 if (parseAbsoluteExpression(ExprValue))
4698 if (parseToken(AsmToken::EndOfStatement,
4699 "unexpected token in '.elseif' directive"))
4702 TheCondState.CondMet = ExprValue;
4703 TheCondState.Ignore = !TheCondState.CondMet;
4709 /// parseDirectiveElse
4711 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4712 if (parseToken(AsmToken::EndOfStatement,
4713 "unexpected token in '.else' directive"))
4716 if (TheCondState.TheCond != AsmCond::IfCond &&
4717 TheCondState.TheCond != AsmCond::ElseIfCond)
4718 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4719 " an .if or an .elseif");
4720 TheCondState.TheCond = AsmCond::ElseCond;
4721 bool LastIgnoreState = false;
4722 if (!TheCondStack.empty())
4723 LastIgnoreState = TheCondStack.back().Ignore;
4724 if (LastIgnoreState || TheCondState.CondMet)
4725 TheCondState.Ignore = true;
4727 TheCondState.Ignore = false;
4732 /// parseDirectiveEnd
4734 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4735 if (parseToken(AsmToken::EndOfStatement,
4736 "unexpected token in '.end' directive"))
4739 while (Lexer.isNot(AsmToken::Eof))
4745 /// parseDirectiveError
4747 /// ::= .error [string]
4748 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4749 if (!TheCondStack.empty()) {
4750 if (TheCondStack.back().Ignore) {
4751 eatToEndOfStatement();
4757 return Error(L, ".err encountered");
4759 StringRef Message = ".error directive invoked in source file";
4760 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4761 if (Lexer.isNot(AsmToken::String))
4762 return TokError(".error argument must be a string");
4764 Message = getTok().getStringContents();
4768 return Error(L, Message);
4771 /// parseDirectiveWarning
4772 /// ::= .warning [string]
4773 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4774 if (!TheCondStack.empty()) {
4775 if (TheCondStack.back().Ignore) {
4776 eatToEndOfStatement();
4781 StringRef Message = ".warning directive invoked in source file";
4783 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4784 if (Lexer.isNot(AsmToken::String))
4785 return TokError(".warning argument must be a string");
4787 Message = getTok().getStringContents();
4789 if (parseToken(AsmToken::EndOfStatement,
4790 "expected end of statement in '.warning' directive"))
4794 return Warning(L, Message);
4797 /// parseDirectiveEndIf
4799 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4800 if (parseToken(AsmToken::EndOfStatement,
4801 "unexpected token in '.endif' directive"))
4804 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4805 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4807 if (!TheCondStack.empty()) {
4808 TheCondState = TheCondStack.back();
4809 TheCondStack.pop_back();
4815 void AsmParser::initializeDirectiveKindMap() {
4816 DirectiveKindMap[".set"] = DK_SET;
4817 DirectiveKindMap[".equ"] = DK_EQU;
4818 DirectiveKindMap[".equiv"] = DK_EQUIV;
4819 DirectiveKindMap[".ascii"] = DK_ASCII;
4820 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4821 DirectiveKindMap[".string"] = DK_STRING;
4822 DirectiveKindMap[".byte"] = DK_BYTE;
4823 DirectiveKindMap[".short"] = DK_SHORT;
4824 DirectiveKindMap[".value"] = DK_VALUE;
4825 DirectiveKindMap[".2byte"] = DK_2BYTE;
4826 DirectiveKindMap[".long"] = DK_LONG;
4827 DirectiveKindMap[".int"] = DK_INT;
4828 DirectiveKindMap[".4byte"] = DK_4BYTE;
4829 DirectiveKindMap[".quad"] = DK_QUAD;
4830 DirectiveKindMap[".8byte"] = DK_8BYTE;
4831 DirectiveKindMap[".octa"] = DK_OCTA;
4832 DirectiveKindMap[".single"] = DK_SINGLE;
4833 DirectiveKindMap[".float"] = DK_FLOAT;
4834 DirectiveKindMap[".double"] = DK_DOUBLE;
4835 DirectiveKindMap[".align"] = DK_ALIGN;
4836 DirectiveKindMap[".align32"] = DK_ALIGN32;
4837 DirectiveKindMap[".balign"] = DK_BALIGN;
4838 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4839 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4840 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4841 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4842 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4843 DirectiveKindMap[".org"] = DK_ORG;
4844 DirectiveKindMap[".fill"] = DK_FILL;
4845 DirectiveKindMap[".zero"] = DK_ZERO;
4846 DirectiveKindMap[".extern"] = DK_EXTERN;
4847 DirectiveKindMap[".globl"] = DK_GLOBL;
4848 DirectiveKindMap[".global"] = DK_GLOBAL;
4849 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4850 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4851 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4852 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4853 DirectiveKindMap[".reference"] = DK_REFERENCE;
4854 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4855 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4856 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4857 DirectiveKindMap[".comm"] = DK_COMM;
4858 DirectiveKindMap[".common"] = DK_COMMON;
4859 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4860 DirectiveKindMap[".abort"] = DK_ABORT;
4861 DirectiveKindMap[".include"] = DK_INCLUDE;
4862 DirectiveKindMap[".incbin"] = DK_INCBIN;
4863 DirectiveKindMap[".code16"] = DK_CODE16;
4864 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4865 DirectiveKindMap[".rept"] = DK_REPT;
4866 DirectiveKindMap[".rep"] = DK_REPT;
4867 DirectiveKindMap[".irp"] = DK_IRP;
4868 DirectiveKindMap[".irpc"] = DK_IRPC;
4869 DirectiveKindMap[".endr"] = DK_ENDR;
4870 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4871 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4872 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4873 DirectiveKindMap[".if"] = DK_IF;
4874 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4875 DirectiveKindMap[".ifge"] = DK_IFGE;
4876 DirectiveKindMap[".ifgt"] = DK_IFGT;
4877 DirectiveKindMap[".ifle"] = DK_IFLE;
4878 DirectiveKindMap[".iflt"] = DK_IFLT;
4879 DirectiveKindMap[".ifne"] = DK_IFNE;
4880 DirectiveKindMap[".ifb"] = DK_IFB;
4881 DirectiveKindMap[".ifnb"] = DK_IFNB;
4882 DirectiveKindMap[".ifc"] = DK_IFC;
4883 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4884 DirectiveKindMap[".ifnc"] = DK_IFNC;
4885 DirectiveKindMap[".ifnes"] = DK_IFNES;
4886 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4887 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4888 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4889 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4890 DirectiveKindMap[".else"] = DK_ELSE;
4891 DirectiveKindMap[".end"] = DK_END;
4892 DirectiveKindMap[".endif"] = DK_ENDIF;
4893 DirectiveKindMap[".skip"] = DK_SKIP;
4894 DirectiveKindMap[".space"] = DK_SPACE;
4895 DirectiveKindMap[".file"] = DK_FILE;
4896 DirectiveKindMap[".line"] = DK_LINE;
4897 DirectiveKindMap[".loc"] = DK_LOC;
4898 DirectiveKindMap[".stabs"] = DK_STABS;
4899 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4900 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
4901 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4902 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4903 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
4904 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
4905 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
4906 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4907 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
4908 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4909 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4910 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4911 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4912 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4913 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4914 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4915 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4916 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4917 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4918 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4919 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4920 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4921 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4922 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4923 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4924 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4925 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4926 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4927 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4928 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4929 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4930 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4931 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4932 DirectiveKindMap[".macro"] = DK_MACRO;
4933 DirectiveKindMap[".exitm"] = DK_EXITM;
4934 DirectiveKindMap[".endm"] = DK_ENDM;
4935 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4936 DirectiveKindMap[".purgem"] = DK_PURGEM;
4937 DirectiveKindMap[".err"] = DK_ERR;
4938 DirectiveKindMap[".error"] = DK_ERROR;
4939 DirectiveKindMap[".warning"] = DK_WARNING;
4940 DirectiveKindMap[".reloc"] = DK_RELOC;
4941 DirectiveKindMap[".dc"] = DK_DC;
4942 DirectiveKindMap[".dc.a"] = DK_DC_A;
4943 DirectiveKindMap[".dc.b"] = DK_DC_B;
4944 DirectiveKindMap[".dc.d"] = DK_DC_D;
4945 DirectiveKindMap[".dc.l"] = DK_DC_L;
4946 DirectiveKindMap[".dc.s"] = DK_DC_S;
4947 DirectiveKindMap[".dc.w"] = DK_DC_W;
4948 DirectiveKindMap[".dc.x"] = DK_DC_X;
4949 DirectiveKindMap[".dcb"] = DK_DCB;
4950 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4951 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4952 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4953 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4954 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4955 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
4956 DirectiveKindMap[".ds"] = DK_DS;
4957 DirectiveKindMap[".ds.b"] = DK_DS_B;
4958 DirectiveKindMap[".ds.d"] = DK_DS_D;
4959 DirectiveKindMap[".ds.l"] = DK_DS_L;
4960 DirectiveKindMap[".ds.p"] = DK_DS_P;
4961 DirectiveKindMap[".ds.s"] = DK_DS_S;
4962 DirectiveKindMap[".ds.w"] = DK_DS_W;
4963 DirectiveKindMap[".ds.x"] = DK_DS_X;
4966 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4967 AsmToken EndToken, StartToken = getTok();
4969 unsigned NestLevel = 0;
4971 // Check whether we have reached the end of the file.
4972 if (getLexer().is(AsmToken::Eof)) {
4973 printError(DirectiveLoc, "no matching '.endr' in definition");
4977 if (Lexer.is(AsmToken::Identifier) &&
4978 (getTok().getIdentifier() == ".rept" ||
4979 getTok().getIdentifier() == ".irp" ||
4980 getTok().getIdentifier() == ".irpc")) {
4984 // Otherwise, check whether we have reached the .endr.
4985 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4986 if (NestLevel == 0) {
4987 EndToken = getTok();
4989 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4990 printError(getTok().getLoc(),
4991 "unexpected token in '.endr' directive");
4999 // Otherwise, scan till the end of the statement.
5000 eatToEndOfStatement();
5003 const char *BodyStart = StartToken.getLoc().getPointer();
5004 const char *BodyEnd = EndToken.getLoc().getPointer();
5005 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5007 // We Are Anonymous.
5008 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5009 return &MacroLikeBodies.back();
5012 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5013 raw_svector_ostream &OS) {
5016 std::unique_ptr<MemoryBuffer> Instantiation =
5017 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5019 // Create the macro instantiation object and add to the current macro
5020 // instantiation stack.
5021 MacroInstantiation *MI = new MacroInstantiation(
5022 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5023 ActiveMacros.push_back(MI);
5025 // Jump to the macro instantiation and prime the lexer.
5026 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5027 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5031 /// parseDirectiveRept
5032 /// ::= .rep | .rept count
5033 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5034 const MCExpr *CountExpr;
5035 SMLoc CountLoc = getTok().getLoc();
5036 if (parseExpression(CountExpr))
5040 if (!CountExpr->evaluateAsAbsolute(Count)) {
5041 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5044 if (check(Count < 0, CountLoc, "Count is negative") ||
5045 parseToken(AsmToken::EndOfStatement,
5046 "unexpected token in '" + Dir + "' directive"))
5049 // Lex the rept definition.
5050 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5054 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5055 // to hold the macro body with substitutions.
5056 SmallString<256> Buf;
5057 raw_svector_ostream OS(Buf);
5059 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5060 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5063 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5068 /// parseDirectiveIrp
5069 /// ::= .irp symbol,values
5070 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5071 MCAsmMacroParameter Parameter;
5072 MCAsmMacroArguments A;
5073 if (check(parseIdentifier(Parameter.Name),
5074 "expected identifier in '.irp' directive") ||
5075 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5076 parseMacroArguments(nullptr, A) ||
5077 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5080 // Lex the irp definition.
5081 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5085 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5086 // to hold the macro body with substitutions.
5087 SmallString<256> Buf;
5088 raw_svector_ostream OS(Buf);
5090 for (const MCAsmMacroArgument &Arg : A) {
5091 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5092 // This is undocumented, but GAS seems to support it.
5093 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5097 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5102 /// parseDirectiveIrpc
5103 /// ::= .irpc symbol,values
5104 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5105 MCAsmMacroParameter Parameter;
5106 MCAsmMacroArguments A;
5108 if (check(parseIdentifier(Parameter.Name),
5109 "expected identifier in '.irpc' directive") ||
5110 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5111 parseMacroArguments(nullptr, A))
5114 if (A.size() != 1 || A.front().size() != 1)
5115 return TokError("unexpected token in '.irpc' directive");
5117 // Eat the end of statement.
5118 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5121 // Lex the irpc definition.
5122 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5126 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5127 // to hold the macro body with substitutions.
5128 SmallString<256> Buf;
5129 raw_svector_ostream OS(Buf);
5131 StringRef Values = A.front().front().getString();
5132 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5133 MCAsmMacroArgument Arg;
5134 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5136 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5137 // This is undocumented, but GAS seems to support it.
5138 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5142 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5147 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5148 if (ActiveMacros.empty())
5149 return TokError("unmatched '.endr' directive");
5151 // The only .repl that should get here are the ones created by
5152 // instantiateMacroLikeBody.
5153 assert(getLexer().is(AsmToken::EndOfStatement));
5159 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5161 const MCExpr *Value;
5162 SMLoc ExprLoc = getLexer().getLoc();
5163 if (parseExpression(Value))
5165 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5167 return Error(ExprLoc, "unexpected expression in _emit");
5168 uint64_t IntValue = MCE->getValue();
5169 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5170 return Error(ExprLoc, "literal value out of range for directive");
5172 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5176 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5177 const MCExpr *Value;
5178 SMLoc ExprLoc = getLexer().getLoc();
5179 if (parseExpression(Value))
5181 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5183 return Error(ExprLoc, "unexpected expression in align");
5184 uint64_t IntValue = MCE->getValue();
5185 if (!isPowerOf2_64(IntValue))
5186 return Error(ExprLoc, "literal value not a power of two greater then zero");
5188 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5192 // We are comparing pointers, but the pointers are relative to a single string.
5193 // Thus, this should always be deterministic.
5194 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5195 const AsmRewrite *AsmRewriteB) {
5196 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5198 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5201 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5202 // rewrite to the same location. Make sure the SizeDirective rewrite is
5203 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5204 // ensures the sort algorithm is stable.
5205 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5206 AsmRewritePrecedence[AsmRewriteB->Kind])
5209 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5210 AsmRewritePrecedence[AsmRewriteB->Kind])
5212 llvm_unreachable("Unstable rewrite sort.");
5215 bool AsmParser::parseMSInlineAsm(
5216 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5217 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5218 SmallVectorImpl<std::string> &Constraints,
5219 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5220 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5221 SmallVector<void *, 4> InputDecls;
5222 SmallVector<void *, 4> OutputDecls;
5223 SmallVector<bool, 4> InputDeclsAddressOf;
5224 SmallVector<bool, 4> OutputDeclsAddressOf;
5225 SmallVector<std::string, 4> InputConstraints;
5226 SmallVector<std::string, 4> OutputConstraints;
5227 SmallVector<unsigned, 4> ClobberRegs;
5229 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5234 // While we have input, parse each statement.
5235 unsigned InputIdx = 0;
5236 unsigned OutputIdx = 0;
5237 while (getLexer().isNot(AsmToken::Eof)) {
5238 // Parse curly braces marking block start/end
5239 if (parseCurlyBlockScope(AsmStrRewrites))
5242 ParseStatementInfo Info(&AsmStrRewrites);
5243 bool StatementErr = parseStatement(Info, &SI);
5245 if (StatementErr || Info.ParseError) {
5246 // Emit pending errors if any exist.
5247 printPendingErrors();
5251 // No pending error should exist here.
5252 assert(!hasPendingError() && "unexpected error from parseStatement");
5254 if (Info.Opcode == ~0U)
5257 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5259 // Build the list of clobbers, outputs and inputs.
5260 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5261 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5264 if (Operand.isImm())
5267 // Register operand.
5268 if (Operand.isReg() && !Operand.needAddressOf() &&
5269 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5270 unsigned NumDefs = Desc.getNumDefs();
5272 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5273 ClobberRegs.push_back(Operand.getReg());
5277 // Expr/Input or Output.
5278 StringRef SymName = Operand.getSymName();
5279 if (SymName.empty())
5282 void *OpDecl = Operand.getOpDecl();
5286 bool isOutput = (i == 1) && Desc.mayStore();
5287 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5290 OutputDecls.push_back(OpDecl);
5291 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5292 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5293 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5295 InputDecls.push_back(OpDecl);
5296 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5297 InputConstraints.push_back(Operand.getConstraint().str());
5298 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5302 // Consider implicit defs to be clobbers. Think of cpuid and push.
5303 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5304 Desc.getNumImplicitDefs());
5305 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5308 // Set the number of Outputs and Inputs.
5309 NumOutputs = OutputDecls.size();
5310 NumInputs = InputDecls.size();
5312 // Set the unique clobbers.
5313 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5314 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5316 Clobbers.assign(ClobberRegs.size(), std::string());
5317 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5318 raw_string_ostream OS(Clobbers[I]);
5319 IP->printRegName(OS, ClobberRegs[I]);
5322 // Merge the various outputs and inputs. Output are expected first.
5323 if (NumOutputs || NumInputs) {
5324 unsigned NumExprs = NumOutputs + NumInputs;
5325 OpDecls.resize(NumExprs);
5326 Constraints.resize(NumExprs);
5327 for (unsigned i = 0; i < NumOutputs; ++i) {
5328 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5329 Constraints[i] = OutputConstraints[i];
5331 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5332 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5333 Constraints[j] = InputConstraints[i];
5337 // Build the IR assembly string.
5338 std::string AsmStringIR;
5339 raw_string_ostream OS(AsmStringIR);
5340 StringRef ASMString =
5341 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5342 const char *AsmStart = ASMString.begin();
5343 const char *AsmEnd = ASMString.end();
5344 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5345 for (const AsmRewrite &AR : AsmStrRewrites) {
5346 AsmRewriteKind Kind = AR.Kind;
5347 if (Kind == AOK_Delete)
5350 const char *Loc = AR.Loc.getPointer();
5351 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5353 // Emit everything up to the immediate/expression.
5354 if (unsigned Len = Loc - AsmStart)
5355 OS << StringRef(AsmStart, Len);
5357 // Skip the original expression.
5358 if (Kind == AOK_Skip) {
5359 AsmStart = Loc + AR.Len;
5363 unsigned AdditionalSkip = 0;
5364 // Rewrite expressions in $N notation.
5369 OS << "$$" << AR.Val;
5375 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5378 OS << '$' << InputIdx++;
5381 OS << '$' << OutputIdx++;
5383 case AOK_SizeDirective:
5386 case 8: OS << "byte ptr "; break;
5387 case 16: OS << "word ptr "; break;
5388 case 32: OS << "dword ptr "; break;
5389 case 64: OS << "qword ptr "; break;
5390 case 80: OS << "xword ptr "; break;
5391 case 128: OS << "xmmword ptr "; break;
5392 case 256: OS << "ymmword ptr "; break;
5399 // MS alignment directives are measured in bytes. If the native assembler
5400 // measures alignment in bytes, we can pass it straight through.
5402 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5405 // Alignment is in log2 form, so print that instead and skip the original
5407 unsigned Val = AR.Val;
5409 assert(Val < 10 && "Expected alignment less then 2^10.");
5410 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5416 case AOK_DotOperator:
5417 // Insert the dot if the user omitted it.
5419 if (AsmStringIR.back() != '.')
5423 case AOK_EndOfStatement:
5428 // Skip the original expression.
5429 AsmStart = Loc + AR.Len + AdditionalSkip;
5432 // Emit the remainder of the asm string.
5433 if (AsmStart != AsmEnd)
5434 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5436 AsmString = OS.str();
5441 namespace MCParserUtils {
5443 /// Returns whether the given symbol is used anywhere in the given expression,
5444 /// or subexpressions.
5445 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5446 switch (Value->getKind()) {
5447 case MCExpr::Binary: {
5448 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5449 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5450 isSymbolUsedInExpression(Sym, BE->getRHS());
5452 case MCExpr::Target:
5453 case MCExpr::Constant:
5455 case MCExpr::SymbolRef: {
5457 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5459 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5463 return isSymbolUsedInExpression(
5464 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5467 llvm_unreachable("Unknown expr kind!");
5470 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5471 MCAsmParser &Parser, MCSymbol *&Sym,
5472 const MCExpr *&Value) {
5474 // FIXME: Use better location, we should use proper tokens.
5475 SMLoc EqualLoc = Parser.getTok().getLoc();
5477 if (Parser.parseExpression(Value)) {
5478 return Parser.TokError("missing expression");
5481 // Note: we don't count b as used in "a = b". This is to allow
5485 if (Parser.parseToken(AsmToken::EndOfStatement))
5488 // Validate that the LHS is allowed to be a variable (either it has not been
5489 // used as a symbol, or it is an absolute symbol).
5490 Sym = Parser.getContext().lookupSymbol(Name);
5492 // Diagnose assignment to a label.
5494 // FIXME: Diagnostics. Note the location of the definition as a label.
5495 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5496 if (isSymbolUsedInExpression(Sym, Value))
5497 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5498 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5500 ; // Allow redefinitions of undefined symbols only used in directives.
5501 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5502 ; // Allow redefinitions of variables that haven't yet been used.
5503 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5504 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5505 else if (!Sym->isVariable())
5506 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5507 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5508 return Parser.Error(EqualLoc,
5509 "invalid reassignment of non-absolute variable '" +
5511 } else if (Name == ".") {
5512 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5515 Sym = Parser.getContext().getOrCreateSymbol(Name);
5517 Sym->setRedefinable(allow_redef);
5522 } // end namespace MCParserUtils
5523 } // end namespace llvm
5525 /// \brief Create an MCAsmParser instance.
5526 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5527 MCStreamer &Out, const MCAsmInfo &MAI,
5529 return new AsmParser(SM, C, Out, MAI, CB);