[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / llvm / lib / MC / MCParser / AsmParser.cpp
blobb36c5f067a95392cd4b219ca903ec67eef3253f8
1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements a parser for assembly files similar to gas syntax.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/Dwarf.h"
25 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeView.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDirectives.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCParser/AsmCond.h"
36 #include "llvm/MC/MCParser/AsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmLexer.h"
38 #include "llvm/MC/MCParser/MCAsmParser.h"
39 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
40 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
41 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
42 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
43 #include "llvm/MC/MCRegisterInfo.h"
44 #include "llvm/MC/MCSection.h"
45 #include "llvm/MC/MCStreamer.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/MCTargetOptions.h"
48 #include "llvm/MC/MCValue.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MD5.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/MemoryBuffer.h"
55 #include "llvm/Support/SMLoc.h"
56 #include "llvm/Support/SourceMgr.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cctype>
61 #include <climits>
62 #include <cstddef>
63 #include <cstdint>
64 #include <deque>
65 #include <memory>
66 #include <optional>
67 #include <sstream>
68 #include <string>
69 #include <tuple>
70 #include <utility>
71 #include <vector>
73 using namespace llvm;
75 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
77 namespace {
79 /// Helper types for tracking macro definitions.
80 typedef std::vector<AsmToken> MCAsmMacroArgument;
81 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
83 /// Helper class for storing information about an active macro
84 /// instantiation.
85 struct MacroInstantiation {
86 /// The location of the instantiation.
87 SMLoc InstantiationLoc;
89 /// The buffer where parsing should resume upon instantiation completion.
90 unsigned ExitBuffer;
92 /// The location where parsing should resume upon instantiation completion.
93 SMLoc ExitLoc;
95 /// The depth of TheCondStack at the start of the instantiation.
96 size_t CondStackDepth;
99 struct ParseStatementInfo {
100 /// The parsed operands from the last parsed statement.
101 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
103 /// The opcode from the last parsed instruction.
104 unsigned Opcode = ~0U;
106 /// Was there an error parsing the inline assembly?
107 bool ParseError = false;
109 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
111 ParseStatementInfo() = delete;
112 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
113 : AsmRewrites(rewrites) {}
116 /// The concrete assembly parser instance.
117 class AsmParser : public MCAsmParser {
118 private:
119 AsmLexer Lexer;
120 MCContext &Ctx;
121 MCStreamer &Out;
122 const MCAsmInfo &MAI;
123 SourceMgr &SrcMgr;
124 SourceMgr::DiagHandlerTy SavedDiagHandler;
125 void *SavedDiagContext;
126 std::unique_ptr<MCAsmParserExtension> PlatformParser;
127 SMLoc StartTokLoc;
129 /// This is the current buffer index we're lexing from as managed by the
130 /// SourceMgr object.
131 unsigned CurBuffer;
133 AsmCond TheCondState;
134 std::vector<AsmCond> TheCondStack;
136 /// maps directive names to handler methods in parser
137 /// extensions. Extensions register themselves in this map by calling
138 /// addDirectiveHandler.
139 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
141 /// Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
153 /// The values from the last parsed cpp hash file line comment if any.
154 struct CppHashInfoTy {
155 StringRef Filename;
156 int64_t LineNumber;
157 SMLoc Loc;
158 unsigned Buf;
159 CppHashInfoTy() : LineNumber(0), Buf(0) {}
161 CppHashInfoTy CppHashInfo;
163 /// The filename from the first cpp hash file line comment, if any.
164 StringRef FirstCppHashFilename;
166 /// List of forward directional labels for diagnosis at the end.
167 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
169 SmallSet<StringRef, 2> LTODiscardSymbols;
171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect = ~0U;
174 /// is Darwin compatibility enabled?
175 bool IsDarwin = false;
177 /// Are we parsing ms-style inline assembly?
178 bool ParsingMSInlineAsm = false;
180 /// Did we already inform the user about inconsistent MD5 usage?
181 bool ReportedInconsistentMD5 = false;
183 // Is alt macro mode enabled.
184 bool AltMacroMode = false;
186 protected:
187 virtual bool parseStatement(ParseStatementInfo &Info,
188 MCAsmParserSemaCallback *SI);
190 /// This routine uses the target specific ParseInstruction function to
191 /// parse an instruction into Operands, and then call the target specific
192 /// MatchAndEmit function to match and emit the instruction.
193 bool parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
194 StringRef IDVal, AsmToken ID,
195 SMLoc IDLoc);
197 /// Should we emit DWARF describing this assembler source? (Returns false if
198 /// the source has .file directives, which means we don't want to generate
199 /// info describing the assembler source itself.)
200 bool enabledGenDwarfForAssembly();
202 public:
203 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
204 const MCAsmInfo &MAI, unsigned CB);
205 AsmParser(const AsmParser &) = delete;
206 AsmParser &operator=(const AsmParser &) = delete;
207 ~AsmParser() override;
209 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
211 void addDirectiveHandler(StringRef Directive,
212 ExtensionDirectiveHandler Handler) override {
213 ExtensionDirectiveMap[Directive] = Handler;
216 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
217 DirectiveKindMap[Directive.lower()] = DirectiveKindMap[Alias.lower()];
220 /// @name MCAsmParser Interface
221 /// {
223 SourceMgr &getSourceManager() override { return SrcMgr; }
224 MCAsmLexer &getLexer() override { return Lexer; }
225 MCContext &getContext() override { return Ctx; }
226 MCStreamer &getStreamer() override { return Out; }
228 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
230 unsigned getAssemblerDialect() override {
231 if (AssemblerDialect == ~0U)
232 return MAI.getAssemblerDialect();
233 else
234 return AssemblerDialect;
236 void setAssemblerDialect(unsigned i) override {
237 AssemblerDialect = i;
240 void Note(SMLoc L, const Twine &Msg, SMRange Range = std::nullopt) override;
241 bool Warning(SMLoc L, const Twine &Msg,
242 SMRange Range = std::nullopt) override;
243 bool printError(SMLoc L, const Twine &Msg,
244 SMRange Range = std::nullopt) override;
246 const AsmToken &Lex() override;
248 void setParsingMSInlineAsm(bool V) override {
249 ParsingMSInlineAsm = V;
250 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
251 // hex integer literals.
252 Lexer.setLexMasmIntegers(V);
254 bool isParsingMSInlineAsm() override { return ParsingMSInlineAsm; }
256 bool discardLTOSymbol(StringRef Name) const override {
257 return LTODiscardSymbols.contains(Name);
260 bool parseMSInlineAsm(std::string &AsmString, unsigned &NumOutputs,
261 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,
271 AsmTypeInfo *TypeInfo) override;
272 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
273 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
274 SMLoc &EndLoc) override;
275 bool parseAbsoluteExpression(int64_t &Res) override;
277 /// Parse a floating point expression using the float \p Semantics
278 /// and set \p Res to the value.
279 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
281 /// Parse an identifier or string (as a quoted identifier)
282 /// and set \p Res to the identifier contents.
283 bool parseIdentifier(StringRef &Res) override;
284 void eatToEndOfStatement() override;
286 bool checkForValidSection() override;
288 /// }
290 private:
291 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
292 bool parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo = true);
294 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
295 ArrayRef<MCAsmMacroParameter> Parameters);
296 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
297 ArrayRef<MCAsmMacroParameter> Parameters,
298 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
299 SMLoc L);
301 /// Are macros enabled in the parser?
302 bool areMacrosEnabled() {return MacrosEnabledFlag;}
304 /// Control a flag in the parser that enables or disables macros.
305 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
307 /// Are we inside a macro instantiation?
308 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
310 /// Handle entry to macro instantiation.
312 /// \param M The macro.
313 /// \param NameLoc Instantiation location.
314 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
316 /// Handle exit from macro instantiation.
317 void handleMacroExit();
319 /// Extract AsmTokens for a macro argument.
320 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
322 /// Parse all macro arguments for a given macro.
323 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
325 void printMacroInstantiations();
326 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
327 SMRange Range = std::nullopt) const {
328 ArrayRef<SMRange> Ranges(Range);
329 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
331 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
333 /// Enter the specified file. This returns true on failure.
334 bool enterIncludeFile(const std::string &Filename);
336 /// Process the specified file for the .incbin directive.
337 /// This returns true on failure.
338 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
339 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
341 /// Reset the current lexer position to that given by \p Loc. The
342 /// current token is not set; clients should ensure Lex() is called
343 /// subsequently.
345 /// \param InBuffer If not 0, should be the known buffer id that contains the
346 /// location.
347 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
349 /// Parse up to the end of statement and a return the contents from the
350 /// current token until the end of the statement; the current token on exit
351 /// will be either the EndOfStatement or EOF.
352 StringRef parseStringToEndOfStatement() override;
354 /// Parse until the end of a statement or a comma is encountered,
355 /// return the contents from the current token up to the end or comma.
356 StringRef parseStringToComma();
358 enum class AssignmentKind {
359 Set,
360 Equiv,
361 Equal,
362 LTOSetConditional,
365 bool parseAssignment(StringRef Name, AssignmentKind Kind);
367 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
368 MCBinaryExpr::Opcode &Kind);
370 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
371 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
372 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
374 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
376 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
377 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
379 // Generic (target and platform independent) directive parsing.
380 enum DirectiveKind {
381 DK_NO_DIRECTIVE, // Placeholder
382 DK_SET,
383 DK_EQU,
384 DK_EQUIV,
385 DK_ASCII,
386 DK_ASCIZ,
387 DK_STRING,
388 DK_BYTE,
389 DK_SHORT,
390 DK_RELOC,
391 DK_VALUE,
392 DK_2BYTE,
393 DK_LONG,
394 DK_INT,
395 DK_4BYTE,
396 DK_QUAD,
397 DK_8BYTE,
398 DK_OCTA,
399 DK_DC,
400 DK_DC_A,
401 DK_DC_B,
402 DK_DC_D,
403 DK_DC_L,
404 DK_DC_S,
405 DK_DC_W,
406 DK_DC_X,
407 DK_DCB,
408 DK_DCB_B,
409 DK_DCB_D,
410 DK_DCB_L,
411 DK_DCB_S,
412 DK_DCB_W,
413 DK_DCB_X,
414 DK_DS,
415 DK_DS_B,
416 DK_DS_D,
417 DK_DS_L,
418 DK_DS_P,
419 DK_DS_S,
420 DK_DS_W,
421 DK_DS_X,
422 DK_SINGLE,
423 DK_FLOAT,
424 DK_DOUBLE,
425 DK_ALIGN,
426 DK_ALIGN32,
427 DK_BALIGN,
428 DK_BALIGNW,
429 DK_BALIGNL,
430 DK_P2ALIGN,
431 DK_P2ALIGNW,
432 DK_P2ALIGNL,
433 DK_ORG,
434 DK_FILL,
435 DK_ENDR,
436 DK_BUNDLE_ALIGN_MODE,
437 DK_BUNDLE_LOCK,
438 DK_BUNDLE_UNLOCK,
439 DK_ZERO,
440 DK_EXTERN,
441 DK_GLOBL,
442 DK_GLOBAL,
443 DK_LAZY_REFERENCE,
444 DK_NO_DEAD_STRIP,
445 DK_SYMBOL_RESOLVER,
446 DK_PRIVATE_EXTERN,
447 DK_REFERENCE,
448 DK_WEAK_DEFINITION,
449 DK_WEAK_REFERENCE,
450 DK_WEAK_DEF_CAN_BE_HIDDEN,
451 DK_COLD,
452 DK_COMM,
453 DK_COMMON,
454 DK_LCOMM,
455 DK_ABORT,
456 DK_INCLUDE,
457 DK_INCBIN,
458 DK_CODE16,
459 DK_CODE16GCC,
460 DK_REPT,
461 DK_IRP,
462 DK_IRPC,
463 DK_IF,
464 DK_IFEQ,
465 DK_IFGE,
466 DK_IFGT,
467 DK_IFLE,
468 DK_IFLT,
469 DK_IFNE,
470 DK_IFB,
471 DK_IFNB,
472 DK_IFC,
473 DK_IFEQS,
474 DK_IFNC,
475 DK_IFNES,
476 DK_IFDEF,
477 DK_IFNDEF,
478 DK_IFNOTDEF,
479 DK_ELSEIF,
480 DK_ELSE,
481 DK_ENDIF,
482 DK_SPACE,
483 DK_SKIP,
484 DK_FILE,
485 DK_LINE,
486 DK_LOC,
487 DK_STABS,
488 DK_CV_FILE,
489 DK_CV_FUNC_ID,
490 DK_CV_INLINE_SITE_ID,
491 DK_CV_LOC,
492 DK_CV_LINETABLE,
493 DK_CV_INLINE_LINETABLE,
494 DK_CV_DEF_RANGE,
495 DK_CV_STRINGTABLE,
496 DK_CV_STRING,
497 DK_CV_FILECHECKSUMS,
498 DK_CV_FILECHECKSUM_OFFSET,
499 DK_CV_FPO_DATA,
500 DK_CFI_SECTIONS,
501 DK_CFI_STARTPROC,
502 DK_CFI_ENDPROC,
503 DK_CFI_DEF_CFA,
504 DK_CFI_DEF_CFA_OFFSET,
505 DK_CFI_ADJUST_CFA_OFFSET,
506 DK_CFI_DEF_CFA_REGISTER,
507 DK_CFI_LLVM_DEF_ASPACE_CFA,
508 DK_CFI_OFFSET,
509 DK_CFI_REL_OFFSET,
510 DK_CFI_PERSONALITY,
511 DK_CFI_LSDA,
512 DK_CFI_REMEMBER_STATE,
513 DK_CFI_RESTORE_STATE,
514 DK_CFI_SAME_VALUE,
515 DK_CFI_RESTORE,
516 DK_CFI_ESCAPE,
517 DK_CFI_RETURN_COLUMN,
518 DK_CFI_SIGNAL_FRAME,
519 DK_CFI_UNDEFINED,
520 DK_CFI_REGISTER,
521 DK_CFI_WINDOW_SAVE,
522 DK_CFI_B_KEY_FRAME,
523 DK_MACROS_ON,
524 DK_MACROS_OFF,
525 DK_ALTMACRO,
526 DK_NOALTMACRO,
527 DK_MACRO,
528 DK_EXITM,
529 DK_ENDM,
530 DK_ENDMACRO,
531 DK_PURGEM,
532 DK_SLEB128,
533 DK_ULEB128,
534 DK_ERR,
535 DK_ERROR,
536 DK_WARNING,
537 DK_PRINT,
538 DK_ADDRSIG,
539 DK_ADDRSIG_SYM,
540 DK_PSEUDO_PROBE,
541 DK_LTO_DISCARD,
542 DK_LTO_SET_CONDITIONAL,
543 DK_CFI_MTE_TAGGED_FRAME,
544 DK_MEMTAG,
545 DK_END
548 /// Maps directive name --> DirectiveKind enum, for
549 /// directives parsed by this class.
550 StringMap<DirectiveKind> DirectiveKindMap;
552 // Codeview def_range type parsing.
553 enum CVDefRangeType {
554 CVDR_DEFRANGE = 0, // Placeholder
555 CVDR_DEFRANGE_REGISTER,
556 CVDR_DEFRANGE_FRAMEPOINTER_REL,
557 CVDR_DEFRANGE_SUBFIELD_REGISTER,
558 CVDR_DEFRANGE_REGISTER_REL
561 /// Maps Codeview def_range types --> CVDefRangeType enum, for
562 /// Codeview def_range types parsed by this class.
563 StringMap<CVDefRangeType> CVDefRangeTypeMap;
565 // ".ascii", ".asciz", ".string"
566 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
567 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
568 bool parseDirectiveValue(StringRef IDVal,
569 unsigned Size); // ".byte", ".long", ...
570 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
571 bool parseDirectiveRealValue(StringRef IDVal,
572 const fltSemantics &); // ".single", ...
573 bool parseDirectiveFill(); // ".fill"
574 bool parseDirectiveZero(); // ".zero"
575 // ".set", ".equ", ".equiv", ".lto_set_conditional"
576 bool parseDirectiveSet(StringRef IDVal, AssignmentKind Kind);
577 bool parseDirectiveOrg(); // ".org"
578 // ".align{,32}", ".p2align{,w,l}"
579 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
581 // ".file", ".line", ".loc", ".stabs"
582 bool parseDirectiveFile(SMLoc DirectiveLoc);
583 bool parseDirectiveLine();
584 bool parseDirectiveLoc();
585 bool parseDirectiveStabs();
587 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
588 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
589 bool parseDirectiveCVFile();
590 bool parseDirectiveCVFuncId();
591 bool parseDirectiveCVInlineSiteId();
592 bool parseDirectiveCVLoc();
593 bool parseDirectiveCVLinetable();
594 bool parseDirectiveCVInlineLinetable();
595 bool parseDirectiveCVDefRange();
596 bool parseDirectiveCVString();
597 bool parseDirectiveCVStringTable();
598 bool parseDirectiveCVFileChecksums();
599 bool parseDirectiveCVFileChecksumOffset();
600 bool parseDirectiveCVFPOData();
602 // .cfi directives
603 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
604 bool parseDirectiveCFIWindowSave(SMLoc DirectiveLoc);
605 bool parseDirectiveCFISections();
606 bool parseDirectiveCFIStartProc();
607 bool parseDirectiveCFIEndProc();
608 bool parseDirectiveCFIDefCfaOffset(SMLoc DirectiveLoc);
609 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
610 bool parseDirectiveCFIAdjustCfaOffset(SMLoc DirectiveLoc);
611 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
612 bool parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc);
613 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
614 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
615 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
616 bool parseDirectiveCFIRememberState(SMLoc DirectiveLoc);
617 bool parseDirectiveCFIRestoreState(SMLoc DirectiveLoc);
618 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
619 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
620 bool parseDirectiveCFIEscape(SMLoc DirectiveLoc);
621 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
622 bool parseDirectiveCFISignalFrame(SMLoc DirectiveLoc);
623 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
625 // macro directives
626 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
627 bool parseDirectiveExitMacro(StringRef Directive);
628 bool parseDirectiveEndMacro(StringRef Directive);
629 bool parseDirectiveMacro(SMLoc DirectiveLoc);
630 bool parseDirectiveMacrosOnOff(StringRef Directive);
631 // alternate macro mode directives
632 bool parseDirectiveAltmacro(StringRef Directive);
633 // ".bundle_align_mode"
634 bool parseDirectiveBundleAlignMode();
635 // ".bundle_lock"
636 bool parseDirectiveBundleLock();
637 // ".bundle_unlock"
638 bool parseDirectiveBundleUnlock();
640 // ".space", ".skip"
641 bool parseDirectiveSpace(StringRef IDVal);
643 // ".dcb"
644 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
645 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
646 // ".ds"
647 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
649 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
650 bool parseDirectiveLEB128(bool Signed);
652 /// Parse a directive like ".globl" which
653 /// accepts a single symbol (which should be a label or an external).
654 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
656 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
658 bool parseDirectiveAbort(); // ".abort"
659 bool parseDirectiveInclude(); // ".include"
660 bool parseDirectiveIncbin(); // ".incbin"
662 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
663 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
664 // ".ifb" or ".ifnb", depending on ExpectBlank.
665 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
666 // ".ifc" or ".ifnc", depending on ExpectEqual.
667 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
668 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
669 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
670 // ".ifdef" or ".ifndef", depending on expect_defined
671 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
672 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
673 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
674 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
675 bool parseEscapedString(std::string &Data) override;
676 bool parseAngleBracketString(std::string &Data) override;
678 const MCExpr *applyModifierToExpr(const MCExpr *E,
679 MCSymbolRefExpr::VariantKind Variant);
681 // Macro-like directives
682 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
683 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
684 raw_svector_ostream &OS);
685 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
686 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
687 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
688 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
690 // "_emit" or "__emit"
691 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
692 size_t Len);
694 // "align"
695 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
697 // "end"
698 bool parseDirectiveEnd(SMLoc DirectiveLoc);
700 // ".err" or ".error"
701 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
703 // ".warning"
704 bool parseDirectiveWarning(SMLoc DirectiveLoc);
706 // .print <double-quotes-string>
707 bool parseDirectivePrint(SMLoc DirectiveLoc);
709 // .pseudoprobe
710 bool parseDirectivePseudoProbe();
712 // ".lto_discard"
713 bool parseDirectiveLTODiscard();
715 // Directives to support address-significance tables.
716 bool parseDirectiveAddrsig();
717 bool parseDirectiveAddrsigSym();
719 void initializeDirectiveKindMap();
720 void initializeCVDefRangeTypeMap();
723 class HLASMAsmParser final : public AsmParser {
724 private:
725 MCAsmLexer &Lexer;
726 MCStreamer &Out;
728 void lexLeadingSpaces() {
729 while (Lexer.is(AsmToken::Space))
730 Lexer.Lex();
733 bool parseAsHLASMLabel(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI);
734 bool parseAsMachineInstruction(ParseStatementInfo &Info,
735 MCAsmParserSemaCallback *SI);
737 public:
738 HLASMAsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
739 const MCAsmInfo &MAI, unsigned CB = 0)
740 : AsmParser(SM, Ctx, Out, MAI, CB), Lexer(getLexer()), Out(Out) {
741 Lexer.setSkipSpace(false);
742 Lexer.setAllowHashInIdentifier(true);
743 Lexer.setLexHLASMIntegers(true);
744 Lexer.setLexHLASMStrings(true);
747 ~HLASMAsmParser() { Lexer.setSkipSpace(true); }
749 bool parseStatement(ParseStatementInfo &Info,
750 MCAsmParserSemaCallback *SI) override;
753 } // end anonymous namespace
755 namespace llvm {
757 extern cl::opt<unsigned> AsmMacroMaxNestingDepth;
759 extern MCAsmParserExtension *createDarwinAsmParser();
760 extern MCAsmParserExtension *createELFAsmParser();
761 extern MCAsmParserExtension *createCOFFAsmParser();
762 extern MCAsmParserExtension *createGOFFAsmParser();
763 extern MCAsmParserExtension *createXCOFFAsmParser();
764 extern MCAsmParserExtension *createWasmAsmParser();
766 } // end namespace llvm
768 enum { DEFAULT_ADDRSPACE = 0 };
770 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
771 const MCAsmInfo &MAI, unsigned CB = 0)
772 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
773 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
774 HadError = false;
775 // Save the old handler.
776 SavedDiagHandler = SrcMgr.getDiagHandler();
777 SavedDiagContext = SrcMgr.getDiagContext();
778 // Set our own handler which calls the saved handler.
779 SrcMgr.setDiagHandler(DiagHandler, this);
780 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
781 // Make MCStreamer aware of the StartTokLoc for locations in diagnostics.
782 Out.setStartTokLocPtr(&StartTokLoc);
784 // Initialize the platform / file format parser.
785 switch (Ctx.getObjectFileType()) {
786 case MCContext::IsCOFF:
787 PlatformParser.reset(createCOFFAsmParser());
788 break;
789 case MCContext::IsMachO:
790 PlatformParser.reset(createDarwinAsmParser());
791 IsDarwin = true;
792 break;
793 case MCContext::IsELF:
794 PlatformParser.reset(createELFAsmParser());
795 break;
796 case MCContext::IsGOFF:
797 PlatformParser.reset(createGOFFAsmParser());
798 break;
799 case MCContext::IsSPIRV:
800 report_fatal_error(
801 "Need to implement createSPIRVAsmParser for SPIRV format.");
802 break;
803 case MCContext::IsWasm:
804 PlatformParser.reset(createWasmAsmParser());
805 break;
806 case MCContext::IsXCOFF:
807 PlatformParser.reset(createXCOFFAsmParser());
808 break;
809 case MCContext::IsDXContainer:
810 report_fatal_error("DXContainer is not supported yet");
811 break;
814 PlatformParser->Initialize(*this);
815 initializeDirectiveKindMap();
816 initializeCVDefRangeTypeMap();
818 NumOfMacroInstantiations = 0;
821 AsmParser::~AsmParser() {
822 assert((HadError || ActiveMacros.empty()) &&
823 "Unexpected active macro instantiation!");
825 // Remove MCStreamer's reference to the parser SMLoc.
826 Out.setStartTokLocPtr(nullptr);
827 // Restore the saved diagnostics handler and context for use during
828 // finalization.
829 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
832 void AsmParser::printMacroInstantiations() {
833 // Print the active macro instantiation stack.
834 for (std::vector<MacroInstantiation *>::const_reverse_iterator
835 it = ActiveMacros.rbegin(),
836 ie = ActiveMacros.rend();
837 it != ie; ++it)
838 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
839 "while in macro instantiation");
842 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
843 printPendingErrors();
844 printMessage(L, SourceMgr::DK_Note, Msg, Range);
845 printMacroInstantiations();
848 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
849 if(getTargetParser().getTargetOptions().MCNoWarn)
850 return false;
851 if (getTargetParser().getTargetOptions().MCFatalWarnings)
852 return Error(L, Msg, Range);
853 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
854 printMacroInstantiations();
855 return false;
858 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
859 HadError = true;
860 printMessage(L, SourceMgr::DK_Error, Msg, Range);
861 printMacroInstantiations();
862 return true;
865 bool AsmParser::enterIncludeFile(const std::string &Filename) {
866 std::string IncludedFile;
867 unsigned NewBuf =
868 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
869 if (!NewBuf)
870 return true;
872 CurBuffer = NewBuf;
873 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
874 return false;
877 /// Process the specified .incbin file by searching for it in the include paths
878 /// then just emitting the byte contents of the file to the streamer. This
879 /// returns true on failure.
880 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
881 const MCExpr *Count, SMLoc Loc) {
882 std::string IncludedFile;
883 unsigned NewBuf =
884 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
885 if (!NewBuf)
886 return true;
888 // Pick up the bytes from the file and emit them.
889 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
890 Bytes = Bytes.drop_front(Skip);
891 if (Count) {
892 int64_t Res;
893 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
894 return Error(Loc, "expected absolute expression");
895 if (Res < 0)
896 return Warning(Loc, "negative count has no effect");
897 Bytes = Bytes.take_front(Res);
899 getStreamer().emitBytes(Bytes);
900 return false;
903 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
904 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
905 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
906 Loc.getPointer());
909 const AsmToken &AsmParser::Lex() {
910 if (Lexer.getTok().is(AsmToken::Error))
911 Error(Lexer.getErrLoc(), Lexer.getErr());
913 // if it's a end of statement with a comment in it
914 if (getTok().is(AsmToken::EndOfStatement)) {
915 // if this is a line comment output it.
916 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
917 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
918 Out.addExplicitComment(Twine(getTok().getString()));
921 const AsmToken *tok = &Lexer.Lex();
923 // Parse comments here to be deferred until end of next statement.
924 while (tok->is(AsmToken::Comment)) {
925 if (MAI.preserveAsmComments())
926 Out.addExplicitComment(Twine(tok->getString()));
927 tok = &Lexer.Lex();
930 if (tok->is(AsmToken::Eof)) {
931 // If this is the end of an included file, pop the parent file off the
932 // include stack.
933 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
934 if (ParentIncludeLoc != SMLoc()) {
935 jumpToLoc(ParentIncludeLoc);
936 return Lex();
940 return *tok;
943 bool AsmParser::enabledGenDwarfForAssembly() {
944 // Check whether the user specified -g.
945 if (!getContext().getGenDwarfForAssembly())
946 return false;
947 // If we haven't encountered any .file directives (which would imply that
948 // the assembler source was produced with debug info already) then emit one
949 // describing the assembler source file itself.
950 if (getContext().getGenDwarfFileNumber() == 0) {
951 // Use the first #line directive for this, if any. It's preprocessed, so
952 // there is no checksum, and of course no source directive.
953 if (!FirstCppHashFilename.empty())
954 getContext().setMCLineTableRootFile(
955 /*CUID=*/0, getContext().getCompilationDir(), FirstCppHashFilename,
956 /*Cksum=*/std::nullopt, /*Source=*/std::nullopt);
957 const MCDwarfFile &RootFile =
958 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
959 getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective(
960 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
961 RootFile.Checksum, RootFile.Source));
963 return true;
966 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
967 LTODiscardSymbols.clear();
969 // Create the initial section, if requested.
970 if (!NoInitialTextSection)
971 Out.initSections(false, getTargetParser().getSTI());
973 // Prime the lexer.
974 Lex();
976 HadError = false;
977 AsmCond StartingCondState = TheCondState;
978 SmallVector<AsmRewrite, 4> AsmStrRewrites;
980 // If we are generating dwarf for assembly source files save the initial text
981 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
982 // emitting any actual debug info yet and haven't had a chance to parse any
983 // embedded .file directives.)
984 if (getContext().getGenDwarfForAssembly()) {
985 MCSection *Sec = getStreamer().getCurrentSectionOnly();
986 if (!Sec->getBeginSymbol()) {
987 MCSymbol *SectionStartSym = getContext().createTempSymbol();
988 getStreamer().emitLabel(SectionStartSym);
989 Sec->setBeginSymbol(SectionStartSym);
991 bool InsertResult = getContext().addGenDwarfSection(Sec);
992 assert(InsertResult && ".text section should not have debug info yet");
993 (void)InsertResult;
996 getTargetParser().onBeginOfFile();
998 // While we have input, parse each statement.
999 while (Lexer.isNot(AsmToken::Eof)) {
1000 ParseStatementInfo Info(&AsmStrRewrites);
1001 bool Parsed = parseStatement(Info, nullptr);
1003 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
1004 // for printing ErrMsg via Lex() only if no (presumably better) parser error
1005 // exists.
1006 if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
1007 Lex();
1010 // parseStatement returned true so may need to emit an error.
1011 printPendingErrors();
1013 // Skipping to the next line if needed.
1014 if (Parsed && !getLexer().isAtStartOfStatement())
1015 eatToEndOfStatement();
1018 getTargetParser().onEndOfFile();
1019 printPendingErrors();
1021 // All errors should have been emitted.
1022 assert(!hasPendingError() && "unexpected error from parseStatement");
1024 getTargetParser().flushPendingInstructions(getStreamer());
1026 if (TheCondState.TheCond != StartingCondState.TheCond ||
1027 TheCondState.Ignore != StartingCondState.Ignore)
1028 printError(getTok().getLoc(), "unmatched .ifs or .elses");
1029 // Check to see there are no empty DwarfFile slots.
1030 const auto &LineTables = getContext().getMCDwarfLineTables();
1031 if (!LineTables.empty()) {
1032 unsigned Index = 0;
1033 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
1034 if (File.Name.empty() && Index != 0)
1035 printError(getTok().getLoc(), "unassigned file number: " +
1036 Twine(Index) +
1037 " for .file directives");
1038 ++Index;
1042 // Check to see that all assembler local symbols were actually defined.
1043 // Targets that don't do subsections via symbols may not want this, though,
1044 // so conservatively exclude them. Only do this if we're finalizing, though,
1045 // as otherwise we won't necessarilly have seen everything yet.
1046 if (!NoFinalize) {
1047 if (MAI.hasSubsectionsViaSymbols()) {
1048 for (const auto &TableEntry : getContext().getSymbols()) {
1049 MCSymbol *Sym = TableEntry.getValue();
1050 // Variable symbols may not be marked as defined, so check those
1051 // explicitly. If we know it's a variable, we have a definition for
1052 // the purposes of this check.
1053 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
1054 // FIXME: We would really like to refer back to where the symbol was
1055 // first referenced for a source location. We need to add something
1056 // to track that. Currently, we just point to the end of the file.
1057 printError(getTok().getLoc(), "assembler local symbol '" +
1058 Sym->getName() + "' not defined");
1062 // Temporary symbols like the ones for directional jumps don't go in the
1063 // symbol table. They also need to be diagnosed in all (final) cases.
1064 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
1065 if (std::get<2>(LocSym)->isUndefined()) {
1066 // Reset the state of any "# line file" directives we've seen to the
1067 // context as it was at the diagnostic site.
1068 CppHashInfo = std::get<1>(LocSym);
1069 printError(std::get<0>(LocSym), "directional label undefined");
1073 // Finalize the output stream if there are no errors and if the client wants
1074 // us to.
1075 if (!HadError && !NoFinalize) {
1076 if (auto *TS = Out.getTargetStreamer())
1077 TS->emitConstantPools();
1079 Out.finish(Lexer.getLoc());
1082 return HadError || getContext().hadError();
1085 bool AsmParser::checkForValidSection() {
1086 if (!ParsingMSInlineAsm && !getStreamer().getCurrentSectionOnly()) {
1087 Out.initSections(false, getTargetParser().getSTI());
1088 return Error(getTok().getLoc(),
1089 "expected section directive before assembly directive");
1091 return false;
1094 /// Throw away the rest of the line for testing purposes.
1095 void AsmParser::eatToEndOfStatement() {
1096 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
1097 Lexer.Lex();
1099 // Eat EOL.
1100 if (Lexer.is(AsmToken::EndOfStatement))
1101 Lexer.Lex();
1104 StringRef AsmParser::parseStringToEndOfStatement() {
1105 const char *Start = getTok().getLoc().getPointer();
1107 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
1108 Lexer.Lex();
1110 const char *End = getTok().getLoc().getPointer();
1111 return StringRef(Start, End - Start);
1114 StringRef AsmParser::parseStringToComma() {
1115 const char *Start = getTok().getLoc().getPointer();
1117 while (Lexer.isNot(AsmToken::EndOfStatement) &&
1118 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
1119 Lexer.Lex();
1121 const char *End = getTok().getLoc().getPointer();
1122 return StringRef(Start, End - Start);
1125 /// Parse a paren expression and return it.
1126 /// NOTE: This assumes the leading '(' has already been consumed.
1128 /// parenexpr ::= expr)
1130 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1131 if (parseExpression(Res))
1132 return true;
1133 EndLoc = Lexer.getTok().getEndLoc();
1134 return parseRParen();
1137 /// Parse a bracket expression and return it.
1138 /// NOTE: This assumes the leading '[' has already been consumed.
1140 /// bracketexpr ::= expr]
1142 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1143 if (parseExpression(Res))
1144 return true;
1145 EndLoc = getTok().getEndLoc();
1146 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1147 return true;
1148 return false;
1151 /// Parse a primary expression and return it.
1152 /// primaryexpr ::= (parenexpr
1153 /// primaryexpr ::= symbol
1154 /// primaryexpr ::= number
1155 /// primaryexpr ::= '.'
1156 /// primaryexpr ::= ~,+,- primaryexpr
1157 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
1158 AsmTypeInfo *TypeInfo) {
1159 SMLoc FirstTokenLoc = getLexer().getLoc();
1160 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1161 switch (FirstTokenKind) {
1162 default:
1163 return TokError("unknown token in expression");
1164 // If we have an error assume that we've already handled it.
1165 case AsmToken::Error:
1166 return true;
1167 case AsmToken::Exclaim:
1168 Lex(); // Eat the operator.
1169 if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1170 return true;
1171 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
1172 return false;
1173 case AsmToken::Dollar:
1174 case AsmToken::Star:
1175 case AsmToken::At:
1176 case AsmToken::String:
1177 case AsmToken::Identifier: {
1178 StringRef Identifier;
1179 if (parseIdentifier(Identifier)) {
1180 // We may have failed but '$'|'*' may be a valid token in context of
1181 // the current PC.
1182 if (getTok().is(AsmToken::Dollar) || getTok().is(AsmToken::Star)) {
1183 bool ShouldGenerateTempSymbol = false;
1184 if ((getTok().is(AsmToken::Dollar) && MAI.getDollarIsPC()) ||
1185 (getTok().is(AsmToken::Star) && MAI.getStarIsPC()))
1186 ShouldGenerateTempSymbol = true;
1188 if (!ShouldGenerateTempSymbol)
1189 return Error(FirstTokenLoc, "invalid token in expression");
1191 // Eat the '$'|'*' token.
1192 Lex();
1193 // This is either a '$'|'*' reference, which references the current PC.
1194 // Emit a temporary label to the streamer and refer to it.
1195 MCSymbol *Sym = Ctx.createTempSymbol();
1196 Out.emitLabel(Sym);
1197 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1198 getContext());
1199 EndLoc = FirstTokenLoc;
1200 return false;
1203 // Parse symbol variant
1204 std::pair<StringRef, StringRef> Split;
1205 if (!MAI.useParensForSymbolVariant()) {
1206 if (FirstTokenKind == AsmToken::String) {
1207 if (Lexer.is(AsmToken::At)) {
1208 Lex(); // eat @
1209 SMLoc AtLoc = getLexer().getLoc();
1210 StringRef VName;
1211 if (parseIdentifier(VName))
1212 return Error(AtLoc, "expected symbol variant after '@'");
1214 Split = std::make_pair(Identifier, VName);
1216 } else {
1217 Split = Identifier.split('@');
1219 } else if (Lexer.is(AsmToken::LParen)) {
1220 Lex(); // eat '('.
1221 StringRef VName;
1222 parseIdentifier(VName);
1223 if (parseRParen())
1224 return true;
1225 Split = std::make_pair(Identifier, VName);
1228 EndLoc = SMLoc::getFromPointer(Identifier.end());
1230 // This is a symbol reference.
1231 StringRef SymbolName = Identifier;
1232 if (SymbolName.empty())
1233 return Error(getLexer().getLoc(), "expected a symbol reference");
1235 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1237 // Lookup the symbol variant if used.
1238 if (!Split.second.empty()) {
1239 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1240 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1241 SymbolName = Split.first;
1242 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
1243 Variant = MCSymbolRefExpr::VK_None;
1244 } else {
1245 return Error(SMLoc::getFromPointer(Split.second.begin()),
1246 "invalid variant '" + Split.second + "'");
1250 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
1251 if (!Sym)
1252 Sym = getContext().getOrCreateSymbol(
1253 MAI.shouldEmitLabelsInUpperCase() ? SymbolName.upper() : SymbolName);
1255 // If this is an absolute variable reference, substitute it now to preserve
1256 // semantics in the face of reassignment.
1257 if (Sym->isVariable()) {
1258 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1259 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
1260 if (auto TV = dyn_cast<MCTargetExpr>(V))
1261 DoInline = TV->inlineAssignedExpr();
1262 if (DoInline) {
1263 if (Variant)
1264 return Error(EndLoc, "unexpected modifier on variable reference");
1265 Res = Sym->getVariableValue(/*SetUsed*/ false);
1266 return false;
1270 // Otherwise create a symbol ref.
1271 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1272 return false;
1274 case AsmToken::BigNum:
1275 return TokError("literal value out of range for directive");
1276 case AsmToken::Integer: {
1277 SMLoc Loc = getTok().getLoc();
1278 int64_t IntVal = getTok().getIntVal();
1279 Res = MCConstantExpr::create(IntVal, getContext());
1280 EndLoc = Lexer.getTok().getEndLoc();
1281 Lex(); // Eat token.
1282 // Look for 'b' or 'f' following an Integer as a directional label
1283 if (Lexer.getKind() == AsmToken::Identifier) {
1284 StringRef IDVal = getTok().getString();
1285 // Lookup the symbol variant if used.
1286 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1287 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1288 if (Split.first.size() != IDVal.size()) {
1289 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1290 if (Variant == MCSymbolRefExpr::VK_Invalid)
1291 return TokError("invalid variant '" + Split.second + "'");
1292 IDVal = Split.first;
1294 if (IDVal == "f" || IDVal == "b") {
1295 MCSymbol *Sym =
1296 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1297 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1298 if (IDVal == "b" && Sym->isUndefined())
1299 return Error(Loc, "directional label undefined");
1300 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1301 EndLoc = Lexer.getTok().getEndLoc();
1302 Lex(); // Eat identifier.
1305 return false;
1307 case AsmToken::Real: {
1308 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1309 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1310 Res = MCConstantExpr::create(IntVal, getContext());
1311 EndLoc = Lexer.getTok().getEndLoc();
1312 Lex(); // Eat token.
1313 return false;
1315 case AsmToken::Dot: {
1316 if (!MAI.getDotIsPC())
1317 return TokError("cannot use . as current PC");
1319 // This is a '.' reference, which references the current PC. Emit a
1320 // temporary label to the streamer and refer to it.
1321 MCSymbol *Sym = Ctx.createTempSymbol();
1322 Out.emitLabel(Sym);
1323 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1324 EndLoc = Lexer.getTok().getEndLoc();
1325 Lex(); // Eat identifier.
1326 return false;
1328 case AsmToken::LParen:
1329 Lex(); // Eat the '('.
1330 return parseParenExpr(Res, EndLoc);
1331 case AsmToken::LBrac:
1332 if (!PlatformParser->HasBracketExpressions())
1333 return TokError("brackets expression not supported on this target");
1334 Lex(); // Eat the '['.
1335 return parseBracketExpr(Res, EndLoc);
1336 case AsmToken::Minus:
1337 Lex(); // Eat the operator.
1338 if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1339 return true;
1340 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1341 return false;
1342 case AsmToken::Plus:
1343 Lex(); // Eat the operator.
1344 if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1345 return true;
1346 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1347 return false;
1348 case AsmToken::Tilde:
1349 Lex(); // Eat the operator.
1350 if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
1351 return true;
1352 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1353 return false;
1354 // MIPS unary expression operators. The lexer won't generate these tokens if
1355 // MCAsmInfo::HasMipsExpressions is false for the target.
1356 case AsmToken::PercentCall16:
1357 case AsmToken::PercentCall_Hi:
1358 case AsmToken::PercentCall_Lo:
1359 case AsmToken::PercentDtprel_Hi:
1360 case AsmToken::PercentDtprel_Lo:
1361 case AsmToken::PercentGot:
1362 case AsmToken::PercentGot_Disp:
1363 case AsmToken::PercentGot_Hi:
1364 case AsmToken::PercentGot_Lo:
1365 case AsmToken::PercentGot_Ofst:
1366 case AsmToken::PercentGot_Page:
1367 case AsmToken::PercentGottprel:
1368 case AsmToken::PercentGp_Rel:
1369 case AsmToken::PercentHi:
1370 case AsmToken::PercentHigher:
1371 case AsmToken::PercentHighest:
1372 case AsmToken::PercentLo:
1373 case AsmToken::PercentNeg:
1374 case AsmToken::PercentPcrel_Hi:
1375 case AsmToken::PercentPcrel_Lo:
1376 case AsmToken::PercentTlsgd:
1377 case AsmToken::PercentTlsldm:
1378 case AsmToken::PercentTprel_Hi:
1379 case AsmToken::PercentTprel_Lo:
1380 Lex(); // Eat the operator.
1381 if (Lexer.isNot(AsmToken::LParen))
1382 return TokError("expected '(' after operator");
1383 Lex(); // Eat the operator.
1384 if (parseExpression(Res, EndLoc))
1385 return true;
1386 if (parseRParen())
1387 return true;
1388 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1389 return !Res;
1393 bool AsmParser::parseExpression(const MCExpr *&Res) {
1394 SMLoc EndLoc;
1395 return parseExpression(Res, EndLoc);
1398 const MCExpr *
1399 AsmParser::applyModifierToExpr(const MCExpr *E,
1400 MCSymbolRefExpr::VariantKind Variant) {
1401 // Ask the target implementation about this expression first.
1402 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1403 if (NewE)
1404 return NewE;
1405 // Recurse over the given expression, rebuilding it to apply the given variant
1406 // if there is exactly one symbol.
1407 switch (E->getKind()) {
1408 case MCExpr::Target:
1409 case MCExpr::Constant:
1410 return nullptr;
1412 case MCExpr::SymbolRef: {
1413 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1415 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1416 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1417 "' (already modified)");
1418 return E;
1421 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1424 case MCExpr::Unary: {
1425 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1426 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1427 if (!Sub)
1428 return nullptr;
1429 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1432 case MCExpr::Binary: {
1433 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1434 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1435 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1437 if (!LHS && !RHS)
1438 return nullptr;
1440 if (!LHS)
1441 LHS = BE->getLHS();
1442 if (!RHS)
1443 RHS = BE->getRHS();
1445 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1449 llvm_unreachable("Invalid expression kind!");
1452 /// This function checks if the next token is <string> type or arithmetic.
1453 /// string that begin with character '<' must end with character '>'.
1454 /// otherwise it is arithmetics.
1455 /// If the function returns a 'true' value,
1456 /// the End argument will be filled with the last location pointed to the '>'
1457 /// character.
1459 /// There is a gap between the AltMacro's documentation and the single quote
1460 /// implementation. GCC does not fully support this feature and so we will not
1461 /// support it.
1462 /// TODO: Adding single quote as a string.
1463 static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) {
1464 assert((StrLoc.getPointer() != nullptr) &&
1465 "Argument to the function cannot be a NULL value");
1466 const char *CharPtr = StrLoc.getPointer();
1467 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1468 (*CharPtr != '\0')) {
1469 if (*CharPtr == '!')
1470 CharPtr++;
1471 CharPtr++;
1473 if (*CharPtr == '>') {
1474 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1475 return true;
1477 return false;
1480 /// creating a string without the escape characters '!'.
1481 static std::string angleBracketString(StringRef AltMacroStr) {
1482 std::string Res;
1483 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1484 if (AltMacroStr[Pos] == '!')
1485 Pos++;
1486 Res += AltMacroStr[Pos];
1488 return Res;
1491 /// Parse an expression and return it.
1493 /// expr ::= expr &&,|| expr -> lowest.
1494 /// expr ::= expr |,^,&,! expr
1495 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1496 /// expr ::= expr <<,>> expr
1497 /// expr ::= expr +,- expr
1498 /// expr ::= expr *,/,% expr -> highest.
1499 /// expr ::= primaryexpr
1501 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1502 // Parse the expression.
1503 Res = nullptr;
1504 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1505 parseBinOpRHS(1, Res, EndLoc))
1506 return true;
1508 // As a special case, we support 'a op b @ modifier' by rewriting the
1509 // expression to include the modifier. This is inefficient, but in general we
1510 // expect users to use 'a@modifier op b'.
1511 if (Lexer.getKind() == AsmToken::At) {
1512 Lex();
1514 if (Lexer.isNot(AsmToken::Identifier))
1515 return TokError("unexpected symbol modifier following '@'");
1517 MCSymbolRefExpr::VariantKind Variant =
1518 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1519 if (Variant == MCSymbolRefExpr::VK_Invalid)
1520 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1522 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1523 if (!ModifiedRes) {
1524 return TokError("invalid modifier '" + getTok().getIdentifier() +
1525 "' (no symbols present)");
1528 Res = ModifiedRes;
1529 Lex();
1532 // Try to constant fold it up front, if possible. Do not exploit
1533 // assembler here.
1534 int64_t Value;
1535 if (Res->evaluateAsAbsolute(Value))
1536 Res = MCConstantExpr::create(Value, getContext());
1538 return false;
1541 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1542 Res = nullptr;
1543 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1546 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1547 SMLoc &EndLoc) {
1548 if (parseParenExpr(Res, EndLoc))
1549 return true;
1551 for (; ParenDepth > 0; --ParenDepth) {
1552 if (parseBinOpRHS(1, Res, EndLoc))
1553 return true;
1555 // We don't Lex() the last RParen.
1556 // This is the same behavior as parseParenExpression().
1557 if (ParenDepth - 1 > 0) {
1558 EndLoc = getTok().getEndLoc();
1559 if (parseRParen())
1560 return true;
1563 return false;
1566 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1567 const MCExpr *Expr;
1569 SMLoc StartLoc = Lexer.getLoc();
1570 if (parseExpression(Expr))
1571 return true;
1573 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
1574 return Error(StartLoc, "expected absolute expression");
1576 return false;
1579 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1580 MCBinaryExpr::Opcode &Kind,
1581 bool ShouldUseLogicalShr) {
1582 switch (K) {
1583 default:
1584 return 0; // not a binop.
1586 // Lowest Precedence: &&, ||
1587 case AsmToken::AmpAmp:
1588 Kind = MCBinaryExpr::LAnd;
1589 return 1;
1590 case AsmToken::PipePipe:
1591 Kind = MCBinaryExpr::LOr;
1592 return 1;
1594 // Low Precedence: |, &, ^
1595 case AsmToken::Pipe:
1596 Kind = MCBinaryExpr::Or;
1597 return 2;
1598 case AsmToken::Caret:
1599 Kind = MCBinaryExpr::Xor;
1600 return 2;
1601 case AsmToken::Amp:
1602 Kind = MCBinaryExpr::And;
1603 return 2;
1605 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1606 case AsmToken::EqualEqual:
1607 Kind = MCBinaryExpr::EQ;
1608 return 3;
1609 case AsmToken::ExclaimEqual:
1610 case AsmToken::LessGreater:
1611 Kind = MCBinaryExpr::NE;
1612 return 3;
1613 case AsmToken::Less:
1614 Kind = MCBinaryExpr::LT;
1615 return 3;
1616 case AsmToken::LessEqual:
1617 Kind = MCBinaryExpr::LTE;
1618 return 3;
1619 case AsmToken::Greater:
1620 Kind = MCBinaryExpr::GT;
1621 return 3;
1622 case AsmToken::GreaterEqual:
1623 Kind = MCBinaryExpr::GTE;
1624 return 3;
1626 // Intermediate Precedence: <<, >>
1627 case AsmToken::LessLess:
1628 Kind = MCBinaryExpr::Shl;
1629 return 4;
1630 case AsmToken::GreaterGreater:
1631 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1632 return 4;
1634 // High Intermediate Precedence: +, -
1635 case AsmToken::Plus:
1636 Kind = MCBinaryExpr::Add;
1637 return 5;
1638 case AsmToken::Minus:
1639 Kind = MCBinaryExpr::Sub;
1640 return 5;
1642 // Highest Precedence: *, /, %
1643 case AsmToken::Star:
1644 Kind = MCBinaryExpr::Mul;
1645 return 6;
1646 case AsmToken::Slash:
1647 Kind = MCBinaryExpr::Div;
1648 return 6;
1649 case AsmToken::Percent:
1650 Kind = MCBinaryExpr::Mod;
1651 return 6;
1655 static unsigned getGNUBinOpPrecedence(const MCAsmInfo &MAI,
1656 AsmToken::TokenKind K,
1657 MCBinaryExpr::Opcode &Kind,
1658 bool ShouldUseLogicalShr) {
1659 switch (K) {
1660 default:
1661 return 0; // not a binop.
1663 // Lowest Precedence: &&, ||
1664 case AsmToken::AmpAmp:
1665 Kind = MCBinaryExpr::LAnd;
1666 return 2;
1667 case AsmToken::PipePipe:
1668 Kind = MCBinaryExpr::LOr;
1669 return 1;
1671 // Low Precedence: ==, !=, <>, <, <=, >, >=
1672 case AsmToken::EqualEqual:
1673 Kind = MCBinaryExpr::EQ;
1674 return 3;
1675 case AsmToken::ExclaimEqual:
1676 case AsmToken::LessGreater:
1677 Kind = MCBinaryExpr::NE;
1678 return 3;
1679 case AsmToken::Less:
1680 Kind = MCBinaryExpr::LT;
1681 return 3;
1682 case AsmToken::LessEqual:
1683 Kind = MCBinaryExpr::LTE;
1684 return 3;
1685 case AsmToken::Greater:
1686 Kind = MCBinaryExpr::GT;
1687 return 3;
1688 case AsmToken::GreaterEqual:
1689 Kind = MCBinaryExpr::GTE;
1690 return 3;
1692 // Low Intermediate Precedence: +, -
1693 case AsmToken::Plus:
1694 Kind = MCBinaryExpr::Add;
1695 return 4;
1696 case AsmToken::Minus:
1697 Kind = MCBinaryExpr::Sub;
1698 return 4;
1700 // High Intermediate Precedence: |, !, &, ^
1702 case AsmToken::Pipe:
1703 Kind = MCBinaryExpr::Or;
1704 return 5;
1705 case AsmToken::Exclaim:
1706 // Hack to support ARM compatible aliases (implied 'sp' operand in 'srs*'
1707 // instructions like 'srsda #31!') and not parse ! as an infix operator.
1708 if (MAI.getCommentString() == "@")
1709 return 0;
1710 Kind = MCBinaryExpr::OrNot;
1711 return 5;
1712 case AsmToken::Caret:
1713 Kind = MCBinaryExpr::Xor;
1714 return 5;
1715 case AsmToken::Amp:
1716 Kind = MCBinaryExpr::And;
1717 return 5;
1719 // Highest Precedence: *, /, %, <<, >>
1720 case AsmToken::Star:
1721 Kind = MCBinaryExpr::Mul;
1722 return 6;
1723 case AsmToken::Slash:
1724 Kind = MCBinaryExpr::Div;
1725 return 6;
1726 case AsmToken::Percent:
1727 Kind = MCBinaryExpr::Mod;
1728 return 6;
1729 case AsmToken::LessLess:
1730 Kind = MCBinaryExpr::Shl;
1731 return 6;
1732 case AsmToken::GreaterGreater:
1733 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1734 return 6;
1738 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1739 MCBinaryExpr::Opcode &Kind) {
1740 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1741 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1742 : getGNUBinOpPrecedence(MAI, K, Kind, ShouldUseLogicalShr);
1745 /// Parse all binary operators with precedence >= 'Precedence'.
1746 /// Res contains the LHS of the expression on input.
1747 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1748 SMLoc &EndLoc) {
1749 SMLoc StartLoc = Lexer.getLoc();
1750 while (true) {
1751 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1752 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1754 // If the next token is lower precedence than we are allowed to eat, return
1755 // successfully with what we ate already.
1756 if (TokPrec < Precedence)
1757 return false;
1759 Lex();
1761 // Eat the next primary expression.
1762 const MCExpr *RHS;
1763 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
1764 return true;
1766 // If BinOp binds less tightly with RHS than the operator after RHS, let
1767 // the pending operator take RHS as its LHS.
1768 MCBinaryExpr::Opcode Dummy;
1769 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1770 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1771 return true;
1773 // Merge LHS and RHS according to operator.
1774 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1778 /// ParseStatement:
1779 /// ::= EndOfStatement
1780 /// ::= Label* Directive ...Operands... EndOfStatement
1781 /// ::= Label* Identifier OperandList* EndOfStatement
1782 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1783 MCAsmParserSemaCallback *SI) {
1784 assert(!hasPendingError() && "parseStatement started with pending error");
1785 // Eat initial spaces and comments
1786 while (Lexer.is(AsmToken::Space))
1787 Lex();
1788 if (Lexer.is(AsmToken::EndOfStatement)) {
1789 // if this is a line comment we can drop it safely
1790 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1791 getTok().getString().front() == '\n')
1792 Out.addBlankLine();
1793 Lex();
1794 return false;
1796 // Statements always start with an identifier.
1797 AsmToken ID = getTok();
1798 SMLoc IDLoc = ID.getLoc();
1799 StringRef IDVal;
1800 int64_t LocalLabelVal = -1;
1801 StartTokLoc = ID.getLoc();
1802 if (Lexer.is(AsmToken::HashDirective))
1803 return parseCppHashLineFilenameComment(IDLoc,
1804 !isInsideMacroInstantiation());
1806 // Allow an integer followed by a ':' as a directional local label.
1807 if (Lexer.is(AsmToken::Integer)) {
1808 LocalLabelVal = getTok().getIntVal();
1809 if (LocalLabelVal < 0) {
1810 if (!TheCondState.Ignore) {
1811 Lex(); // always eat a token
1812 return Error(IDLoc, "unexpected token at start of statement");
1814 IDVal = "";
1815 } else {
1816 IDVal = getTok().getString();
1817 Lex(); // Consume the integer token to be used as an identifier token.
1818 if (Lexer.getKind() != AsmToken::Colon) {
1819 if (!TheCondState.Ignore) {
1820 Lex(); // always eat a token
1821 return Error(IDLoc, "unexpected token at start of statement");
1825 } else if (Lexer.is(AsmToken::Dot)) {
1826 // Treat '.' as a valid identifier in this context.
1827 Lex();
1828 IDVal = ".";
1829 } else if (Lexer.is(AsmToken::LCurly)) {
1830 // Treat '{' as a valid identifier in this context.
1831 Lex();
1832 IDVal = "{";
1834 } else if (Lexer.is(AsmToken::RCurly)) {
1835 // Treat '}' as a valid identifier in this context.
1836 Lex();
1837 IDVal = "}";
1838 } else if (Lexer.is(AsmToken::Star) &&
1839 getTargetParser().starIsStartOfStatement()) {
1840 // Accept '*' as a valid start of statement.
1841 Lex();
1842 IDVal = "*";
1843 } else if (parseIdentifier(IDVal)) {
1844 if (!TheCondState.Ignore) {
1845 Lex(); // always eat a token
1846 return Error(IDLoc, "unexpected token at start of statement");
1848 IDVal = "";
1851 // Handle conditional assembly here before checking for skipping. We
1852 // have to do this so that .endif isn't skipped in a ".if 0" block for
1853 // example.
1854 StringMap<DirectiveKind>::const_iterator DirKindIt =
1855 DirectiveKindMap.find(IDVal.lower());
1856 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1857 ? DK_NO_DIRECTIVE
1858 : DirKindIt->getValue();
1859 switch (DirKind) {
1860 default:
1861 break;
1862 case DK_IF:
1863 case DK_IFEQ:
1864 case DK_IFGE:
1865 case DK_IFGT:
1866 case DK_IFLE:
1867 case DK_IFLT:
1868 case DK_IFNE:
1869 return parseDirectiveIf(IDLoc, DirKind);
1870 case DK_IFB:
1871 return parseDirectiveIfb(IDLoc, true);
1872 case DK_IFNB:
1873 return parseDirectiveIfb(IDLoc, false);
1874 case DK_IFC:
1875 return parseDirectiveIfc(IDLoc, true);
1876 case DK_IFEQS:
1877 return parseDirectiveIfeqs(IDLoc, true);
1878 case DK_IFNC:
1879 return parseDirectiveIfc(IDLoc, false);
1880 case DK_IFNES:
1881 return parseDirectiveIfeqs(IDLoc, false);
1882 case DK_IFDEF:
1883 return parseDirectiveIfdef(IDLoc, true);
1884 case DK_IFNDEF:
1885 case DK_IFNOTDEF:
1886 return parseDirectiveIfdef(IDLoc, false);
1887 case DK_ELSEIF:
1888 return parseDirectiveElseIf(IDLoc);
1889 case DK_ELSE:
1890 return parseDirectiveElse(IDLoc);
1891 case DK_ENDIF:
1892 return parseDirectiveEndIf(IDLoc);
1895 // Ignore the statement if in the middle of inactive conditional
1896 // (e.g. ".if 0").
1897 if (TheCondState.Ignore) {
1898 eatToEndOfStatement();
1899 return false;
1902 // FIXME: Recurse on local labels?
1904 // Check for a label.
1905 // ::= identifier ':'
1906 // ::= number ':'
1907 if (Lexer.is(AsmToken::Colon) && getTargetParser().isLabel(ID)) {
1908 if (checkForValidSection())
1909 return true;
1911 Lex(); // Consume the ':'.
1913 // Diagnose attempt to use '.' as a label.
1914 if (IDVal == ".")
1915 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1917 // Diagnose attempt to use a variable as a label.
1919 // FIXME: Diagnostics. Note the location of the definition as a label.
1920 // FIXME: This doesn't diagnose assignment to a symbol which has been
1921 // implicitly marked as external.
1922 MCSymbol *Sym;
1923 if (LocalLabelVal == -1) {
1924 if (ParsingMSInlineAsm && SI) {
1925 StringRef RewrittenLabel =
1926 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1927 assert(!RewrittenLabel.empty() &&
1928 "We should have an internal name here.");
1929 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1930 RewrittenLabel);
1931 IDVal = RewrittenLabel;
1933 Sym = getContext().getOrCreateSymbol(IDVal);
1934 } else
1935 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1936 // End of Labels should be treated as end of line for lexing
1937 // purposes but that information is not available to the Lexer who
1938 // does not understand Labels. This may cause us to see a Hash
1939 // here instead of a preprocessor line comment.
1940 if (getTok().is(AsmToken::Hash)) {
1941 StringRef CommentStr = parseStringToEndOfStatement();
1942 Lexer.Lex();
1943 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1946 // Consume any end of statement token, if present, to avoid spurious
1947 // addBlankLine calls().
1948 if (getTok().is(AsmToken::EndOfStatement)) {
1949 Lex();
1952 if (discardLTOSymbol(IDVal))
1953 return false;
1955 getTargetParser().doBeforeLabelEmit(Sym, IDLoc);
1957 // Emit the label.
1958 if (!getTargetParser().isParsingMSInlineAsm())
1959 Out.emitLabel(Sym, IDLoc);
1961 // If we are generating dwarf for assembly source files then gather the
1962 // info to make a dwarf label entry for this label if needed.
1963 if (enabledGenDwarfForAssembly())
1964 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1965 IDLoc);
1967 getTargetParser().onLabelParsed(Sym);
1969 return false;
1972 // Check for an assignment statement.
1973 // ::= identifier '='
1974 if (Lexer.is(AsmToken::Equal) && getTargetParser().equalIsAsmAssignment()) {
1975 Lex();
1976 return parseAssignment(IDVal, AssignmentKind::Equal);
1979 // If macros are enabled, check to see if this is a macro instantiation.
1980 if (areMacrosEnabled())
1981 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1982 return handleMacroEntry(M, IDLoc);
1985 // Otherwise, we have a normal instruction or directive.
1987 // Directives start with "."
1988 if (IDVal.startswith(".") && IDVal != ".") {
1989 // There are several entities interested in parsing directives:
1991 // 1. The target-specific assembly parser. Some directives are target
1992 // specific or may potentially behave differently on certain targets.
1993 // 2. Asm parser extensions. For example, platform-specific parsers
1994 // (like the ELF parser) register themselves as extensions.
1995 // 3. The generic directive parser implemented by this class. These are
1996 // all the directives that behave in a target and platform independent
1997 // manner, or at least have a default behavior that's shared between
1998 // all targets and platforms.
2000 getTargetParser().flushPendingInstructions(getStreamer());
2002 ParseStatus TPDirectiveReturn = getTargetParser().parseDirective(ID);
2003 assert(TPDirectiveReturn.isFailure() == hasPendingError() &&
2004 "Should only return Failure iff there was an error");
2005 if (TPDirectiveReturn.isFailure())
2006 return true;
2007 if (TPDirectiveReturn.isSuccess())
2008 return false;
2010 // Next, check the extension directive map to see if any extension has
2011 // registered itself to parse this directive.
2012 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
2013 ExtensionDirectiveMap.lookup(IDVal);
2014 if (Handler.first)
2015 return (*Handler.second)(Handler.first, IDVal, IDLoc);
2017 // Finally, if no one else is interested in this directive, it must be
2018 // generic and familiar to this class.
2019 switch (DirKind) {
2020 default:
2021 break;
2022 case DK_SET:
2023 case DK_EQU:
2024 return parseDirectiveSet(IDVal, AssignmentKind::Set);
2025 case DK_EQUIV:
2026 return parseDirectiveSet(IDVal, AssignmentKind::Equiv);
2027 case DK_LTO_SET_CONDITIONAL:
2028 return parseDirectiveSet(IDVal, AssignmentKind::LTOSetConditional);
2029 case DK_ASCII:
2030 return parseDirectiveAscii(IDVal, false);
2031 case DK_ASCIZ:
2032 case DK_STRING:
2033 return parseDirectiveAscii(IDVal, true);
2034 case DK_BYTE:
2035 case DK_DC_B:
2036 return parseDirectiveValue(IDVal, 1);
2037 case DK_DC:
2038 case DK_DC_W:
2039 case DK_SHORT:
2040 case DK_VALUE:
2041 case DK_2BYTE:
2042 return parseDirectiveValue(IDVal, 2);
2043 case DK_LONG:
2044 case DK_INT:
2045 case DK_4BYTE:
2046 case DK_DC_L:
2047 return parseDirectiveValue(IDVal, 4);
2048 case DK_QUAD:
2049 case DK_8BYTE:
2050 return parseDirectiveValue(IDVal, 8);
2051 case DK_DC_A:
2052 return parseDirectiveValue(
2053 IDVal, getContext().getAsmInfo()->getCodePointerSize());
2054 case DK_OCTA:
2055 return parseDirectiveOctaValue(IDVal);
2056 case DK_SINGLE:
2057 case DK_FLOAT:
2058 case DK_DC_S:
2059 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
2060 case DK_DOUBLE:
2061 case DK_DC_D:
2062 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
2063 case DK_ALIGN: {
2064 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
2065 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
2067 case DK_ALIGN32: {
2068 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
2069 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
2071 case DK_BALIGN:
2072 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
2073 case DK_BALIGNW:
2074 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
2075 case DK_BALIGNL:
2076 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
2077 case DK_P2ALIGN:
2078 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
2079 case DK_P2ALIGNW:
2080 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
2081 case DK_P2ALIGNL:
2082 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
2083 case DK_ORG:
2084 return parseDirectiveOrg();
2085 case DK_FILL:
2086 return parseDirectiveFill();
2087 case DK_ZERO:
2088 return parseDirectiveZero();
2089 case DK_EXTERN:
2090 eatToEndOfStatement(); // .extern is the default, ignore it.
2091 return false;
2092 case DK_GLOBL:
2093 case DK_GLOBAL:
2094 return parseDirectiveSymbolAttribute(MCSA_Global);
2095 case DK_LAZY_REFERENCE:
2096 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
2097 case DK_NO_DEAD_STRIP:
2098 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
2099 case DK_SYMBOL_RESOLVER:
2100 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
2101 case DK_PRIVATE_EXTERN:
2102 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
2103 case DK_REFERENCE:
2104 return parseDirectiveSymbolAttribute(MCSA_Reference);
2105 case DK_WEAK_DEFINITION:
2106 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2107 case DK_WEAK_REFERENCE:
2108 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2109 case DK_WEAK_DEF_CAN_BE_HIDDEN:
2110 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
2111 case DK_COLD:
2112 return parseDirectiveSymbolAttribute(MCSA_Cold);
2113 case DK_COMM:
2114 case DK_COMMON:
2115 return parseDirectiveComm(/*IsLocal=*/false);
2116 case DK_LCOMM:
2117 return parseDirectiveComm(/*IsLocal=*/true);
2118 case DK_ABORT:
2119 return parseDirectiveAbort();
2120 case DK_INCLUDE:
2121 return parseDirectiveInclude();
2122 case DK_INCBIN:
2123 return parseDirectiveIncbin();
2124 case DK_CODE16:
2125 case DK_CODE16GCC:
2126 return TokError(Twine(IDVal) +
2127 " not currently supported for this target");
2128 case DK_REPT:
2129 return parseDirectiveRept(IDLoc, IDVal);
2130 case DK_IRP:
2131 return parseDirectiveIrp(IDLoc);
2132 case DK_IRPC:
2133 return parseDirectiveIrpc(IDLoc);
2134 case DK_ENDR:
2135 return parseDirectiveEndr(IDLoc);
2136 case DK_BUNDLE_ALIGN_MODE:
2137 return parseDirectiveBundleAlignMode();
2138 case DK_BUNDLE_LOCK:
2139 return parseDirectiveBundleLock();
2140 case DK_BUNDLE_UNLOCK:
2141 return parseDirectiveBundleUnlock();
2142 case DK_SLEB128:
2143 return parseDirectiveLEB128(true);
2144 case DK_ULEB128:
2145 return parseDirectiveLEB128(false);
2146 case DK_SPACE:
2147 case DK_SKIP:
2148 return parseDirectiveSpace(IDVal);
2149 case DK_FILE:
2150 return parseDirectiveFile(IDLoc);
2151 case DK_LINE:
2152 return parseDirectiveLine();
2153 case DK_LOC:
2154 return parseDirectiveLoc();
2155 case DK_STABS:
2156 return parseDirectiveStabs();
2157 case DK_CV_FILE:
2158 return parseDirectiveCVFile();
2159 case DK_CV_FUNC_ID:
2160 return parseDirectiveCVFuncId();
2161 case DK_CV_INLINE_SITE_ID:
2162 return parseDirectiveCVInlineSiteId();
2163 case DK_CV_LOC:
2164 return parseDirectiveCVLoc();
2165 case DK_CV_LINETABLE:
2166 return parseDirectiveCVLinetable();
2167 case DK_CV_INLINE_LINETABLE:
2168 return parseDirectiveCVInlineLinetable();
2169 case DK_CV_DEF_RANGE:
2170 return parseDirectiveCVDefRange();
2171 case DK_CV_STRING:
2172 return parseDirectiveCVString();
2173 case DK_CV_STRINGTABLE:
2174 return parseDirectiveCVStringTable();
2175 case DK_CV_FILECHECKSUMS:
2176 return parseDirectiveCVFileChecksums();
2177 case DK_CV_FILECHECKSUM_OFFSET:
2178 return parseDirectiveCVFileChecksumOffset();
2179 case DK_CV_FPO_DATA:
2180 return parseDirectiveCVFPOData();
2181 case DK_CFI_SECTIONS:
2182 return parseDirectiveCFISections();
2183 case DK_CFI_STARTPROC:
2184 return parseDirectiveCFIStartProc();
2185 case DK_CFI_ENDPROC:
2186 return parseDirectiveCFIEndProc();
2187 case DK_CFI_DEF_CFA:
2188 return parseDirectiveCFIDefCfa(IDLoc);
2189 case DK_CFI_DEF_CFA_OFFSET:
2190 return parseDirectiveCFIDefCfaOffset(IDLoc);
2191 case DK_CFI_ADJUST_CFA_OFFSET:
2192 return parseDirectiveCFIAdjustCfaOffset(IDLoc);
2193 case DK_CFI_DEF_CFA_REGISTER:
2194 return parseDirectiveCFIDefCfaRegister(IDLoc);
2195 case DK_CFI_LLVM_DEF_ASPACE_CFA:
2196 return parseDirectiveCFILLVMDefAspaceCfa(IDLoc);
2197 case DK_CFI_OFFSET:
2198 return parseDirectiveCFIOffset(IDLoc);
2199 case DK_CFI_REL_OFFSET:
2200 return parseDirectiveCFIRelOffset(IDLoc);
2201 case DK_CFI_PERSONALITY:
2202 return parseDirectiveCFIPersonalityOrLsda(true);
2203 case DK_CFI_LSDA:
2204 return parseDirectiveCFIPersonalityOrLsda(false);
2205 case DK_CFI_REMEMBER_STATE:
2206 return parseDirectiveCFIRememberState(IDLoc);
2207 case DK_CFI_RESTORE_STATE:
2208 return parseDirectiveCFIRestoreState(IDLoc);
2209 case DK_CFI_SAME_VALUE:
2210 return parseDirectiveCFISameValue(IDLoc);
2211 case DK_CFI_RESTORE:
2212 return parseDirectiveCFIRestore(IDLoc);
2213 case DK_CFI_ESCAPE:
2214 return parseDirectiveCFIEscape(IDLoc);
2215 case DK_CFI_RETURN_COLUMN:
2216 return parseDirectiveCFIReturnColumn(IDLoc);
2217 case DK_CFI_SIGNAL_FRAME:
2218 return parseDirectiveCFISignalFrame(IDLoc);
2219 case DK_CFI_UNDEFINED:
2220 return parseDirectiveCFIUndefined(IDLoc);
2221 case DK_CFI_REGISTER:
2222 return parseDirectiveCFIRegister(IDLoc);
2223 case DK_CFI_WINDOW_SAVE:
2224 return parseDirectiveCFIWindowSave(IDLoc);
2225 case DK_MACROS_ON:
2226 case DK_MACROS_OFF:
2227 return parseDirectiveMacrosOnOff(IDVal);
2228 case DK_MACRO:
2229 return parseDirectiveMacro(IDLoc);
2230 case DK_ALTMACRO:
2231 case DK_NOALTMACRO:
2232 return parseDirectiveAltmacro(IDVal);
2233 case DK_EXITM:
2234 return parseDirectiveExitMacro(IDVal);
2235 case DK_ENDM:
2236 case DK_ENDMACRO:
2237 return parseDirectiveEndMacro(IDVal);
2238 case DK_PURGEM:
2239 return parseDirectivePurgeMacro(IDLoc);
2240 case DK_END:
2241 return parseDirectiveEnd(IDLoc);
2242 case DK_ERR:
2243 return parseDirectiveError(IDLoc, false);
2244 case DK_ERROR:
2245 return parseDirectiveError(IDLoc, true);
2246 case DK_WARNING:
2247 return parseDirectiveWarning(IDLoc);
2248 case DK_RELOC:
2249 return parseDirectiveReloc(IDLoc);
2250 case DK_DCB:
2251 case DK_DCB_W:
2252 return parseDirectiveDCB(IDVal, 2);
2253 case DK_DCB_B:
2254 return parseDirectiveDCB(IDVal, 1);
2255 case DK_DCB_D:
2256 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2257 case DK_DCB_L:
2258 return parseDirectiveDCB(IDVal, 4);
2259 case DK_DCB_S:
2260 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2261 case DK_DC_X:
2262 case DK_DCB_X:
2263 return TokError(Twine(IDVal) +
2264 " not currently supported for this target");
2265 case DK_DS:
2266 case DK_DS_W:
2267 return parseDirectiveDS(IDVal, 2);
2268 case DK_DS_B:
2269 return parseDirectiveDS(IDVal, 1);
2270 case DK_DS_D:
2271 return parseDirectiveDS(IDVal, 8);
2272 case DK_DS_L:
2273 case DK_DS_S:
2274 return parseDirectiveDS(IDVal, 4);
2275 case DK_DS_P:
2276 case DK_DS_X:
2277 return parseDirectiveDS(IDVal, 12);
2278 case DK_PRINT:
2279 return parseDirectivePrint(IDLoc);
2280 case DK_ADDRSIG:
2281 return parseDirectiveAddrsig();
2282 case DK_ADDRSIG_SYM:
2283 return parseDirectiveAddrsigSym();
2284 case DK_PSEUDO_PROBE:
2285 return parseDirectivePseudoProbe();
2286 case DK_LTO_DISCARD:
2287 return parseDirectiveLTODiscard();
2288 case DK_MEMTAG:
2289 return parseDirectiveSymbolAttribute(MCSA_Memtag);
2292 return Error(IDLoc, "unknown directive");
2295 // __asm _emit or __asm __emit
2296 if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2297 IDVal == "_EMIT" || IDVal == "__EMIT"))
2298 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2300 // __asm align
2301 if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2302 return parseDirectiveMSAlign(IDLoc, Info);
2304 if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2305 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2306 if (checkForValidSection())
2307 return true;
2309 return parseAndMatchAndEmitTargetInstruction(Info, IDVal, ID, IDLoc);
2312 bool AsmParser::parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
2313 StringRef IDVal,
2314 AsmToken ID,
2315 SMLoc IDLoc) {
2316 // Canonicalize the opcode to lower case.
2317 std::string OpcodeStr = IDVal.lower();
2318 ParseInstructionInfo IInfo(Info.AsmRewrites);
2319 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2320 Info.ParsedOperands);
2321 Info.ParseError = ParseHadError;
2323 // Dump the parsed representation, if requested.
2324 if (getShowParsedOperands()) {
2325 SmallString<256> Str;
2326 raw_svector_ostream OS(Str);
2327 OS << "parsed instruction: [";
2328 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2329 if (i != 0)
2330 OS << ", ";
2331 Info.ParsedOperands[i]->print(OS);
2333 OS << "]";
2335 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2338 // Fail even if ParseInstruction erroneously returns false.
2339 if (hasPendingError() || ParseHadError)
2340 return true;
2342 // If we are generating dwarf for the current section then generate a .loc
2343 // directive for the instruction.
2344 if (!ParseHadError && enabledGenDwarfForAssembly() &&
2345 getContext().getGenDwarfSectionSyms().count(
2346 getStreamer().getCurrentSectionOnly())) {
2347 unsigned Line;
2348 if (ActiveMacros.empty())
2349 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2350 else
2351 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2352 ActiveMacros.front()->ExitBuffer);
2354 // If we previously parsed a cpp hash file line comment then make sure the
2355 // current Dwarf File is for the CppHashFilename if not then emit the
2356 // Dwarf File table for it and adjust the line number for the .loc.
2357 if (!CppHashInfo.Filename.empty()) {
2358 unsigned FileNumber = getStreamer().emitDwarfFileDirective(
2359 0, StringRef(), CppHashInfo.Filename);
2360 getContext().setGenDwarfFileNumber(FileNumber);
2362 unsigned CppHashLocLineNo =
2363 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2364 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2367 getStreamer().emitDwarfLocDirective(
2368 getContext().getGenDwarfFileNumber(), Line, 0,
2369 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2370 StringRef());
2373 // If parsing succeeded, match the instruction.
2374 if (!ParseHadError) {
2375 uint64_t ErrorInfo;
2376 if (getTargetParser().MatchAndEmitInstruction(
2377 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2378 getTargetParser().isParsingMSInlineAsm()))
2379 return true;
2381 return false;
2384 // Parse and erase curly braces marking block start/end
2385 bool
2386 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2387 // Identify curly brace marking block start/end
2388 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2389 return false;
2391 SMLoc StartLoc = Lexer.getLoc();
2392 Lex(); // Eat the brace
2393 if (Lexer.is(AsmToken::EndOfStatement))
2394 Lex(); // Eat EndOfStatement following the brace
2396 // Erase the block start/end brace from the output asm string
2397 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2398 StartLoc.getPointer());
2399 return true;
2402 /// parseCppHashLineFilenameComment as this:
2403 /// ::= # number "filename"
2404 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo) {
2405 Lex(); // Eat the hash token.
2406 // Lexer only ever emits HashDirective if it fully formed if it's
2407 // done the checking already so this is an internal error.
2408 assert(getTok().is(AsmToken::Integer) &&
2409 "Lexing Cpp line comment: Expected Integer");
2410 int64_t LineNumber = getTok().getIntVal();
2411 Lex();
2412 assert(getTok().is(AsmToken::String) &&
2413 "Lexing Cpp line comment: Expected String");
2414 StringRef Filename = getTok().getString();
2415 Lex();
2417 if (!SaveLocInfo)
2418 return false;
2420 // Get rid of the enclosing quotes.
2421 Filename = Filename.substr(1, Filename.size() - 2);
2423 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2424 // and possibly DWARF file info.
2425 CppHashInfo.Loc = L;
2426 CppHashInfo.Filename = Filename;
2427 CppHashInfo.LineNumber = LineNumber;
2428 CppHashInfo.Buf = CurBuffer;
2429 if (FirstCppHashFilename.empty())
2430 FirstCppHashFilename = Filename;
2431 return false;
2434 /// will use the last parsed cpp hash line filename comment
2435 /// for the Filename and LineNo if any in the diagnostic.
2436 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2437 auto *Parser = static_cast<AsmParser *>(Context);
2438 raw_ostream &OS = errs();
2440 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2441 SMLoc DiagLoc = Diag.getLoc();
2442 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2443 unsigned CppHashBuf =
2444 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2446 // Like SourceMgr::printMessage() we need to print the include stack if any
2447 // before printing the message.
2448 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2449 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2450 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2451 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2452 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2455 // If we have not parsed a cpp hash line filename comment or the source
2456 // manager changed or buffer changed (like in a nested include) then just
2457 // print the normal diagnostic using its Filename and LineNo.
2458 if (!Parser->CppHashInfo.LineNumber || DiagBuf != CppHashBuf) {
2459 if (Parser->SavedDiagHandler)
2460 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2461 else
2462 Parser->getContext().diagnose(Diag);
2463 return;
2466 // Use the CppHashFilename and calculate a line number based on the
2467 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2468 // for the diagnostic.
2469 const std::string &Filename = std::string(Parser->CppHashInfo.Filename);
2471 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2472 int CppHashLocLineNo =
2473 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2474 int LineNo =
2475 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2477 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2478 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2479 Diag.getLineContents(), Diag.getRanges());
2481 if (Parser->SavedDiagHandler)
2482 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2483 else
2484 Parser->getContext().diagnose(NewDiag);
2487 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2488 // difference being that that function accepts '@' as part of identifiers and
2489 // we can't do that. AsmLexer.cpp should probably be changed to handle
2490 // '@' as a special case when needed.
2491 static bool isIdentifierChar(char c) {
2492 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2493 c == '.';
2496 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2497 ArrayRef<MCAsmMacroParameter> Parameters,
2498 ArrayRef<MCAsmMacroArgument> A,
2499 bool EnableAtPseudoVariable, SMLoc L) {
2500 unsigned NParameters = Parameters.size();
2501 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2502 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2503 return Error(L, "Wrong number of arguments");
2505 // A macro without parameters is handled differently on Darwin:
2506 // gas accepts no arguments and does no substitutions
2507 while (!Body.empty()) {
2508 // Scan for the next substitution.
2509 std::size_t End = Body.size(), Pos = 0;
2510 for (; Pos != End; ++Pos) {
2511 // Check for a substitution or escape.
2512 if (IsDarwin && !NParameters) {
2513 // This macro has no parameters, look for $0, $1, etc.
2514 if (Body[Pos] != '$' || Pos + 1 == End)
2515 continue;
2517 char Next = Body[Pos + 1];
2518 if (Next == '$' || Next == 'n' ||
2519 isdigit(static_cast<unsigned char>(Next)))
2520 break;
2521 } else {
2522 // This macro has parameters, look for \foo, \bar, etc.
2523 if (Body[Pos] == '\\' && Pos + 1 != End)
2524 break;
2528 // Add the prefix.
2529 OS << Body.slice(0, Pos);
2531 // Check if we reached the end.
2532 if (Pos == End)
2533 break;
2535 if (IsDarwin && !NParameters) {
2536 switch (Body[Pos + 1]) {
2537 // $$ => $
2538 case '$':
2539 OS << '$';
2540 break;
2542 // $n => number of arguments
2543 case 'n':
2544 OS << A.size();
2545 break;
2547 // $[0-9] => argument
2548 default: {
2549 // Missing arguments are ignored.
2550 unsigned Index = Body[Pos + 1] - '0';
2551 if (Index >= A.size())
2552 break;
2554 // Otherwise substitute with the token values, with spaces eliminated.
2555 for (const AsmToken &Token : A[Index])
2556 OS << Token.getString();
2557 break;
2560 Pos += 2;
2561 } else {
2562 unsigned I = Pos + 1;
2564 // Check for the \@ pseudo-variable.
2565 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2566 ++I;
2567 else
2568 while (isIdentifierChar(Body[I]) && I + 1 != End)
2569 ++I;
2571 const char *Begin = Body.data() + Pos + 1;
2572 StringRef Argument(Begin, I - (Pos + 1));
2573 unsigned Index = 0;
2575 if (Argument == "@") {
2576 OS << NumOfMacroInstantiations;
2577 Pos += 2;
2578 } else {
2579 for (; Index < NParameters; ++Index)
2580 if (Parameters[Index].Name == Argument)
2581 break;
2583 if (Index == NParameters) {
2584 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2585 Pos += 3;
2586 else {
2587 OS << '\\' << Argument;
2588 Pos = I;
2590 } else {
2591 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2592 for (const AsmToken &Token : A[Index])
2593 // For altmacro mode, you can write '%expr'.
2594 // The prefix '%' evaluates the expression 'expr'
2595 // and uses the result as a string (e.g. replace %(1+2) with the
2596 // string "3").
2597 // Here, we identify the integer token which is the result of the
2598 // absolute expression evaluation and replace it with its string
2599 // representation.
2600 if (AltMacroMode && Token.getString().front() == '%' &&
2601 Token.is(AsmToken::Integer))
2602 // Emit an integer value to the buffer.
2603 OS << Token.getIntVal();
2604 // Only Token that was validated as a string and begins with '<'
2605 // is considered altMacroString!!!
2606 else if (AltMacroMode && Token.getString().front() == '<' &&
2607 Token.is(AsmToken::String)) {
2608 OS << angleBracketString(Token.getStringContents());
2610 // We expect no quotes around the string's contents when
2611 // parsing for varargs.
2612 else if (Token.isNot(AsmToken::String) || VarargParameter)
2613 OS << Token.getString();
2614 else
2615 OS << Token.getStringContents();
2617 Pos += 1 + Argument.size();
2621 // Update the scan point.
2622 Body = Body.substr(Pos);
2625 return false;
2628 static bool isOperator(AsmToken::TokenKind kind) {
2629 switch (kind) {
2630 default:
2631 return false;
2632 case AsmToken::Plus:
2633 case AsmToken::Minus:
2634 case AsmToken::Tilde:
2635 case AsmToken::Slash:
2636 case AsmToken::Star:
2637 case AsmToken::Dot:
2638 case AsmToken::Equal:
2639 case AsmToken::EqualEqual:
2640 case AsmToken::Pipe:
2641 case AsmToken::PipePipe:
2642 case AsmToken::Caret:
2643 case AsmToken::Amp:
2644 case AsmToken::AmpAmp:
2645 case AsmToken::Exclaim:
2646 case AsmToken::ExclaimEqual:
2647 case AsmToken::Less:
2648 case AsmToken::LessEqual:
2649 case AsmToken::LessLess:
2650 case AsmToken::LessGreater:
2651 case AsmToken::Greater:
2652 case AsmToken::GreaterEqual:
2653 case AsmToken::GreaterGreater:
2654 return true;
2658 namespace {
2660 class AsmLexerSkipSpaceRAII {
2661 public:
2662 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2663 Lexer.setSkipSpace(SkipSpace);
2666 ~AsmLexerSkipSpaceRAII() {
2667 Lexer.setSkipSpace(true);
2670 private:
2671 AsmLexer &Lexer;
2674 } // end anonymous namespace
2676 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2678 if (Vararg) {
2679 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2680 StringRef Str = parseStringToEndOfStatement();
2681 MA.emplace_back(AsmToken::String, Str);
2683 return false;
2686 unsigned ParenLevel = 0;
2688 // Darwin doesn't use spaces to delmit arguments.
2689 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2691 bool SpaceEaten;
2693 while (true) {
2694 SpaceEaten = false;
2695 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2696 return TokError("unexpected token in macro instantiation");
2698 if (ParenLevel == 0) {
2700 if (Lexer.is(AsmToken::Comma))
2701 break;
2703 if (Lexer.is(AsmToken::Space)) {
2704 SpaceEaten = true;
2705 Lexer.Lex(); // Eat spaces
2708 // Spaces can delimit parameters, but could also be part an expression.
2709 // If the token after a space is an operator, add the token and the next
2710 // one into this argument
2711 if (!IsDarwin) {
2712 if (isOperator(Lexer.getKind())) {
2713 MA.push_back(getTok());
2714 Lexer.Lex();
2716 // Whitespace after an operator can be ignored.
2717 if (Lexer.is(AsmToken::Space))
2718 Lexer.Lex();
2720 continue;
2723 if (SpaceEaten)
2724 break;
2727 // handleMacroEntry relies on not advancing the lexer here
2728 // to be able to fill in the remaining default parameter values
2729 if (Lexer.is(AsmToken::EndOfStatement))
2730 break;
2732 // Adjust the current parentheses level.
2733 if (Lexer.is(AsmToken::LParen))
2734 ++ParenLevel;
2735 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2736 --ParenLevel;
2738 // Append the token to the current argument list.
2739 MA.push_back(getTok());
2740 Lexer.Lex();
2743 if (ParenLevel != 0)
2744 return TokError("unbalanced parentheses in macro argument");
2745 return false;
2748 // Parse the macro instantiation arguments.
2749 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2750 MCAsmMacroArguments &A) {
2751 const unsigned NParameters = M ? M->Parameters.size() : 0;
2752 bool NamedParametersFound = false;
2753 SmallVector<SMLoc, 4> FALocs;
2755 A.resize(NParameters);
2756 FALocs.resize(NParameters);
2758 // Parse two kinds of macro invocations:
2759 // - macros defined without any parameters accept an arbitrary number of them
2760 // - macros defined with parameters accept at most that many of them
2761 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2762 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2763 ++Parameter) {
2764 SMLoc IDLoc = Lexer.getLoc();
2765 MCAsmMacroParameter FA;
2767 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2768 if (parseIdentifier(FA.Name))
2769 return Error(IDLoc, "invalid argument identifier for formal argument");
2771 if (Lexer.isNot(AsmToken::Equal))
2772 return TokError("expected '=' after formal parameter identifier");
2774 Lex();
2776 NamedParametersFound = true;
2778 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2780 if (NamedParametersFound && FA.Name.empty())
2781 return Error(IDLoc, "cannot mix positional and keyword arguments");
2783 SMLoc StrLoc = Lexer.getLoc();
2784 SMLoc EndLoc;
2785 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
2786 const MCExpr *AbsoluteExp;
2787 int64_t Value;
2788 /// Eat '%'
2789 Lex();
2790 if (parseExpression(AbsoluteExp, EndLoc))
2791 return false;
2792 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2793 getStreamer().getAssemblerPtr()))
2794 return Error(StrLoc, "expected absolute expression");
2795 const char *StrChar = StrLoc.getPointer();
2796 const char *EndChar = EndLoc.getPointer();
2797 AsmToken newToken(AsmToken::Integer,
2798 StringRef(StrChar, EndChar - StrChar), Value);
2799 FA.Value.push_back(newToken);
2800 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
2801 isAngleBracketString(StrLoc, EndLoc)) {
2802 const char *StrChar = StrLoc.getPointer();
2803 const char *EndChar = EndLoc.getPointer();
2804 jumpToLoc(EndLoc, CurBuffer);
2805 /// Eat from '<' to '>'
2806 Lex();
2807 AsmToken newToken(AsmToken::String,
2808 StringRef(StrChar, EndChar - StrChar));
2809 FA.Value.push_back(newToken);
2810 } else if(parseMacroArgument(FA.Value, Vararg))
2811 return true;
2813 unsigned PI = Parameter;
2814 if (!FA.Name.empty()) {
2815 unsigned FAI = 0;
2816 for (FAI = 0; FAI < NParameters; ++FAI)
2817 if (M->Parameters[FAI].Name == FA.Name)
2818 break;
2820 if (FAI >= NParameters) {
2821 assert(M && "expected macro to be defined");
2822 return Error(IDLoc, "parameter named '" + FA.Name +
2823 "' does not exist for macro '" + M->Name + "'");
2825 PI = FAI;
2828 if (!FA.Value.empty()) {
2829 if (A.size() <= PI)
2830 A.resize(PI + 1);
2831 A[PI] = FA.Value;
2833 if (FALocs.size() <= PI)
2834 FALocs.resize(PI + 1);
2836 FALocs[PI] = Lexer.getLoc();
2839 // At the end of the statement, fill in remaining arguments that have
2840 // default values. If there aren't any, then the next argument is
2841 // required but missing
2842 if (Lexer.is(AsmToken::EndOfStatement)) {
2843 bool Failure = false;
2844 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2845 if (A[FAI].empty()) {
2846 if (M->Parameters[FAI].Required) {
2847 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2848 "missing value for required parameter "
2849 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2850 Failure = true;
2853 if (!M->Parameters[FAI].Value.empty())
2854 A[FAI] = M->Parameters[FAI].Value;
2857 return Failure;
2860 if (Lexer.is(AsmToken::Comma))
2861 Lex();
2864 return TokError("too many positional arguments");
2867 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2868 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2869 // eliminate this, although we should protect against infinite loops.
2870 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2871 if (ActiveMacros.size() == MaxNestingDepth) {
2872 std::ostringstream MaxNestingDepthError;
2873 MaxNestingDepthError << "macros cannot be nested more than "
2874 << MaxNestingDepth << " levels deep."
2875 << " Use -asm-macro-max-nesting-depth to increase "
2876 "this limit.";
2877 return TokError(MaxNestingDepthError.str());
2880 MCAsmMacroArguments A;
2881 if (parseMacroArguments(M, A))
2882 return true;
2884 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2885 // to hold the macro body with substitutions.
2886 SmallString<256> Buf;
2887 StringRef Body = M->Body;
2888 raw_svector_ostream OS(Buf);
2890 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2891 return true;
2893 // We include the .endmacro in the buffer as our cue to exit the macro
2894 // instantiation.
2895 OS << ".endmacro\n";
2897 std::unique_ptr<MemoryBuffer> Instantiation =
2898 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2900 // Create the macro instantiation object and add to the current macro
2901 // instantiation stack.
2902 MacroInstantiation *MI = new MacroInstantiation{
2903 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
2904 ActiveMacros.push_back(MI);
2906 ++NumOfMacroInstantiations;
2908 // Jump to the macro instantiation and prime the lexer.
2909 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2910 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2911 Lex();
2913 return false;
2916 void AsmParser::handleMacroExit() {
2917 // Jump to the EndOfStatement we should return to, and consume it.
2918 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2919 Lex();
2921 // Pop the instantiation entry.
2922 delete ActiveMacros.back();
2923 ActiveMacros.pop_back();
2926 bool AsmParser::parseAssignment(StringRef Name, AssignmentKind Kind) {
2927 MCSymbol *Sym;
2928 const MCExpr *Value;
2929 SMLoc ExprLoc = getTok().getLoc();
2930 bool AllowRedef =
2931 Kind == AssignmentKind::Set || Kind == AssignmentKind::Equal;
2932 if (MCParserUtils::parseAssignmentExpression(Name, AllowRedef, *this, Sym,
2933 Value))
2934 return true;
2936 if (!Sym) {
2937 // In the case where we parse an expression starting with a '.', we will
2938 // not generate an error, nor will we create a symbol. In this case we
2939 // should just return out.
2940 return false;
2943 if (discardLTOSymbol(Name))
2944 return false;
2946 // Do the assignment.
2947 switch (Kind) {
2948 case AssignmentKind::Equal:
2949 Out.emitAssignment(Sym, Value);
2950 break;
2951 case AssignmentKind::Set:
2952 case AssignmentKind::Equiv:
2953 Out.emitAssignment(Sym, Value);
2954 Out.emitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2955 break;
2956 case AssignmentKind::LTOSetConditional:
2957 if (Value->getKind() != MCExpr::SymbolRef)
2958 return Error(ExprLoc, "expected identifier");
2960 Out.emitConditionalAssignment(Sym, Value);
2961 break;
2964 return false;
2967 /// parseIdentifier:
2968 /// ::= identifier
2969 /// ::= string
2970 bool AsmParser::parseIdentifier(StringRef &Res) {
2971 // The assembler has relaxed rules for accepting identifiers, in particular we
2972 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2973 // separate tokens. At this level, we have already lexed so we cannot (currently)
2974 // handle this as a context dependent token, instead we detect adjacent tokens
2975 // and return the combined identifier.
2976 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2977 SMLoc PrefixLoc = getLexer().getLoc();
2979 // Consume the prefix character, and check for a following identifier.
2981 AsmToken Buf[1];
2982 Lexer.peekTokens(Buf, false);
2984 if (Buf[0].isNot(AsmToken::Identifier) && Buf[0].isNot(AsmToken::Integer))
2985 return true;
2987 // We have a '$' or '@' followed by an identifier or integer token, make
2988 // sure they are adjacent.
2989 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2990 return true;
2992 // eat $ or @
2993 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2994 // Construct the joined identifier and consume the token.
2995 Res = StringRef(PrefixLoc.getPointer(), getTok().getString().size() + 1);
2996 Lex(); // Parser Lex to maintain invariants.
2997 return false;
3000 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
3001 return true;
3003 Res = getTok().getIdentifier();
3005 Lex(); // Consume the identifier token.
3007 return false;
3010 /// parseDirectiveSet:
3011 /// ::= .equ identifier ',' expression
3012 /// ::= .equiv identifier ',' expression
3013 /// ::= .set identifier ',' expression
3014 /// ::= .lto_set_conditional identifier ',' expression
3015 bool AsmParser::parseDirectiveSet(StringRef IDVal, AssignmentKind Kind) {
3016 StringRef Name;
3017 if (check(parseIdentifier(Name), "expected identifier") || parseComma() ||
3018 parseAssignment(Name, Kind))
3019 return true;
3020 return false;
3023 bool AsmParser::parseEscapedString(std::string &Data) {
3024 if (check(getTok().isNot(AsmToken::String), "expected string"))
3025 return true;
3027 Data = "";
3028 StringRef Str = getTok().getStringContents();
3029 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
3030 if (Str[i] != '\\') {
3031 Data += Str[i];
3032 continue;
3035 // Recognize escaped characters. Note that this escape semantics currently
3036 // loosely follows Darwin 'as'.
3037 ++i;
3038 if (i == e)
3039 return TokError("unexpected backslash at end of string");
3041 // Recognize hex sequences similarly to GNU 'as'.
3042 if (Str[i] == 'x' || Str[i] == 'X') {
3043 size_t length = Str.size();
3044 if (i + 1 >= length || !isHexDigit(Str[i + 1]))
3045 return TokError("invalid hexadecimal escape sequence");
3047 // Consume hex characters. GNU 'as' reads all hexadecimal characters and
3048 // then truncates to the lower 16 bits. Seems reasonable.
3049 unsigned Value = 0;
3050 while (i + 1 < length && isHexDigit(Str[i + 1]))
3051 Value = Value * 16 + hexDigitValue(Str[++i]);
3053 Data += (unsigned char)(Value & 0xFF);
3054 continue;
3057 // Recognize octal sequences.
3058 if ((unsigned)(Str[i] - '0') <= 7) {
3059 // Consume up to three octal characters.
3060 unsigned Value = Str[i] - '0';
3062 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
3063 ++i;
3064 Value = Value * 8 + (Str[i] - '0');
3066 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
3067 ++i;
3068 Value = Value * 8 + (Str[i] - '0');
3072 if (Value > 255)
3073 return TokError("invalid octal escape sequence (out of range)");
3075 Data += (unsigned char)Value;
3076 continue;
3079 // Otherwise recognize individual escapes.
3080 switch (Str[i]) {
3081 default:
3082 // Just reject invalid escape sequences for now.
3083 return TokError("invalid escape sequence (unrecognized character)");
3085 case 'b': Data += '\b'; break;
3086 case 'f': Data += '\f'; break;
3087 case 'n': Data += '\n'; break;
3088 case 'r': Data += '\r'; break;
3089 case 't': Data += '\t'; break;
3090 case '"': Data += '"'; break;
3091 case '\\': Data += '\\'; break;
3095 Lex();
3096 return false;
3099 bool AsmParser::parseAngleBracketString(std::string &Data) {
3100 SMLoc EndLoc, StartLoc = getTok().getLoc();
3101 if (isAngleBracketString(StartLoc, EndLoc)) {
3102 const char *StartChar = StartLoc.getPointer() + 1;
3103 const char *EndChar = EndLoc.getPointer() - 1;
3104 jumpToLoc(EndLoc, CurBuffer);
3105 /// Eat from '<' to '>'
3106 Lex();
3108 Data = angleBracketString(StringRef(StartChar, EndChar - StartChar));
3109 return false;
3111 return true;
3114 /// parseDirectiveAscii:
3115 // ::= .ascii [ "string"+ ( , "string"+ )* ]
3116 /// ::= ( .asciz | .string ) [ "string" ( , "string" )* ]
3117 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
3118 auto parseOp = [&]() -> bool {
3119 std::string Data;
3120 if (checkForValidSection())
3121 return true;
3122 // Only support spaces as separators for .ascii directive for now. See the
3123 // discusssion at https://reviews.llvm.org/D91460 for more details.
3124 do {
3125 if (parseEscapedString(Data))
3126 return true;
3127 getStreamer().emitBytes(Data);
3128 } while (!ZeroTerminated && getTok().is(AsmToken::String));
3129 if (ZeroTerminated)
3130 getStreamer().emitBytes(StringRef("\0", 1));
3131 return false;
3134 return parseMany(parseOp);
3137 /// parseDirectiveReloc
3138 /// ::= .reloc expression , identifier [ , expression ]
3139 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
3140 const MCExpr *Offset;
3141 const MCExpr *Expr = nullptr;
3142 SMLoc OffsetLoc = Lexer.getTok().getLoc();
3144 if (parseExpression(Offset))
3145 return true;
3146 if (parseComma() ||
3147 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
3148 return true;
3150 SMLoc NameLoc = Lexer.getTok().getLoc();
3151 StringRef Name = Lexer.getTok().getIdentifier();
3152 Lex();
3154 if (Lexer.is(AsmToken::Comma)) {
3155 Lex();
3156 SMLoc ExprLoc = Lexer.getLoc();
3157 if (parseExpression(Expr))
3158 return true;
3160 MCValue Value;
3161 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
3162 return Error(ExprLoc, "expression must be relocatable");
3165 if (parseEOL())
3166 return true;
3168 const MCTargetAsmParser &MCT = getTargetParser();
3169 const MCSubtargetInfo &STI = MCT.getSTI();
3170 if (std::optional<std::pair<bool, std::string>> Err =
3171 getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc,
3172 STI))
3173 return Error(Err->first ? NameLoc : OffsetLoc, Err->second);
3175 return false;
3178 /// parseDirectiveValue
3179 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
3180 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3181 auto parseOp = [&]() -> bool {
3182 const MCExpr *Value;
3183 SMLoc ExprLoc = getLexer().getLoc();
3184 if (checkForValidSection() || parseExpression(Value))
3185 return true;
3186 // Special case constant expressions to match code generator.
3187 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3188 assert(Size <= 8 && "Invalid size");
3189 uint64_t IntValue = MCE->getValue();
3190 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3191 return Error(ExprLoc, "out of range literal value");
3192 getStreamer().emitIntValue(IntValue, Size);
3193 } else
3194 getStreamer().emitValue(Value, Size, ExprLoc);
3195 return false;
3198 return parseMany(parseOp);
3201 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3202 if (Asm.getTok().isNot(AsmToken::Integer) &&
3203 Asm.getTok().isNot(AsmToken::BigNum))
3204 return Asm.TokError("unknown token in expression");
3205 SMLoc ExprLoc = Asm.getTok().getLoc();
3206 APInt IntValue = Asm.getTok().getAPIntVal();
3207 Asm.Lex();
3208 if (!IntValue.isIntN(128))
3209 return Asm.Error(ExprLoc, "out of range literal value");
3210 if (!IntValue.isIntN(64)) {
3211 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3212 lo = IntValue.getLoBits(64).getZExtValue();
3213 } else {
3214 hi = 0;
3215 lo = IntValue.getZExtValue();
3217 return false;
3220 /// ParseDirectiveOctaValue
3221 /// ::= .octa [ hexconstant (, hexconstant)* ]
3223 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3224 auto parseOp = [&]() -> bool {
3225 if (checkForValidSection())
3226 return true;
3227 uint64_t hi, lo;
3228 if (parseHexOcta(*this, hi, lo))
3229 return true;
3230 if (MAI.isLittleEndian()) {
3231 getStreamer().emitInt64(lo);
3232 getStreamer().emitInt64(hi);
3233 } else {
3234 getStreamer().emitInt64(hi);
3235 getStreamer().emitInt64(lo);
3237 return false;
3240 return parseMany(parseOp);
3243 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3244 // We don't truly support arithmetic on floating point expressions, so we
3245 // have to manually parse unary prefixes.
3246 bool IsNeg = false;
3247 if (getLexer().is(AsmToken::Minus)) {
3248 Lexer.Lex();
3249 IsNeg = true;
3250 } else if (getLexer().is(AsmToken::Plus))
3251 Lexer.Lex();
3253 if (Lexer.is(AsmToken::Error))
3254 return TokError(Lexer.getErr());
3255 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3256 Lexer.isNot(AsmToken::Identifier))
3257 return TokError("unexpected token in directive");
3259 // Convert to an APFloat.
3260 APFloat Value(Semantics);
3261 StringRef IDVal = getTok().getString();
3262 if (getLexer().is(AsmToken::Identifier)) {
3263 if (!IDVal.compare_insensitive("infinity") ||
3264 !IDVal.compare_insensitive("inf"))
3265 Value = APFloat::getInf(Semantics);
3266 else if (!IDVal.compare_insensitive("nan"))
3267 Value = APFloat::getNaN(Semantics, false, ~0);
3268 else
3269 return TokError("invalid floating point literal");
3270 } else if (errorToBool(
3271 Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven)
3272 .takeError()))
3273 return TokError("invalid floating point literal");
3274 if (IsNeg)
3275 Value.changeSign();
3277 // Consume the numeric token.
3278 Lex();
3280 Res = Value.bitcastToAPInt();
3282 return false;
3285 /// parseDirectiveRealValue
3286 /// ::= (.single | .double) [ expression (, expression)* ]
3287 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3288 const fltSemantics &Semantics) {
3289 auto parseOp = [&]() -> bool {
3290 APInt AsInt;
3291 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3292 return true;
3293 getStreamer().emitIntValue(AsInt.getLimitedValue(),
3294 AsInt.getBitWidth() / 8);
3295 return false;
3298 return parseMany(parseOp);
3301 /// parseDirectiveZero
3302 /// ::= .zero expression
3303 bool AsmParser::parseDirectiveZero() {
3304 SMLoc NumBytesLoc = Lexer.getLoc();
3305 const MCExpr *NumBytes;
3306 if (checkForValidSection() || parseExpression(NumBytes))
3307 return true;
3309 int64_t Val = 0;
3310 if (getLexer().is(AsmToken::Comma)) {
3311 Lex();
3312 if (parseAbsoluteExpression(Val))
3313 return true;
3316 if (parseEOL())
3317 return true;
3318 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3320 return false;
3323 /// parseDirectiveFill
3324 /// ::= .fill expression [ , expression [ , expression ] ]
3325 bool AsmParser::parseDirectiveFill() {
3326 SMLoc NumValuesLoc = Lexer.getLoc();
3327 const MCExpr *NumValues;
3328 if (checkForValidSection() || parseExpression(NumValues))
3329 return true;
3331 int64_t FillSize = 1;
3332 int64_t FillExpr = 0;
3334 SMLoc SizeLoc, ExprLoc;
3336 if (parseOptionalToken(AsmToken::Comma)) {
3337 SizeLoc = getTok().getLoc();
3338 if (parseAbsoluteExpression(FillSize))
3339 return true;
3340 if (parseOptionalToken(AsmToken::Comma)) {
3341 ExprLoc = getTok().getLoc();
3342 if (parseAbsoluteExpression(FillExpr))
3343 return true;
3346 if (parseEOL())
3347 return true;
3349 if (FillSize < 0) {
3350 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3351 return false;
3353 if (FillSize > 8) {
3354 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3355 FillSize = 8;
3358 if (!isUInt<32>(FillExpr) && FillSize > 4)
3359 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3361 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3363 return false;
3366 /// parseDirectiveOrg
3367 /// ::= .org expression [ , expression ]
3368 bool AsmParser::parseDirectiveOrg() {
3369 const MCExpr *Offset;
3370 SMLoc OffsetLoc = Lexer.getLoc();
3371 if (checkForValidSection() || parseExpression(Offset))
3372 return true;
3374 // Parse optional fill expression.
3375 int64_t FillExpr = 0;
3376 if (parseOptionalToken(AsmToken::Comma))
3377 if (parseAbsoluteExpression(FillExpr))
3378 return true;
3379 if (parseEOL())
3380 return true;
3382 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3383 return false;
3386 /// parseDirectiveAlign
3387 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3388 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3389 SMLoc AlignmentLoc = getLexer().getLoc();
3390 int64_t Alignment;
3391 SMLoc MaxBytesLoc;
3392 bool HasFillExpr = false;
3393 int64_t FillExpr = 0;
3394 int64_t MaxBytesToFill = 0;
3395 SMLoc FillExprLoc;
3397 auto parseAlign = [&]() -> bool {
3398 if (parseAbsoluteExpression(Alignment))
3399 return true;
3400 if (parseOptionalToken(AsmToken::Comma)) {
3401 // The fill expression can be omitted while specifying a maximum number of
3402 // alignment bytes, e.g:
3403 // .align 3,,4
3404 if (getTok().isNot(AsmToken::Comma)) {
3405 HasFillExpr = true;
3406 if (parseTokenLoc(FillExprLoc) || parseAbsoluteExpression(FillExpr))
3407 return true;
3409 if (parseOptionalToken(AsmToken::Comma))
3410 if (parseTokenLoc(MaxBytesLoc) ||
3411 parseAbsoluteExpression(MaxBytesToFill))
3412 return true;
3414 return parseEOL();
3417 if (checkForValidSection())
3418 return true;
3419 // Ignore empty '.p2align' directives for GNU-as compatibility
3420 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3421 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3422 return parseEOL();
3424 if (parseAlign())
3425 return true;
3427 // Always emit an alignment here even if we thrown an error.
3428 bool ReturnVal = false;
3430 // Compute alignment in bytes.
3431 if (IsPow2) {
3432 // FIXME: Diagnose overflow.
3433 if (Alignment >= 32) {
3434 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3435 Alignment = 31;
3438 Alignment = 1ULL << Alignment;
3439 } else {
3440 // Reject alignments that aren't either a power of two or zero,
3441 // for gas compatibility. Alignment of zero is silently rounded
3442 // up to one.
3443 if (Alignment == 0)
3444 Alignment = 1;
3445 else if (!isPowerOf2_64(Alignment)) {
3446 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3447 Alignment = llvm::bit_floor<uint64_t>(Alignment);
3449 if (!isUInt<32>(Alignment)) {
3450 ReturnVal |= Error(AlignmentLoc, "alignment must be smaller than 2**32");
3451 Alignment = 1u << 31;
3455 if (HasFillExpr && FillExpr != 0) {
3456 MCSection *Sec = getStreamer().getCurrentSectionOnly();
3457 if (Sec && Sec->isVirtualSection()) {
3458 ReturnVal |=
3459 Warning(FillExprLoc, "ignoring non-zero fill value in " +
3460 Sec->getVirtualSectionKind() + " section '" +
3461 Sec->getName() + "'");
3462 FillExpr = 0;
3466 // Diagnose non-sensical max bytes to align.
3467 if (MaxBytesLoc.isValid()) {
3468 if (MaxBytesToFill < 1) {
3469 ReturnVal |= Error(MaxBytesLoc,
3470 "alignment directive can never be satisfied in this "
3471 "many bytes, ignoring maximum bytes expression");
3472 MaxBytesToFill = 0;
3475 if (MaxBytesToFill >= Alignment) {
3476 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3477 "has no effect");
3478 MaxBytesToFill = 0;
3482 // Check whether we should use optimal code alignment for this .align
3483 // directive.
3484 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3485 assert(Section && "must have section to emit alignment");
3486 bool useCodeAlign = Section->useCodeAlign();
3487 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3488 ValueSize == 1 && useCodeAlign) {
3489 getStreamer().emitCodeAlignment(
3490 Align(Alignment), &getTargetParser().getSTI(), MaxBytesToFill);
3491 } else {
3492 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3493 getStreamer().emitValueToAlignment(Align(Alignment), FillExpr, ValueSize,
3494 MaxBytesToFill);
3497 return ReturnVal;
3500 /// parseDirectiveFile
3501 /// ::= .file filename
3502 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3503 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3504 // FIXME: I'm not sure what this is.
3505 int64_t FileNumber = -1;
3506 if (getLexer().is(AsmToken::Integer)) {
3507 FileNumber = getTok().getIntVal();
3508 Lex();
3510 if (FileNumber < 0)
3511 return TokError("negative file number");
3514 std::string Path;
3516 // Usually the directory and filename together, otherwise just the directory.
3517 // Allow the strings to have escaped octal character sequence.
3518 if (parseEscapedString(Path))
3519 return true;
3521 StringRef Directory;
3522 StringRef Filename;
3523 std::string FilenameData;
3524 if (getLexer().is(AsmToken::String)) {
3525 if (check(FileNumber == -1,
3526 "explicit path specified, but no file number") ||
3527 parseEscapedString(FilenameData))
3528 return true;
3529 Filename = FilenameData;
3530 Directory = Path;
3531 } else {
3532 Filename = Path;
3535 uint64_t MD5Hi, MD5Lo;
3536 bool HasMD5 = false;
3538 std::optional<StringRef> Source;
3539 bool HasSource = false;
3540 std::string SourceString;
3542 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3543 StringRef Keyword;
3544 if (check(getTok().isNot(AsmToken::Identifier),
3545 "unexpected token in '.file' directive") ||
3546 parseIdentifier(Keyword))
3547 return true;
3548 if (Keyword == "md5") {
3549 HasMD5 = true;
3550 if (check(FileNumber == -1,
3551 "MD5 checksum specified, but no file number") ||
3552 parseHexOcta(*this, MD5Hi, MD5Lo))
3553 return true;
3554 } else if (Keyword == "source") {
3555 HasSource = true;
3556 if (check(FileNumber == -1,
3557 "source specified, but no file number") ||
3558 check(getTok().isNot(AsmToken::String),
3559 "unexpected token in '.file' directive") ||
3560 parseEscapedString(SourceString))
3561 return true;
3562 } else {
3563 return TokError("unexpected token in '.file' directive");
3567 if (FileNumber == -1) {
3568 // Ignore the directive if there is no number and the target doesn't support
3569 // numberless .file directives. This allows some portability of assembler
3570 // between different object file formats.
3571 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3572 getStreamer().emitFileDirective(Filename);
3573 } else {
3574 // In case there is a -g option as well as debug info from directive .file,
3575 // we turn off the -g option, directly use the existing debug info instead.
3576 // Throw away any implicit file table for the assembler source.
3577 if (Ctx.getGenDwarfForAssembly()) {
3578 Ctx.getMCDwarfLineTable(0).resetFileTable();
3579 Ctx.setGenDwarfForAssembly(false);
3582 std::optional<MD5::MD5Result> CKMem;
3583 if (HasMD5) {
3584 MD5::MD5Result Sum;
3585 for (unsigned i = 0; i != 8; ++i) {
3586 Sum[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3587 Sum[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3589 CKMem = Sum;
3591 if (HasSource) {
3592 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3593 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3594 Source = StringRef(SourceBuf, SourceString.size());
3596 if (FileNumber == 0) {
3597 // Upgrade to Version 5 for assembly actions like clang -c a.s.
3598 if (Ctx.getDwarfVersion() < 5)
3599 Ctx.setDwarfVersion(5);
3600 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3601 } else {
3602 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3603 FileNumber, Directory, Filename, CKMem, Source);
3604 if (!FileNumOrErr)
3605 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3607 // Alert the user if there are some .file directives with MD5 and some not.
3608 // But only do that once.
3609 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3610 ReportedInconsistentMD5 = true;
3611 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3615 return false;
3618 /// parseDirectiveLine
3619 /// ::= .line [number]
3620 bool AsmParser::parseDirectiveLine() {
3621 int64_t LineNumber;
3622 if (getLexer().is(AsmToken::Integer)) {
3623 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3624 return true;
3625 (void)LineNumber;
3626 // FIXME: Do something with the .line.
3628 return parseEOL();
3631 /// parseDirectiveLoc
3632 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3633 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3634 /// The first number is a file number, must have been previously assigned with
3635 /// a .file directive, the second number is the line number and optionally the
3636 /// third number is a column position (zero if not specified). The remaining
3637 /// optional items are .loc sub-directives.
3638 bool AsmParser::parseDirectiveLoc() {
3639 int64_t FileNumber = 0, LineNumber = 0;
3640 SMLoc Loc = getTok().getLoc();
3641 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3642 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
3643 "file number less than one in '.loc' directive") ||
3644 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3645 "unassigned file number in '.loc' directive"))
3646 return true;
3648 // optional
3649 if (getLexer().is(AsmToken::Integer)) {
3650 LineNumber = getTok().getIntVal();
3651 if (LineNumber < 0)
3652 return TokError("line number less than zero in '.loc' directive");
3653 Lex();
3656 int64_t ColumnPos = 0;
3657 if (getLexer().is(AsmToken::Integer)) {
3658 ColumnPos = getTok().getIntVal();
3659 if (ColumnPos < 0)
3660 return TokError("column position less than zero in '.loc' directive");
3661 Lex();
3664 auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags();
3665 unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT;
3666 unsigned Isa = 0;
3667 int64_t Discriminator = 0;
3669 auto parseLocOp = [&]() -> bool {
3670 StringRef Name;
3671 SMLoc Loc = getTok().getLoc();
3672 if (parseIdentifier(Name))
3673 return TokError("unexpected token in '.loc' directive");
3675 if (Name == "basic_block")
3676 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3677 else if (Name == "prologue_end")
3678 Flags |= DWARF2_FLAG_PROLOGUE_END;
3679 else if (Name == "epilogue_begin")
3680 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3681 else if (Name == "is_stmt") {
3682 Loc = getTok().getLoc();
3683 const MCExpr *Value;
3684 if (parseExpression(Value))
3685 return true;
3686 // The expression must be the constant 0 or 1.
3687 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3688 int Value = MCE->getValue();
3689 if (Value == 0)
3690 Flags &= ~DWARF2_FLAG_IS_STMT;
3691 else if (Value == 1)
3692 Flags |= DWARF2_FLAG_IS_STMT;
3693 else
3694 return Error(Loc, "is_stmt value not 0 or 1");
3695 } else {
3696 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3698 } else if (Name == "isa") {
3699 Loc = getTok().getLoc();
3700 const MCExpr *Value;
3701 if (parseExpression(Value))
3702 return true;
3703 // The expression must be a constant greater or equal to 0.
3704 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3705 int Value = MCE->getValue();
3706 if (Value < 0)
3707 return Error(Loc, "isa number less than zero");
3708 Isa = Value;
3709 } else {
3710 return Error(Loc, "isa number not a constant value");
3712 } else if (Name == "discriminator") {
3713 if (parseAbsoluteExpression(Discriminator))
3714 return true;
3715 } else {
3716 return Error(Loc, "unknown sub-directive in '.loc' directive");
3718 return false;
3721 if (parseMany(parseLocOp, false /*hasComma*/))
3722 return true;
3724 getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3725 Isa, Discriminator, StringRef());
3727 return false;
3730 /// parseDirectiveStabs
3731 /// ::= .stabs string, number, number, number
3732 bool AsmParser::parseDirectiveStabs() {
3733 return TokError("unsupported directive '.stabs'");
3736 /// parseDirectiveCVFile
3737 /// ::= .cv_file number filename [checksum] [checksumkind]
3738 bool AsmParser::parseDirectiveCVFile() {
3739 SMLoc FileNumberLoc = getTok().getLoc();
3740 int64_t FileNumber;
3741 std::string Filename;
3742 std::string Checksum;
3743 int64_t ChecksumKind = 0;
3745 if (parseIntToken(FileNumber,
3746 "expected file number in '.cv_file' directive") ||
3747 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3748 check(getTok().isNot(AsmToken::String),
3749 "unexpected token in '.cv_file' directive") ||
3750 parseEscapedString(Filename))
3751 return true;
3752 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3753 if (check(getTok().isNot(AsmToken::String),
3754 "unexpected token in '.cv_file' directive") ||
3755 parseEscapedString(Checksum) ||
3756 parseIntToken(ChecksumKind,
3757 "expected checksum kind in '.cv_file' directive") ||
3758 parseEOL())
3759 return true;
3762 Checksum = fromHex(Checksum);
3763 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3764 memcpy(CKMem, Checksum.data(), Checksum.size());
3765 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3766 Checksum.size());
3768 if (!getStreamer().emitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3769 static_cast<uint8_t>(ChecksumKind)))
3770 return Error(FileNumberLoc, "file number already allocated");
3772 return false;
3775 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3776 StringRef DirectiveName) {
3777 SMLoc Loc;
3778 return parseTokenLoc(Loc) ||
3779 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3780 "' directive") ||
3781 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3782 "expected function id within range [0, UINT_MAX)");
3785 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3786 SMLoc Loc;
3787 return parseTokenLoc(Loc) ||
3788 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3789 "' directive") ||
3790 check(FileNumber < 1, Loc, "file number less than one in '" +
3791 DirectiveName + "' directive") ||
3792 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3793 "unassigned file number in '" + DirectiveName + "' directive");
3796 /// parseDirectiveCVFuncId
3797 /// ::= .cv_func_id FunctionId
3799 /// Introduces a function ID that can be used with .cv_loc.
3800 bool AsmParser::parseDirectiveCVFuncId() {
3801 SMLoc FunctionIdLoc = getTok().getLoc();
3802 int64_t FunctionId;
3804 if (parseCVFunctionId(FunctionId, ".cv_func_id") || parseEOL())
3805 return true;
3807 if (!getStreamer().emitCVFuncIdDirective(FunctionId))
3808 return Error(FunctionIdLoc, "function id already allocated");
3810 return false;
3813 /// parseDirectiveCVInlineSiteId
3814 /// ::= .cv_inline_site_id FunctionId
3815 /// "within" IAFunc
3816 /// "inlined_at" IAFile IALine [IACol]
3818 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3819 /// at" source location information for use in the line table of the caller,
3820 /// whether the caller is a real function or another inlined call site.
3821 bool AsmParser::parseDirectiveCVInlineSiteId() {
3822 SMLoc FunctionIdLoc = getTok().getLoc();
3823 int64_t FunctionId;
3824 int64_t IAFunc;
3825 int64_t IAFile;
3826 int64_t IALine;
3827 int64_t IACol = 0;
3829 // FunctionId
3830 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3831 return true;
3833 // "within"
3834 if (check((getLexer().isNot(AsmToken::Identifier) ||
3835 getTok().getIdentifier() != "within"),
3836 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3837 return true;
3838 Lex();
3840 // IAFunc
3841 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3842 return true;
3844 // "inlined_at"
3845 if (check((getLexer().isNot(AsmToken::Identifier) ||
3846 getTok().getIdentifier() != "inlined_at"),
3847 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3848 "directive") )
3849 return true;
3850 Lex();
3852 // IAFile IALine
3853 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3854 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3855 return true;
3857 // [IACol]
3858 if (getLexer().is(AsmToken::Integer)) {
3859 IACol = getTok().getIntVal();
3860 Lex();
3863 if (parseEOL())
3864 return true;
3866 if (!getStreamer().emitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3867 IALine, IACol, FunctionIdLoc))
3868 return Error(FunctionIdLoc, "function id already allocated");
3870 return false;
3873 /// parseDirectiveCVLoc
3874 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3875 /// [is_stmt VALUE]
3876 /// The first number is a file number, must have been previously assigned with
3877 /// a .file directive, the second number is the line number and optionally the
3878 /// third number is a column position (zero if not specified). The remaining
3879 /// optional items are .loc sub-directives.
3880 bool AsmParser::parseDirectiveCVLoc() {
3881 SMLoc DirectiveLoc = getTok().getLoc();
3882 int64_t FunctionId, FileNumber;
3883 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3884 parseCVFileId(FileNumber, ".cv_loc"))
3885 return true;
3887 int64_t LineNumber = 0;
3888 if (getLexer().is(AsmToken::Integer)) {
3889 LineNumber = getTok().getIntVal();
3890 if (LineNumber < 0)
3891 return TokError("line number less than zero in '.cv_loc' directive");
3892 Lex();
3895 int64_t ColumnPos = 0;
3896 if (getLexer().is(AsmToken::Integer)) {
3897 ColumnPos = getTok().getIntVal();
3898 if (ColumnPos < 0)
3899 return TokError("column position less than zero in '.cv_loc' directive");
3900 Lex();
3903 bool PrologueEnd = false;
3904 uint64_t IsStmt = 0;
3906 auto parseOp = [&]() -> bool {
3907 StringRef Name;
3908 SMLoc Loc = getTok().getLoc();
3909 if (parseIdentifier(Name))
3910 return TokError("unexpected token in '.cv_loc' directive");
3911 if (Name == "prologue_end")
3912 PrologueEnd = true;
3913 else if (Name == "is_stmt") {
3914 Loc = getTok().getLoc();
3915 const MCExpr *Value;
3916 if (parseExpression(Value))
3917 return true;
3918 // The expression must be the constant 0 or 1.
3919 IsStmt = ~0ULL;
3920 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3921 IsStmt = MCE->getValue();
3923 if (IsStmt > 1)
3924 return Error(Loc, "is_stmt value not 0 or 1");
3925 } else {
3926 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3928 return false;
3931 if (parseMany(parseOp, false /*hasComma*/))
3932 return true;
3934 getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber,
3935 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3936 DirectiveLoc);
3937 return false;
3940 /// parseDirectiveCVLinetable
3941 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3942 bool AsmParser::parseDirectiveCVLinetable() {
3943 int64_t FunctionId;
3944 StringRef FnStartName, FnEndName;
3945 SMLoc Loc = getTok().getLoc();
3946 if (parseCVFunctionId(FunctionId, ".cv_linetable") || parseComma() ||
3947 parseTokenLoc(Loc) ||
3948 check(parseIdentifier(FnStartName), Loc,
3949 "expected identifier in directive") ||
3950 parseComma() || parseTokenLoc(Loc) ||
3951 check(parseIdentifier(FnEndName), Loc,
3952 "expected identifier in directive"))
3953 return true;
3955 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3956 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3958 getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3959 return false;
3962 /// parseDirectiveCVInlineLinetable
3963 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3964 bool AsmParser::parseDirectiveCVInlineLinetable() {
3965 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3966 StringRef FnStartName, FnEndName;
3967 SMLoc Loc = getTok().getLoc();
3968 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3969 parseTokenLoc(Loc) ||
3970 parseIntToken(
3971 SourceFileId,
3972 "expected SourceField in '.cv_inline_linetable' directive") ||
3973 check(SourceFileId <= 0, Loc,
3974 "File id less than zero in '.cv_inline_linetable' directive") ||
3975 parseTokenLoc(Loc) ||
3976 parseIntToken(
3977 SourceLineNum,
3978 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3979 check(SourceLineNum < 0, Loc,
3980 "Line number less than zero in '.cv_inline_linetable' directive") ||
3981 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3982 "expected identifier in directive") ||
3983 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3984 "expected identifier in directive"))
3985 return true;
3987 if (parseEOL())
3988 return true;
3990 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3991 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3992 getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3993 SourceLineNum, FnStartSym,
3994 FnEndSym);
3995 return false;
3998 void AsmParser::initializeCVDefRangeTypeMap() {
3999 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
4000 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
4001 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
4002 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
4005 /// parseDirectiveCVDefRange
4006 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
4007 bool AsmParser::parseDirectiveCVDefRange() {
4008 SMLoc Loc;
4009 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
4010 while (getLexer().is(AsmToken::Identifier)) {
4011 Loc = getLexer().getLoc();
4012 StringRef GapStartName;
4013 if (parseIdentifier(GapStartName))
4014 return Error(Loc, "expected identifier in directive");
4015 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
4017 Loc = getLexer().getLoc();
4018 StringRef GapEndName;
4019 if (parseIdentifier(GapEndName))
4020 return Error(Loc, "expected identifier in directive");
4021 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
4023 Ranges.push_back({GapStartSym, GapEndSym});
4026 StringRef CVDefRangeTypeStr;
4027 if (parseToken(
4028 AsmToken::Comma,
4029 "expected comma before def_range type in .cv_def_range directive") ||
4030 parseIdentifier(CVDefRangeTypeStr))
4031 return Error(Loc, "expected def_range type in directive");
4033 StringMap<CVDefRangeType>::const_iterator CVTypeIt =
4034 CVDefRangeTypeMap.find(CVDefRangeTypeStr);
4035 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
4036 ? CVDR_DEFRANGE
4037 : CVTypeIt->getValue();
4038 switch (CVDRType) {
4039 case CVDR_DEFRANGE_REGISTER: {
4040 int64_t DRRegister;
4041 if (parseToken(AsmToken::Comma, "expected comma before register number in "
4042 ".cv_def_range directive") ||
4043 parseAbsoluteExpression(DRRegister))
4044 return Error(Loc, "expected register number");
4046 codeview::DefRangeRegisterHeader DRHdr;
4047 DRHdr.Register = DRRegister;
4048 DRHdr.MayHaveNoName = 0;
4049 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4050 break;
4052 case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
4053 int64_t DROffset;
4054 if (parseToken(AsmToken::Comma,
4055 "expected comma before offset in .cv_def_range directive") ||
4056 parseAbsoluteExpression(DROffset))
4057 return Error(Loc, "expected offset value");
4059 codeview::DefRangeFramePointerRelHeader DRHdr;
4060 DRHdr.Offset = DROffset;
4061 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4062 break;
4064 case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
4065 int64_t DRRegister;
4066 int64_t DROffsetInParent;
4067 if (parseToken(AsmToken::Comma, "expected comma before register number in "
4068 ".cv_def_range directive") ||
4069 parseAbsoluteExpression(DRRegister))
4070 return Error(Loc, "expected register number");
4071 if (parseToken(AsmToken::Comma,
4072 "expected comma before offset in .cv_def_range directive") ||
4073 parseAbsoluteExpression(DROffsetInParent))
4074 return Error(Loc, "expected offset value");
4076 codeview::DefRangeSubfieldRegisterHeader DRHdr;
4077 DRHdr.Register = DRRegister;
4078 DRHdr.MayHaveNoName = 0;
4079 DRHdr.OffsetInParent = DROffsetInParent;
4080 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4081 break;
4083 case CVDR_DEFRANGE_REGISTER_REL: {
4084 int64_t DRRegister;
4085 int64_t DRFlags;
4086 int64_t DRBasePointerOffset;
4087 if (parseToken(AsmToken::Comma, "expected comma before register number in "
4088 ".cv_def_range directive") ||
4089 parseAbsoluteExpression(DRRegister))
4090 return Error(Loc, "expected register value");
4091 if (parseToken(
4092 AsmToken::Comma,
4093 "expected comma before flag value in .cv_def_range directive") ||
4094 parseAbsoluteExpression(DRFlags))
4095 return Error(Loc, "expected flag value");
4096 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
4097 "in .cv_def_range directive") ||
4098 parseAbsoluteExpression(DRBasePointerOffset))
4099 return Error(Loc, "expected base pointer offset value");
4101 codeview::DefRangeRegisterRelHeader DRHdr;
4102 DRHdr.Register = DRRegister;
4103 DRHdr.Flags = DRFlags;
4104 DRHdr.BasePointerOffset = DRBasePointerOffset;
4105 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
4106 break;
4108 default:
4109 return Error(Loc, "unexpected def_range type in .cv_def_range directive");
4111 return true;
4114 /// parseDirectiveCVString
4115 /// ::= .cv_stringtable "string"
4116 bool AsmParser::parseDirectiveCVString() {
4117 std::string Data;
4118 if (checkForValidSection() || parseEscapedString(Data))
4119 return true;
4121 // Put the string in the table and emit the offset.
4122 std::pair<StringRef, unsigned> Insertion =
4123 getCVContext().addToStringTable(Data);
4124 getStreamer().emitInt32(Insertion.second);
4125 return false;
4128 /// parseDirectiveCVStringTable
4129 /// ::= .cv_stringtable
4130 bool AsmParser::parseDirectiveCVStringTable() {
4131 getStreamer().emitCVStringTableDirective();
4132 return false;
4135 /// parseDirectiveCVFileChecksums
4136 /// ::= .cv_filechecksums
4137 bool AsmParser::parseDirectiveCVFileChecksums() {
4138 getStreamer().emitCVFileChecksumsDirective();
4139 return false;
4142 /// parseDirectiveCVFileChecksumOffset
4143 /// ::= .cv_filechecksumoffset fileno
4144 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4145 int64_t FileNo;
4146 if (parseIntToken(FileNo, "expected identifier in directive"))
4147 return true;
4148 if (parseEOL())
4149 return true;
4150 getStreamer().emitCVFileChecksumOffsetDirective(FileNo);
4151 return false;
4154 /// parseDirectiveCVFPOData
4155 /// ::= .cv_fpo_data procsym
4156 bool AsmParser::parseDirectiveCVFPOData() {
4157 SMLoc DirLoc = getLexer().getLoc();
4158 StringRef ProcName;
4159 if (parseIdentifier(ProcName))
4160 return TokError("expected symbol name");
4161 if (parseEOL())
4162 return true;
4163 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
4164 getStreamer().emitCVFPOData(ProcSym, DirLoc);
4165 return false;
4168 /// parseDirectiveCFISections
4169 /// ::= .cfi_sections section [, section]
4170 bool AsmParser::parseDirectiveCFISections() {
4171 StringRef Name;
4172 bool EH = false;
4173 bool Debug = false;
4175 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4176 for (;;) {
4177 if (parseIdentifier(Name))
4178 return TokError("expected .eh_frame or .debug_frame");
4179 if (Name == ".eh_frame")
4180 EH = true;
4181 else if (Name == ".debug_frame")
4182 Debug = true;
4183 if (parseOptionalToken(AsmToken::EndOfStatement))
4184 break;
4185 if (parseComma())
4186 return true;
4189 getStreamer().emitCFISections(EH, Debug);
4190 return false;
4193 /// parseDirectiveCFIStartProc
4194 /// ::= .cfi_startproc [simple]
4195 bool AsmParser::parseDirectiveCFIStartProc() {
4196 StringRef Simple;
4197 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4198 if (check(parseIdentifier(Simple) || Simple != "simple",
4199 "unexpected token") ||
4200 parseEOL())
4201 return true;
4204 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4205 // being produced if this directive is emitted as part of preprocessor macro
4206 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4207 // Tools like llvm-mc on the other hand are not affected by it, and report
4208 // correct context information.
4209 getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc());
4210 return false;
4213 /// parseDirectiveCFIEndProc
4214 /// ::= .cfi_endproc
4215 bool AsmParser::parseDirectiveCFIEndProc() {
4216 if (parseEOL())
4217 return true;
4218 getStreamer().emitCFIEndProc();
4219 return false;
4222 /// parse register name or number.
4223 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
4224 SMLoc DirectiveLoc) {
4225 MCRegister RegNo;
4227 if (getLexer().isNot(AsmToken::Integer)) {
4228 if (getTargetParser().parseRegister(RegNo, DirectiveLoc, DirectiveLoc))
4229 return true;
4230 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
4231 } else
4232 return parseAbsoluteExpression(Register);
4234 return false;
4237 /// parseDirectiveCFIDefCfa
4238 /// ::= .cfi_def_cfa register, offset
4239 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
4240 int64_t Register = 0, Offset = 0;
4241 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4242 parseAbsoluteExpression(Offset) || parseEOL())
4243 return true;
4245 getStreamer().emitCFIDefCfa(Register, Offset, DirectiveLoc);
4246 return false;
4249 /// parseDirectiveCFIDefCfaOffset
4250 /// ::= .cfi_def_cfa_offset offset
4251 bool AsmParser::parseDirectiveCFIDefCfaOffset(SMLoc DirectiveLoc) {
4252 int64_t Offset = 0;
4253 if (parseAbsoluteExpression(Offset) || parseEOL())
4254 return true;
4256 getStreamer().emitCFIDefCfaOffset(Offset, DirectiveLoc);
4257 return false;
4260 /// parseDirectiveCFIRegister
4261 /// ::= .cfi_register register, register
4262 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
4263 int64_t Register1 = 0, Register2 = 0;
4264 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || parseComma() ||
4265 parseRegisterOrRegisterNumber(Register2, DirectiveLoc) || parseEOL())
4266 return true;
4268 getStreamer().emitCFIRegister(Register1, Register2, DirectiveLoc);
4269 return false;
4272 /// parseDirectiveCFIWindowSave
4273 /// ::= .cfi_window_save
4274 bool AsmParser::parseDirectiveCFIWindowSave(SMLoc DirectiveLoc) {
4275 if (parseEOL())
4276 return true;
4277 getStreamer().emitCFIWindowSave(DirectiveLoc);
4278 return false;
4281 /// parseDirectiveCFIAdjustCfaOffset
4282 /// ::= .cfi_adjust_cfa_offset adjustment
4283 bool AsmParser::parseDirectiveCFIAdjustCfaOffset(SMLoc DirectiveLoc) {
4284 int64_t Adjustment = 0;
4285 if (parseAbsoluteExpression(Adjustment) || parseEOL())
4286 return true;
4288 getStreamer().emitCFIAdjustCfaOffset(Adjustment, DirectiveLoc);
4289 return false;
4292 /// parseDirectiveCFIDefCfaRegister
4293 /// ::= .cfi_def_cfa_register register
4294 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
4295 int64_t Register = 0;
4296 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4297 return true;
4299 getStreamer().emitCFIDefCfaRegister(Register, DirectiveLoc);
4300 return false;
4303 /// parseDirectiveCFILLVMDefAspaceCfa
4304 /// ::= .cfi_llvm_def_aspace_cfa register, offset, address_space
4305 bool AsmParser::parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc) {
4306 int64_t Register = 0, Offset = 0, AddressSpace = 0;
4307 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4308 parseAbsoluteExpression(Offset) || parseComma() ||
4309 parseAbsoluteExpression(AddressSpace) || parseEOL())
4310 return true;
4312 getStreamer().emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace,
4313 DirectiveLoc);
4314 return false;
4317 /// parseDirectiveCFIOffset
4318 /// ::= .cfi_offset register, offset
4319 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
4320 int64_t Register = 0;
4321 int64_t Offset = 0;
4323 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4324 parseAbsoluteExpression(Offset) || parseEOL())
4325 return true;
4327 getStreamer().emitCFIOffset(Register, Offset, DirectiveLoc);
4328 return false;
4331 /// parseDirectiveCFIRelOffset
4332 /// ::= .cfi_rel_offset register, offset
4333 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
4334 int64_t Register = 0, Offset = 0;
4336 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
4337 parseAbsoluteExpression(Offset) || parseEOL())
4338 return true;
4340 getStreamer().emitCFIRelOffset(Register, Offset, DirectiveLoc);
4341 return false;
4344 static bool isValidEncoding(int64_t Encoding) {
4345 if (Encoding & ~0xff)
4346 return false;
4348 if (Encoding == dwarf::DW_EH_PE_omit)
4349 return true;
4351 const unsigned Format = Encoding & 0xf;
4352 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4353 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4354 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4355 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4356 return false;
4358 const unsigned Application = Encoding & 0x70;
4359 if (Application != dwarf::DW_EH_PE_absptr &&
4360 Application != dwarf::DW_EH_PE_pcrel)
4361 return false;
4363 return true;
4366 /// parseDirectiveCFIPersonalityOrLsda
4367 /// IsPersonality true for cfi_personality, false for cfi_lsda
4368 /// ::= .cfi_personality encoding, [symbol_name]
4369 /// ::= .cfi_lsda encoding, [symbol_name]
4370 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4371 int64_t Encoding = 0;
4372 if (parseAbsoluteExpression(Encoding))
4373 return true;
4374 if (Encoding == dwarf::DW_EH_PE_omit)
4375 return false;
4377 StringRef Name;
4378 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4379 parseComma() ||
4380 check(parseIdentifier(Name), "expected identifier in directive") ||
4381 parseEOL())
4382 return true;
4384 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4386 if (IsPersonality)
4387 getStreamer().emitCFIPersonality(Sym, Encoding);
4388 else
4389 getStreamer().emitCFILsda(Sym, Encoding);
4390 return false;
4393 /// parseDirectiveCFIRememberState
4394 /// ::= .cfi_remember_state
4395 bool AsmParser::parseDirectiveCFIRememberState(SMLoc DirectiveLoc) {
4396 if (parseEOL())
4397 return true;
4398 getStreamer().emitCFIRememberState(DirectiveLoc);
4399 return false;
4402 /// parseDirectiveCFIRestoreState
4403 /// ::= .cfi_remember_state
4404 bool AsmParser::parseDirectiveCFIRestoreState(SMLoc DirectiveLoc) {
4405 if (parseEOL())
4406 return true;
4407 getStreamer().emitCFIRestoreState(DirectiveLoc);
4408 return false;
4411 /// parseDirectiveCFISameValue
4412 /// ::= .cfi_same_value register
4413 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4414 int64_t Register = 0;
4416 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4417 return true;
4419 getStreamer().emitCFISameValue(Register, DirectiveLoc);
4420 return false;
4423 /// parseDirectiveCFIRestore
4424 /// ::= .cfi_restore register
4425 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4426 int64_t Register = 0;
4427 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4428 return true;
4430 getStreamer().emitCFIRestore(Register, DirectiveLoc);
4431 return false;
4434 /// parseDirectiveCFIEscape
4435 /// ::= .cfi_escape expression[,...]
4436 bool AsmParser::parseDirectiveCFIEscape(SMLoc DirectiveLoc) {
4437 std::string Values;
4438 int64_t CurrValue;
4439 if (parseAbsoluteExpression(CurrValue))
4440 return true;
4442 Values.push_back((uint8_t)CurrValue);
4444 while (getLexer().is(AsmToken::Comma)) {
4445 Lex();
4447 if (parseAbsoluteExpression(CurrValue))
4448 return true;
4450 Values.push_back((uint8_t)CurrValue);
4453 getStreamer().emitCFIEscape(Values, DirectiveLoc);
4454 return false;
4457 /// parseDirectiveCFIReturnColumn
4458 /// ::= .cfi_return_column register
4459 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4460 int64_t Register = 0;
4461 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4462 return true;
4463 getStreamer().emitCFIReturnColumn(Register);
4464 return false;
4467 /// parseDirectiveCFISignalFrame
4468 /// ::= .cfi_signal_frame
4469 bool AsmParser::parseDirectiveCFISignalFrame(SMLoc DirectiveLoc) {
4470 if (parseEOL())
4471 return true;
4473 getStreamer().emitCFISignalFrame();
4474 return false;
4477 /// parseDirectiveCFIUndefined
4478 /// ::= .cfi_undefined register
4479 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4480 int64_t Register = 0;
4482 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
4483 return true;
4485 getStreamer().emitCFIUndefined(Register, DirectiveLoc);
4486 return false;
4489 /// parseDirectiveAltmacro
4490 /// ::= .altmacro
4491 /// ::= .noaltmacro
4492 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4493 if (parseEOL())
4494 return true;
4495 AltMacroMode = (Directive == ".altmacro");
4496 return false;
4499 /// parseDirectiveMacrosOnOff
4500 /// ::= .macros_on
4501 /// ::= .macros_off
4502 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4503 if (parseEOL())
4504 return true;
4505 setMacrosEnabled(Directive == ".macros_on");
4506 return false;
4509 /// parseDirectiveMacro
4510 /// ::= .macro name[,] [parameters]
4511 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4512 StringRef Name;
4513 if (parseIdentifier(Name))
4514 return TokError("expected identifier in '.macro' directive");
4516 if (getLexer().is(AsmToken::Comma))
4517 Lex();
4519 MCAsmMacroParameters Parameters;
4520 while (getLexer().isNot(AsmToken::EndOfStatement)) {
4522 if (!Parameters.empty() && Parameters.back().Vararg)
4523 return Error(Lexer.getLoc(), "vararg parameter '" +
4524 Parameters.back().Name +
4525 "' should be the last parameter");
4527 MCAsmMacroParameter Parameter;
4528 if (parseIdentifier(Parameter.Name))
4529 return TokError("expected identifier in '.macro' directive");
4531 // Emit an error if two (or more) named parameters share the same name
4532 for (const MCAsmMacroParameter& CurrParam : Parameters)
4533 if (CurrParam.Name.equals(Parameter.Name))
4534 return TokError("macro '" + Name + "' has multiple parameters"
4535 " named '" + Parameter.Name + "'");
4537 if (Lexer.is(AsmToken::Colon)) {
4538 Lex(); // consume ':'
4540 SMLoc QualLoc;
4541 StringRef Qualifier;
4543 QualLoc = Lexer.getLoc();
4544 if (parseIdentifier(Qualifier))
4545 return Error(QualLoc, "missing parameter qualifier for "
4546 "'" + Parameter.Name + "' in macro '" + Name + "'");
4548 if (Qualifier == "req")
4549 Parameter.Required = true;
4550 else if (Qualifier == "vararg")
4551 Parameter.Vararg = true;
4552 else
4553 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4554 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4557 if (getLexer().is(AsmToken::Equal)) {
4558 Lex();
4560 SMLoc ParamLoc;
4562 ParamLoc = Lexer.getLoc();
4563 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4564 return true;
4566 if (Parameter.Required)
4567 Warning(ParamLoc, "pointless default value for required parameter "
4568 "'" + Parameter.Name + "' in macro '" + Name + "'");
4571 Parameters.push_back(std::move(Parameter));
4573 if (getLexer().is(AsmToken::Comma))
4574 Lex();
4577 // Eat just the end of statement.
4578 Lexer.Lex();
4580 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4581 AsmToken EndToken, StartToken = getTok();
4582 unsigned MacroDepth = 0;
4583 // Lex the macro definition.
4584 while (true) {
4585 // Ignore Lexing errors in macros.
4586 while (Lexer.is(AsmToken::Error)) {
4587 Lexer.Lex();
4590 // Check whether we have reached the end of the file.
4591 if (getLexer().is(AsmToken::Eof))
4592 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4594 // Otherwise, check whether we have reach the .endmacro or the start of a
4595 // preprocessor line marker.
4596 if (getLexer().is(AsmToken::Identifier)) {
4597 if (getTok().getIdentifier() == ".endm" ||
4598 getTok().getIdentifier() == ".endmacro") {
4599 if (MacroDepth == 0) { // Outermost macro.
4600 EndToken = getTok();
4601 Lexer.Lex();
4602 if (getLexer().isNot(AsmToken::EndOfStatement))
4603 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4604 "' directive");
4605 break;
4606 } else {
4607 // Otherwise we just found the end of an inner macro.
4608 --MacroDepth;
4610 } else if (getTok().getIdentifier() == ".macro") {
4611 // We allow nested macros. Those aren't instantiated until the outermost
4612 // macro is expanded so just ignore them for now.
4613 ++MacroDepth;
4615 } else if (Lexer.is(AsmToken::HashDirective)) {
4616 (void)parseCppHashLineFilenameComment(getLexer().getLoc());
4619 // Otherwise, scan til the end of the statement.
4620 eatToEndOfStatement();
4623 if (getContext().lookupMacro(Name)) {
4624 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4627 const char *BodyStart = StartToken.getLoc().getPointer();
4628 const char *BodyEnd = EndToken.getLoc().getPointer();
4629 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4630 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4631 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4632 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4633 Macro.dump());
4634 getContext().defineMacro(Name, std::move(Macro));
4635 return false;
4638 /// checkForBadMacro
4640 /// With the support added for named parameters there may be code out there that
4641 /// is transitioning from positional parameters. In versions of gas that did
4642 /// not support named parameters they would be ignored on the macro definition.
4643 /// But to support both styles of parameters this is not possible so if a macro
4644 /// definition has named parameters but does not use them and has what appears
4645 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4646 /// warning that the positional parameter found in body which have no effect.
4647 /// Hoping the developer will either remove the named parameters from the macro
4648 /// definition so the positional parameters get used if that was what was
4649 /// intended or change the macro to use the named parameters. It is possible
4650 /// this warning will trigger when the none of the named parameters are used
4651 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4652 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4653 StringRef Body,
4654 ArrayRef<MCAsmMacroParameter> Parameters) {
4655 // If this macro is not defined with named parameters the warning we are
4656 // checking for here doesn't apply.
4657 unsigned NParameters = Parameters.size();
4658 if (NParameters == 0)
4659 return;
4661 bool NamedParametersFound = false;
4662 bool PositionalParametersFound = false;
4664 // Look at the body of the macro for use of both the named parameters and what
4665 // are likely to be positional parameters. This is what expandMacro() is
4666 // doing when it finds the parameters in the body.
4667 while (!Body.empty()) {
4668 // Scan for the next possible parameter.
4669 std::size_t End = Body.size(), Pos = 0;
4670 for (; Pos != End; ++Pos) {
4671 // Check for a substitution or escape.
4672 // This macro is defined with parameters, look for \foo, \bar, etc.
4673 if (Body[Pos] == '\\' && Pos + 1 != End)
4674 break;
4676 // This macro should have parameters, but look for $0, $1, ..., $n too.
4677 if (Body[Pos] != '$' || Pos + 1 == End)
4678 continue;
4679 char Next = Body[Pos + 1];
4680 if (Next == '$' || Next == 'n' ||
4681 isdigit(static_cast<unsigned char>(Next)))
4682 break;
4685 // Check if we reached the end.
4686 if (Pos == End)
4687 break;
4689 if (Body[Pos] == '$') {
4690 switch (Body[Pos + 1]) {
4691 // $$ => $
4692 case '$':
4693 break;
4695 // $n => number of arguments
4696 case 'n':
4697 PositionalParametersFound = true;
4698 break;
4700 // $[0-9] => argument
4701 default: {
4702 PositionalParametersFound = true;
4703 break;
4706 Pos += 2;
4707 } else {
4708 unsigned I = Pos + 1;
4709 while (isIdentifierChar(Body[I]) && I + 1 != End)
4710 ++I;
4712 const char *Begin = Body.data() + Pos + 1;
4713 StringRef Argument(Begin, I - (Pos + 1));
4714 unsigned Index = 0;
4715 for (; Index < NParameters; ++Index)
4716 if (Parameters[Index].Name == Argument)
4717 break;
4719 if (Index == NParameters) {
4720 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4721 Pos += 3;
4722 else {
4723 Pos = I;
4725 } else {
4726 NamedParametersFound = true;
4727 Pos += 1 + Argument.size();
4730 // Update the scan point.
4731 Body = Body.substr(Pos);
4734 if (!NamedParametersFound && PositionalParametersFound)
4735 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4736 "used in macro body, possible positional parameter "
4737 "found in body which will have no effect");
4740 /// parseDirectiveExitMacro
4741 /// ::= .exitm
4742 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4743 if (parseEOL())
4744 return true;
4746 if (!isInsideMacroInstantiation())
4747 return TokError("unexpected '" + Directive + "' in file, "
4748 "no current macro definition");
4750 // Exit all conditionals that are active in the current macro.
4751 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4752 TheCondState = TheCondStack.back();
4753 TheCondStack.pop_back();
4756 handleMacroExit();
4757 return false;
4760 /// parseDirectiveEndMacro
4761 /// ::= .endm
4762 /// ::= .endmacro
4763 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4764 if (getLexer().isNot(AsmToken::EndOfStatement))
4765 return TokError("unexpected token in '" + Directive + "' directive");
4767 // If we are inside a macro instantiation, terminate the current
4768 // instantiation.
4769 if (isInsideMacroInstantiation()) {
4770 handleMacroExit();
4771 return false;
4774 // Otherwise, this .endmacro is a stray entry in the file; well formed
4775 // .endmacro directives are handled during the macro definition parsing.
4776 return TokError("unexpected '" + Directive + "' in file, "
4777 "no current macro definition");
4780 /// parseDirectivePurgeMacro
4781 /// ::= .purgem name
4782 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4783 StringRef Name;
4784 SMLoc Loc;
4785 if (parseTokenLoc(Loc) ||
4786 check(parseIdentifier(Name), Loc,
4787 "expected identifier in '.purgem' directive") ||
4788 parseEOL())
4789 return true;
4791 if (!getContext().lookupMacro(Name))
4792 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4794 getContext().undefineMacro(Name);
4795 DEBUG_WITH_TYPE("asm-macros", dbgs()
4796 << "Un-defining macro: " << Name << "\n");
4797 return false;
4800 /// parseDirectiveBundleAlignMode
4801 /// ::= {.bundle_align_mode} expression
4802 bool AsmParser::parseDirectiveBundleAlignMode() {
4803 // Expect a single argument: an expression that evaluates to a constant
4804 // in the inclusive range 0-30.
4805 SMLoc ExprLoc = getLexer().getLoc();
4806 int64_t AlignSizePow2;
4807 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4808 parseEOL() ||
4809 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4810 "invalid bundle alignment size (expected between 0 and 30)"))
4811 return true;
4813 getStreamer().emitBundleAlignMode(Align(1ULL << AlignSizePow2));
4814 return false;
4817 /// parseDirectiveBundleLock
4818 /// ::= {.bundle_lock} [align_to_end]
4819 bool AsmParser::parseDirectiveBundleLock() {
4820 if (checkForValidSection())
4821 return true;
4822 bool AlignToEnd = false;
4824 StringRef Option;
4825 SMLoc Loc = getTok().getLoc();
4826 const char *kInvalidOptionError =
4827 "invalid option for '.bundle_lock' directive";
4829 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4830 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4831 check(Option != "align_to_end", Loc, kInvalidOptionError) || parseEOL())
4832 return true;
4833 AlignToEnd = true;
4836 getStreamer().emitBundleLock(AlignToEnd);
4837 return false;
4840 /// parseDirectiveBundleLock
4841 /// ::= {.bundle_lock}
4842 bool AsmParser::parseDirectiveBundleUnlock() {
4843 if (checkForValidSection() || parseEOL())
4844 return true;
4846 getStreamer().emitBundleUnlock();
4847 return false;
4850 /// parseDirectiveSpace
4851 /// ::= (.skip | .space) expression [ , expression ]
4852 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4853 SMLoc NumBytesLoc = Lexer.getLoc();
4854 const MCExpr *NumBytes;
4855 if (checkForValidSection() || parseExpression(NumBytes))
4856 return true;
4858 int64_t FillExpr = 0;
4859 if (parseOptionalToken(AsmToken::Comma))
4860 if (parseAbsoluteExpression(FillExpr))
4861 return true;
4862 if (parseEOL())
4863 return true;
4865 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4866 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4868 return false;
4871 /// parseDirectiveDCB
4872 /// ::= .dcb.{b, l, w} expression, expression
4873 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4874 SMLoc NumValuesLoc = Lexer.getLoc();
4875 int64_t NumValues;
4876 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4877 return true;
4879 if (NumValues < 0) {
4880 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4881 return false;
4884 if (parseComma())
4885 return true;
4887 const MCExpr *Value;
4888 SMLoc ExprLoc = getLexer().getLoc();
4889 if (parseExpression(Value))
4890 return true;
4892 // Special case constant expressions to match code generator.
4893 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4894 assert(Size <= 8 && "Invalid size");
4895 uint64_t IntValue = MCE->getValue();
4896 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4897 return Error(ExprLoc, "literal value out of range for directive");
4898 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4899 getStreamer().emitIntValue(IntValue, Size);
4900 } else {
4901 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4902 getStreamer().emitValue(Value, Size, ExprLoc);
4905 return parseEOL();
4908 /// parseDirectiveRealDCB
4909 /// ::= .dcb.{d, s} expression, expression
4910 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4911 SMLoc NumValuesLoc = Lexer.getLoc();
4912 int64_t NumValues;
4913 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4914 return true;
4916 if (NumValues < 0) {
4917 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4918 return false;
4921 if (parseComma())
4922 return true;
4924 APInt AsInt;
4925 if (parseRealValue(Semantics, AsInt) || parseEOL())
4926 return true;
4928 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4929 getStreamer().emitIntValue(AsInt.getLimitedValue(),
4930 AsInt.getBitWidth() / 8);
4932 return false;
4935 /// parseDirectiveDS
4936 /// ::= .ds.{b, d, l, p, s, w, x} expression
4937 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4938 SMLoc NumValuesLoc = Lexer.getLoc();
4939 int64_t NumValues;
4940 if (checkForValidSection() || parseAbsoluteExpression(NumValues) ||
4941 parseEOL())
4942 return true;
4944 if (NumValues < 0) {
4945 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4946 return false;
4949 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4950 getStreamer().emitFill(Size, 0);
4952 return false;
4955 /// parseDirectiveLEB128
4956 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4957 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4958 if (checkForValidSection())
4959 return true;
4961 auto parseOp = [&]() -> bool {
4962 const MCExpr *Value;
4963 if (parseExpression(Value))
4964 return true;
4965 if (Signed)
4966 getStreamer().emitSLEB128Value(Value);
4967 else
4968 getStreamer().emitULEB128Value(Value);
4969 return false;
4972 return parseMany(parseOp);
4975 /// parseDirectiveSymbolAttribute
4976 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4977 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4978 auto parseOp = [&]() -> bool {
4979 StringRef Name;
4980 SMLoc Loc = getTok().getLoc();
4981 if (parseIdentifier(Name))
4982 return Error(Loc, "expected identifier");
4984 if (discardLTOSymbol(Name))
4985 return false;
4987 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4989 // Assembler local symbols don't make any sense here, except for directives
4990 // that the symbol should be tagged.
4991 if (Sym->isTemporary() && Attr != MCSA_Memtag)
4992 return Error(Loc, "non-local symbol required");
4994 if (!getStreamer().emitSymbolAttribute(Sym, Attr))
4995 return Error(Loc, "unable to emit symbol attribute");
4996 return false;
4999 return parseMany(parseOp);
5002 /// parseDirectiveComm
5003 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
5004 bool AsmParser::parseDirectiveComm(bool IsLocal) {
5005 if (checkForValidSection())
5006 return true;
5008 SMLoc IDLoc = getLexer().getLoc();
5009 StringRef Name;
5010 if (parseIdentifier(Name))
5011 return TokError("expected identifier in directive");
5013 // Handle the identifier as the key symbol.
5014 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5016 if (parseComma())
5017 return true;
5019 int64_t Size;
5020 SMLoc SizeLoc = getLexer().getLoc();
5021 if (parseAbsoluteExpression(Size))
5022 return true;
5024 int64_t Pow2Alignment = 0;
5025 SMLoc Pow2AlignmentLoc;
5026 if (getLexer().is(AsmToken::Comma)) {
5027 Lex();
5028 Pow2AlignmentLoc = getLexer().getLoc();
5029 if (parseAbsoluteExpression(Pow2Alignment))
5030 return true;
5032 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
5033 if (IsLocal && LCOMM == LCOMM::NoAlignment)
5034 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
5036 // If this target takes alignments in bytes (not log) validate and convert.
5037 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
5038 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
5039 if (!isPowerOf2_64(Pow2Alignment))
5040 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
5041 Pow2Alignment = Log2_64(Pow2Alignment);
5045 if (parseEOL())
5046 return true;
5048 // NOTE: a size of zero for a .comm should create a undefined symbol
5049 // but a size of .lcomm creates a bss symbol of size zero.
5050 if (Size < 0)
5051 return Error(SizeLoc, "size must be non-negative");
5053 Sym->redefineIfPossible();
5054 if (!Sym->isUndefined())
5055 return Error(IDLoc, "invalid symbol redefinition");
5057 // Create the Symbol as a common or local common with Size and Pow2Alignment
5058 if (IsLocal) {
5059 getStreamer().emitLocalCommonSymbol(Sym, Size,
5060 Align(1ULL << Pow2Alignment));
5061 return false;
5064 getStreamer().emitCommonSymbol(Sym, Size, Align(1ULL << Pow2Alignment));
5065 return false;
5068 /// parseDirectiveAbort
5069 /// ::= .abort [... message ...]
5070 bool AsmParser::parseDirectiveAbort() {
5071 // FIXME: Use loc from directive.
5072 SMLoc Loc = getLexer().getLoc();
5074 StringRef Str = parseStringToEndOfStatement();
5075 if (parseEOL())
5076 return true;
5078 if (Str.empty())
5079 return Error(Loc, ".abort detected. Assembly stopping.");
5080 else
5081 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
5082 // FIXME: Actually abort assembly here.
5084 return false;
5087 /// parseDirectiveInclude
5088 /// ::= .include "filename"
5089 bool AsmParser::parseDirectiveInclude() {
5090 // Allow the strings to have escaped octal character sequence.
5091 std::string Filename;
5092 SMLoc IncludeLoc = getTok().getLoc();
5094 if (check(getTok().isNot(AsmToken::String),
5095 "expected string in '.include' directive") ||
5096 parseEscapedString(Filename) ||
5097 check(getTok().isNot(AsmToken::EndOfStatement),
5098 "unexpected token in '.include' directive") ||
5099 // Attempt to switch the lexer to the included file before consuming the
5100 // end of statement to avoid losing it when we switch.
5101 check(enterIncludeFile(Filename), IncludeLoc,
5102 "Could not find include file '" + Filename + "'"))
5103 return true;
5105 return false;
5108 /// parseDirectiveIncbin
5109 /// ::= .incbin "filename" [ , skip [ , count ] ]
5110 bool AsmParser::parseDirectiveIncbin() {
5111 // Allow the strings to have escaped octal character sequence.
5112 std::string Filename;
5113 SMLoc IncbinLoc = getTok().getLoc();
5114 if (check(getTok().isNot(AsmToken::String),
5115 "expected string in '.incbin' directive") ||
5116 parseEscapedString(Filename))
5117 return true;
5119 int64_t Skip = 0;
5120 const MCExpr *Count = nullptr;
5121 SMLoc SkipLoc, CountLoc;
5122 if (parseOptionalToken(AsmToken::Comma)) {
5123 // The skip expression can be omitted while specifying the count, e.g:
5124 // .incbin "filename",,4
5125 if (getTok().isNot(AsmToken::Comma)) {
5126 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
5127 return true;
5129 if (parseOptionalToken(AsmToken::Comma)) {
5130 CountLoc = getTok().getLoc();
5131 if (parseExpression(Count))
5132 return true;
5136 if (parseEOL())
5137 return true;
5139 if (check(Skip < 0, SkipLoc, "skip is negative"))
5140 return true;
5142 // Attempt to process the included file.
5143 if (processIncbinFile(Filename, Skip, Count, CountLoc))
5144 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
5145 return false;
5148 /// parseDirectiveIf
5149 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
5150 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
5151 TheCondStack.push_back(TheCondState);
5152 TheCondState.TheCond = AsmCond::IfCond;
5153 if (TheCondState.Ignore) {
5154 eatToEndOfStatement();
5155 } else {
5156 int64_t ExprValue;
5157 if (parseAbsoluteExpression(ExprValue) || parseEOL())
5158 return true;
5160 switch (DirKind) {
5161 default:
5162 llvm_unreachable("unsupported directive");
5163 case DK_IF:
5164 case DK_IFNE:
5165 break;
5166 case DK_IFEQ:
5167 ExprValue = ExprValue == 0;
5168 break;
5169 case DK_IFGE:
5170 ExprValue = ExprValue >= 0;
5171 break;
5172 case DK_IFGT:
5173 ExprValue = ExprValue > 0;
5174 break;
5175 case DK_IFLE:
5176 ExprValue = ExprValue <= 0;
5177 break;
5178 case DK_IFLT:
5179 ExprValue = ExprValue < 0;
5180 break;
5183 TheCondState.CondMet = ExprValue;
5184 TheCondState.Ignore = !TheCondState.CondMet;
5187 return false;
5190 /// parseDirectiveIfb
5191 /// ::= .ifb string
5192 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
5193 TheCondStack.push_back(TheCondState);
5194 TheCondState.TheCond = AsmCond::IfCond;
5196 if (TheCondState.Ignore) {
5197 eatToEndOfStatement();
5198 } else {
5199 StringRef Str = parseStringToEndOfStatement();
5201 if (parseEOL())
5202 return true;
5204 TheCondState.CondMet = ExpectBlank == Str.empty();
5205 TheCondState.Ignore = !TheCondState.CondMet;
5208 return false;
5211 /// parseDirectiveIfc
5212 /// ::= .ifc string1, string2
5213 /// ::= .ifnc string1, string2
5214 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
5215 TheCondStack.push_back(TheCondState);
5216 TheCondState.TheCond = AsmCond::IfCond;
5218 if (TheCondState.Ignore) {
5219 eatToEndOfStatement();
5220 } else {
5221 StringRef Str1 = parseStringToComma();
5223 if (parseComma())
5224 return true;
5226 StringRef Str2 = parseStringToEndOfStatement();
5228 if (parseEOL())
5229 return true;
5231 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
5232 TheCondState.Ignore = !TheCondState.CondMet;
5235 return false;
5238 /// parseDirectiveIfeqs
5239 /// ::= .ifeqs string1, string2
5240 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
5241 if (Lexer.isNot(AsmToken::String)) {
5242 if (ExpectEqual)
5243 return TokError("expected string parameter for '.ifeqs' directive");
5244 return TokError("expected string parameter for '.ifnes' directive");
5247 StringRef String1 = getTok().getStringContents();
5248 Lex();
5250 if (Lexer.isNot(AsmToken::Comma)) {
5251 if (ExpectEqual)
5252 return TokError(
5253 "expected comma after first string for '.ifeqs' directive");
5254 return TokError("expected comma after first string for '.ifnes' directive");
5257 Lex();
5259 if (Lexer.isNot(AsmToken::String)) {
5260 if (ExpectEqual)
5261 return TokError("expected string parameter for '.ifeqs' directive");
5262 return TokError("expected string parameter for '.ifnes' directive");
5265 StringRef String2 = getTok().getStringContents();
5266 Lex();
5268 TheCondStack.push_back(TheCondState);
5269 TheCondState.TheCond = AsmCond::IfCond;
5270 TheCondState.CondMet = ExpectEqual == (String1 == String2);
5271 TheCondState.Ignore = !TheCondState.CondMet;
5273 return false;
5276 /// parseDirectiveIfdef
5277 /// ::= .ifdef symbol
5278 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5279 StringRef Name;
5280 TheCondStack.push_back(TheCondState);
5281 TheCondState.TheCond = AsmCond::IfCond;
5283 if (TheCondState.Ignore) {
5284 eatToEndOfStatement();
5285 } else {
5286 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5287 parseEOL())
5288 return true;
5290 MCSymbol *Sym = getContext().lookupSymbol(Name);
5292 if (expect_defined)
5293 TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
5294 else
5295 TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
5296 TheCondState.Ignore = !TheCondState.CondMet;
5299 return false;
5302 /// parseDirectiveElseIf
5303 /// ::= .elseif expression
5304 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
5305 if (TheCondState.TheCond != AsmCond::IfCond &&
5306 TheCondState.TheCond != AsmCond::ElseIfCond)
5307 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5308 " .if or an .elseif");
5309 TheCondState.TheCond = AsmCond::ElseIfCond;
5311 bool LastIgnoreState = false;
5312 if (!TheCondStack.empty())
5313 LastIgnoreState = TheCondStack.back().Ignore;
5314 if (LastIgnoreState || TheCondState.CondMet) {
5315 TheCondState.Ignore = true;
5316 eatToEndOfStatement();
5317 } else {
5318 int64_t ExprValue;
5319 if (parseAbsoluteExpression(ExprValue))
5320 return true;
5322 if (parseEOL())
5323 return true;
5325 TheCondState.CondMet = ExprValue;
5326 TheCondState.Ignore = !TheCondState.CondMet;
5329 return false;
5332 /// parseDirectiveElse
5333 /// ::= .else
5334 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
5335 if (parseEOL())
5336 return true;
5338 if (TheCondState.TheCond != AsmCond::IfCond &&
5339 TheCondState.TheCond != AsmCond::ElseIfCond)
5340 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5341 " an .if or an .elseif");
5342 TheCondState.TheCond = AsmCond::ElseCond;
5343 bool LastIgnoreState = false;
5344 if (!TheCondStack.empty())
5345 LastIgnoreState = TheCondStack.back().Ignore;
5346 if (LastIgnoreState || TheCondState.CondMet)
5347 TheCondState.Ignore = true;
5348 else
5349 TheCondState.Ignore = false;
5351 return false;
5354 /// parseDirectiveEnd
5355 /// ::= .end
5356 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5357 if (parseEOL())
5358 return true;
5360 while (Lexer.isNot(AsmToken::Eof))
5361 Lexer.Lex();
5363 return false;
5366 /// parseDirectiveError
5367 /// ::= .err
5368 /// ::= .error [string]
5369 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5370 if (!TheCondStack.empty()) {
5371 if (TheCondStack.back().Ignore) {
5372 eatToEndOfStatement();
5373 return false;
5377 if (!WithMessage)
5378 return Error(L, ".err encountered");
5380 StringRef Message = ".error directive invoked in source file";
5381 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5382 if (Lexer.isNot(AsmToken::String))
5383 return TokError(".error argument must be a string");
5385 Message = getTok().getStringContents();
5386 Lex();
5389 return Error(L, Message);
5392 /// parseDirectiveWarning
5393 /// ::= .warning [string]
5394 bool AsmParser::parseDirectiveWarning(SMLoc L) {
5395 if (!TheCondStack.empty()) {
5396 if (TheCondStack.back().Ignore) {
5397 eatToEndOfStatement();
5398 return false;
5402 StringRef Message = ".warning directive invoked in source file";
5404 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5405 if (Lexer.isNot(AsmToken::String))
5406 return TokError(".warning argument must be a string");
5408 Message = getTok().getStringContents();
5409 Lex();
5410 if (parseEOL())
5411 return true;
5414 return Warning(L, Message);
5417 /// parseDirectiveEndIf
5418 /// ::= .endif
5419 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5420 if (parseEOL())
5421 return true;
5423 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5424 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5425 "an .if or .else");
5426 if (!TheCondStack.empty()) {
5427 TheCondState = TheCondStack.back();
5428 TheCondStack.pop_back();
5431 return false;
5434 void AsmParser::initializeDirectiveKindMap() {
5435 /* Lookup will be done with the directive
5436 * converted to lower case, so all these
5437 * keys should be lower case.
5438 * (target specific directives are handled
5439 * elsewhere)
5441 DirectiveKindMap[".set"] = DK_SET;
5442 DirectiveKindMap[".equ"] = DK_EQU;
5443 DirectiveKindMap[".equiv"] = DK_EQUIV;
5444 DirectiveKindMap[".ascii"] = DK_ASCII;
5445 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5446 DirectiveKindMap[".string"] = DK_STRING;
5447 DirectiveKindMap[".byte"] = DK_BYTE;
5448 DirectiveKindMap[".short"] = DK_SHORT;
5449 DirectiveKindMap[".value"] = DK_VALUE;
5450 DirectiveKindMap[".2byte"] = DK_2BYTE;
5451 DirectiveKindMap[".long"] = DK_LONG;
5452 DirectiveKindMap[".int"] = DK_INT;
5453 DirectiveKindMap[".4byte"] = DK_4BYTE;
5454 DirectiveKindMap[".quad"] = DK_QUAD;
5455 DirectiveKindMap[".8byte"] = DK_8BYTE;
5456 DirectiveKindMap[".octa"] = DK_OCTA;
5457 DirectiveKindMap[".single"] = DK_SINGLE;
5458 DirectiveKindMap[".float"] = DK_FLOAT;
5459 DirectiveKindMap[".double"] = DK_DOUBLE;
5460 DirectiveKindMap[".align"] = DK_ALIGN;
5461 DirectiveKindMap[".align32"] = DK_ALIGN32;
5462 DirectiveKindMap[".balign"] = DK_BALIGN;
5463 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5464 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5465 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5466 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5467 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5468 DirectiveKindMap[".org"] = DK_ORG;
5469 DirectiveKindMap[".fill"] = DK_FILL;
5470 DirectiveKindMap[".zero"] = DK_ZERO;
5471 DirectiveKindMap[".extern"] = DK_EXTERN;
5472 DirectiveKindMap[".globl"] = DK_GLOBL;
5473 DirectiveKindMap[".global"] = DK_GLOBAL;
5474 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5475 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5476 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5477 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5478 DirectiveKindMap[".reference"] = DK_REFERENCE;
5479 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5480 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5481 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5482 DirectiveKindMap[".cold"] = DK_COLD;
5483 DirectiveKindMap[".comm"] = DK_COMM;
5484 DirectiveKindMap[".common"] = DK_COMMON;
5485 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5486 DirectiveKindMap[".abort"] = DK_ABORT;
5487 DirectiveKindMap[".include"] = DK_INCLUDE;
5488 DirectiveKindMap[".incbin"] = DK_INCBIN;
5489 DirectiveKindMap[".code16"] = DK_CODE16;
5490 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5491 DirectiveKindMap[".rept"] = DK_REPT;
5492 DirectiveKindMap[".rep"] = DK_REPT;
5493 DirectiveKindMap[".irp"] = DK_IRP;
5494 DirectiveKindMap[".irpc"] = DK_IRPC;
5495 DirectiveKindMap[".endr"] = DK_ENDR;
5496 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5497 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5498 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5499 DirectiveKindMap[".if"] = DK_IF;
5500 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5501 DirectiveKindMap[".ifge"] = DK_IFGE;
5502 DirectiveKindMap[".ifgt"] = DK_IFGT;
5503 DirectiveKindMap[".ifle"] = DK_IFLE;
5504 DirectiveKindMap[".iflt"] = DK_IFLT;
5505 DirectiveKindMap[".ifne"] = DK_IFNE;
5506 DirectiveKindMap[".ifb"] = DK_IFB;
5507 DirectiveKindMap[".ifnb"] = DK_IFNB;
5508 DirectiveKindMap[".ifc"] = DK_IFC;
5509 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5510 DirectiveKindMap[".ifnc"] = DK_IFNC;
5511 DirectiveKindMap[".ifnes"] = DK_IFNES;
5512 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5513 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5514 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5515 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5516 DirectiveKindMap[".else"] = DK_ELSE;
5517 DirectiveKindMap[".end"] = DK_END;
5518 DirectiveKindMap[".endif"] = DK_ENDIF;
5519 DirectiveKindMap[".skip"] = DK_SKIP;
5520 DirectiveKindMap[".space"] = DK_SPACE;
5521 DirectiveKindMap[".file"] = DK_FILE;
5522 DirectiveKindMap[".line"] = DK_LINE;
5523 DirectiveKindMap[".loc"] = DK_LOC;
5524 DirectiveKindMap[".stabs"] = DK_STABS;
5525 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5526 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5527 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5528 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5529 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5530 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5531 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5532 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
5533 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5534 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5535 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5536 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5537 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5538 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5539 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5540 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5541 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5542 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5543 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5544 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5545 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5546 DirectiveKindMap[".cfi_llvm_def_aspace_cfa"] = DK_CFI_LLVM_DEF_ASPACE_CFA;
5547 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5548 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5549 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5550 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5551 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5552 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5553 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5554 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5555 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5556 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5557 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5558 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5559 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5560 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5561 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
5562 DirectiveKindMap[".cfi_mte_tagged_frame"] = DK_CFI_MTE_TAGGED_FRAME;
5563 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5564 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5565 DirectiveKindMap[".macro"] = DK_MACRO;
5566 DirectiveKindMap[".exitm"] = DK_EXITM;
5567 DirectiveKindMap[".endm"] = DK_ENDM;
5568 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5569 DirectiveKindMap[".purgem"] = DK_PURGEM;
5570 DirectiveKindMap[".err"] = DK_ERR;
5571 DirectiveKindMap[".error"] = DK_ERROR;
5572 DirectiveKindMap[".warning"] = DK_WARNING;
5573 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5574 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5575 DirectiveKindMap[".reloc"] = DK_RELOC;
5576 DirectiveKindMap[".dc"] = DK_DC;
5577 DirectiveKindMap[".dc.a"] = DK_DC_A;
5578 DirectiveKindMap[".dc.b"] = DK_DC_B;
5579 DirectiveKindMap[".dc.d"] = DK_DC_D;
5580 DirectiveKindMap[".dc.l"] = DK_DC_L;
5581 DirectiveKindMap[".dc.s"] = DK_DC_S;
5582 DirectiveKindMap[".dc.w"] = DK_DC_W;
5583 DirectiveKindMap[".dc.x"] = DK_DC_X;
5584 DirectiveKindMap[".dcb"] = DK_DCB;
5585 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5586 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5587 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5588 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5589 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5590 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5591 DirectiveKindMap[".ds"] = DK_DS;
5592 DirectiveKindMap[".ds.b"] = DK_DS_B;
5593 DirectiveKindMap[".ds.d"] = DK_DS_D;
5594 DirectiveKindMap[".ds.l"] = DK_DS_L;
5595 DirectiveKindMap[".ds.p"] = DK_DS_P;
5596 DirectiveKindMap[".ds.s"] = DK_DS_S;
5597 DirectiveKindMap[".ds.w"] = DK_DS_W;
5598 DirectiveKindMap[".ds.x"] = DK_DS_X;
5599 DirectiveKindMap[".print"] = DK_PRINT;
5600 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5601 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
5602 DirectiveKindMap[".pseudoprobe"] = DK_PSEUDO_PROBE;
5603 DirectiveKindMap[".lto_discard"] = DK_LTO_DISCARD;
5604 DirectiveKindMap[".lto_set_conditional"] = DK_LTO_SET_CONDITIONAL;
5605 DirectiveKindMap[".memtag"] = DK_MEMTAG;
5608 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5609 AsmToken EndToken, StartToken = getTok();
5611 unsigned NestLevel = 0;
5612 while (true) {
5613 // Check whether we have reached the end of the file.
5614 if (getLexer().is(AsmToken::Eof)) {
5615 printError(DirectiveLoc, "no matching '.endr' in definition");
5616 return nullptr;
5619 if (Lexer.is(AsmToken::Identifier) &&
5620 (getTok().getIdentifier() == ".rep" ||
5621 getTok().getIdentifier() == ".rept" ||
5622 getTok().getIdentifier() == ".irp" ||
5623 getTok().getIdentifier() == ".irpc")) {
5624 ++NestLevel;
5627 // Otherwise, check whether we have reached the .endr.
5628 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5629 if (NestLevel == 0) {
5630 EndToken = getTok();
5631 Lex();
5632 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5633 printError(getTok().getLoc(),
5634 "unexpected token in '.endr' directive");
5635 return nullptr;
5637 break;
5639 --NestLevel;
5642 // Otherwise, scan till the end of the statement.
5643 eatToEndOfStatement();
5646 const char *BodyStart = StartToken.getLoc().getPointer();
5647 const char *BodyEnd = EndToken.getLoc().getPointer();
5648 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5650 // We Are Anonymous.
5651 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5652 return &MacroLikeBodies.back();
5655 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5656 raw_svector_ostream &OS) {
5657 OS << ".endr\n";
5659 std::unique_ptr<MemoryBuffer> Instantiation =
5660 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5662 // Create the macro instantiation object and add to the current macro
5663 // instantiation stack.
5664 MacroInstantiation *MI = new MacroInstantiation{
5665 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
5666 ActiveMacros.push_back(MI);
5668 // Jump to the macro instantiation and prime the lexer.
5669 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5670 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5671 Lex();
5674 /// parseDirectiveRept
5675 /// ::= .rep | .rept count
5676 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5677 const MCExpr *CountExpr;
5678 SMLoc CountLoc = getTok().getLoc();
5679 if (parseExpression(CountExpr))
5680 return true;
5682 int64_t Count;
5683 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
5684 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5687 if (check(Count < 0, CountLoc, "Count is negative") || parseEOL())
5688 return true;
5690 // Lex the rept definition.
5691 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5692 if (!M)
5693 return true;
5695 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5696 // to hold the macro body with substitutions.
5697 SmallString<256> Buf;
5698 raw_svector_ostream OS(Buf);
5699 while (Count--) {
5700 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5701 if (expandMacro(OS, M->Body, std::nullopt, std::nullopt, false,
5702 getTok().getLoc()))
5703 return true;
5705 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5707 return false;
5710 /// parseDirectiveIrp
5711 /// ::= .irp symbol,values
5712 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5713 MCAsmMacroParameter Parameter;
5714 MCAsmMacroArguments A;
5715 if (check(parseIdentifier(Parameter.Name),
5716 "expected identifier in '.irp' directive") ||
5717 parseComma() || parseMacroArguments(nullptr, A) || parseEOL())
5718 return true;
5720 // Lex the irp definition.
5721 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5722 if (!M)
5723 return true;
5725 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5726 // to hold the macro body with substitutions.
5727 SmallString<256> Buf;
5728 raw_svector_ostream OS(Buf);
5730 for (const MCAsmMacroArgument &Arg : A) {
5731 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5732 // This is undocumented, but GAS seems to support it.
5733 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5734 return true;
5737 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5739 return false;
5742 /// parseDirectiveIrpc
5743 /// ::= .irpc symbol,values
5744 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5745 MCAsmMacroParameter Parameter;
5746 MCAsmMacroArguments A;
5748 if (check(parseIdentifier(Parameter.Name),
5749 "expected identifier in '.irpc' directive") ||
5750 parseComma() || parseMacroArguments(nullptr, A))
5751 return true;
5753 if (A.size() != 1 || A.front().size() != 1)
5754 return TokError("unexpected token in '.irpc' directive");
5755 if (parseEOL())
5756 return true;
5758 // Lex the irpc definition.
5759 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5760 if (!M)
5761 return true;
5763 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5764 // to hold the macro body with substitutions.
5765 SmallString<256> Buf;
5766 raw_svector_ostream OS(Buf);
5768 StringRef Values = A.front().front().getString();
5769 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5770 MCAsmMacroArgument Arg;
5771 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5773 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5774 // This is undocumented, but GAS seems to support it.
5775 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5776 return true;
5779 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5781 return false;
5784 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5785 if (ActiveMacros.empty())
5786 return TokError("unmatched '.endr' directive");
5788 // The only .repl that should get here are the ones created by
5789 // instantiateMacroLikeBody.
5790 assert(getLexer().is(AsmToken::EndOfStatement));
5792 handleMacroExit();
5793 return false;
5796 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5797 size_t Len) {
5798 const MCExpr *Value;
5799 SMLoc ExprLoc = getLexer().getLoc();
5800 if (parseExpression(Value))
5801 return true;
5802 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5803 if (!MCE)
5804 return Error(ExprLoc, "unexpected expression in _emit");
5805 uint64_t IntValue = MCE->getValue();
5806 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5807 return Error(ExprLoc, "literal value out of range for directive");
5809 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5810 return false;
5813 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5814 const MCExpr *Value;
5815 SMLoc ExprLoc = getLexer().getLoc();
5816 if (parseExpression(Value))
5817 return true;
5818 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5819 if (!MCE)
5820 return Error(ExprLoc, "unexpected expression in align");
5821 uint64_t IntValue = MCE->getValue();
5822 if (!isPowerOf2_64(IntValue))
5823 return Error(ExprLoc, "literal value not a power of two greater then zero");
5825 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5826 return false;
5829 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5830 const AsmToken StrTok = getTok();
5831 Lex();
5832 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5833 return Error(DirectiveLoc, "expected double quoted string after .print");
5834 if (parseEOL())
5835 return true;
5836 llvm::outs() << StrTok.getStringContents() << '\n';
5837 return false;
5840 bool AsmParser::parseDirectiveAddrsig() {
5841 if (parseEOL())
5842 return true;
5843 getStreamer().emitAddrsig();
5844 return false;
5847 bool AsmParser::parseDirectiveAddrsigSym() {
5848 StringRef Name;
5849 if (check(parseIdentifier(Name), "expected identifier") || parseEOL())
5850 return true;
5851 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5852 getStreamer().emitAddrsigSym(Sym);
5853 return false;
5856 bool AsmParser::parseDirectivePseudoProbe() {
5857 int64_t Guid;
5858 int64_t Index;
5859 int64_t Type;
5860 int64_t Attr;
5861 int64_t Discriminator = 0;
5863 if (parseIntToken(Guid, "unexpected token in '.pseudoprobe' directive"))
5864 return true;
5866 if (parseIntToken(Index, "unexpected token in '.pseudoprobe' directive"))
5867 return true;
5869 if (parseIntToken(Type, "unexpected token in '.pseudoprobe' directive"))
5870 return true;
5872 if (parseIntToken(Attr, "unexpected token in '.pseudoprobe' directive"))
5873 return true;
5875 if (hasDiscriminator(Attr)) {
5876 if (parseIntToken(Discriminator,
5877 "unexpected token in '.pseudoprobe' directive"))
5878 return true;
5881 // Parse inline stack like @ GUID:11:12 @ GUID:1:11 @ GUID:3:21
5882 MCPseudoProbeInlineStack InlineStack;
5884 while (getLexer().is(AsmToken::At)) {
5885 // eat @
5886 Lex();
5888 int64_t CallerGuid = 0;
5889 if (getLexer().is(AsmToken::Integer)) {
5890 if (parseIntToken(CallerGuid,
5891 "unexpected token in '.pseudoprobe' directive"))
5892 return true;
5895 // eat colon
5896 if (getLexer().is(AsmToken::Colon))
5897 Lex();
5899 int64_t CallerProbeId = 0;
5900 if (getLexer().is(AsmToken::Integer)) {
5901 if (parseIntToken(CallerProbeId,
5902 "unexpected token in '.pseudoprobe' directive"))
5903 return true;
5906 InlineSite Site(CallerGuid, CallerProbeId);
5907 InlineStack.push_back(Site);
5910 // Parse function entry name
5911 StringRef FnName;
5912 if (parseIdentifier(FnName))
5913 return Error(getLexer().getLoc(), "unexpected token in '.pseudoprobe' directive");
5914 MCSymbol *FnSym = getContext().lookupSymbol(FnName);
5916 if (parseEOL())
5917 return true;
5919 getStreamer().emitPseudoProbe(Guid, Index, Type, Attr, Discriminator,
5920 InlineStack, FnSym);
5921 return false;
5924 /// parseDirectiveLTODiscard
5925 /// ::= ".lto_discard" [ identifier ( , identifier )* ]
5926 /// The LTO library emits this directive to discard non-prevailing symbols.
5927 /// We ignore symbol assignments and attribute changes for the specified
5928 /// symbols.
5929 bool AsmParser::parseDirectiveLTODiscard() {
5930 auto ParseOp = [&]() -> bool {
5931 StringRef Name;
5932 SMLoc Loc = getTok().getLoc();
5933 if (parseIdentifier(Name))
5934 return Error(Loc, "expected identifier");
5935 LTODiscardSymbols.insert(Name);
5936 return false;
5939 LTODiscardSymbols.clear();
5940 return parseMany(ParseOp);
5943 // We are comparing pointers, but the pointers are relative to a single string.
5944 // Thus, this should always be deterministic.
5945 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5946 const AsmRewrite *AsmRewriteB) {
5947 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5948 return -1;
5949 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5950 return 1;
5952 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5953 // rewrite to the same location. Make sure the SizeDirective rewrite is
5954 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5955 // ensures the sort algorithm is stable.
5956 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5957 AsmRewritePrecedence[AsmRewriteB->Kind])
5958 return -1;
5960 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5961 AsmRewritePrecedence[AsmRewriteB->Kind])
5962 return 1;
5963 llvm_unreachable("Unstable rewrite sort.");
5966 bool AsmParser::parseMSInlineAsm(
5967 std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
5968 SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5969 SmallVectorImpl<std::string> &Constraints,
5970 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5971 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5972 SmallVector<void *, 4> InputDecls;
5973 SmallVector<void *, 4> OutputDecls;
5974 SmallVector<bool, 4> InputDeclsAddressOf;
5975 SmallVector<bool, 4> OutputDeclsAddressOf;
5976 SmallVector<std::string, 4> InputConstraints;
5977 SmallVector<std::string, 4> OutputConstraints;
5978 SmallVector<unsigned, 4> ClobberRegs;
5980 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5982 // Prime the lexer.
5983 Lex();
5985 // While we have input, parse each statement.
5986 unsigned InputIdx = 0;
5987 unsigned OutputIdx = 0;
5988 while (getLexer().isNot(AsmToken::Eof)) {
5989 // Parse curly braces marking block start/end
5990 if (parseCurlyBlockScope(AsmStrRewrites))
5991 continue;
5993 ParseStatementInfo Info(&AsmStrRewrites);
5994 bool StatementErr = parseStatement(Info, &SI);
5996 if (StatementErr || Info.ParseError) {
5997 // Emit pending errors if any exist.
5998 printPendingErrors();
5999 return true;
6002 // No pending error should exist here.
6003 assert(!hasPendingError() && "unexpected error from parseStatement");
6005 if (Info.Opcode == ~0U)
6006 continue;
6008 const MCInstrDesc &Desc = MII->get(Info.Opcode);
6010 // Build the list of clobbers, outputs and inputs.
6011 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
6012 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
6014 // Register operand.
6015 if (Operand.isReg() && !Operand.needAddressOf() &&
6016 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
6017 unsigned NumDefs = Desc.getNumDefs();
6018 // Clobber.
6019 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
6020 ClobberRegs.push_back(Operand.getReg());
6021 continue;
6024 // Expr/Input or Output.
6025 StringRef SymName = Operand.getSymName();
6026 if (SymName.empty())
6027 continue;
6029 void *OpDecl = Operand.getOpDecl();
6030 if (!OpDecl)
6031 continue;
6033 StringRef Constraint = Operand.getConstraint();
6034 if (Operand.isImm()) {
6035 // Offset as immediate
6036 if (Operand.isOffsetOfLocal())
6037 Constraint = "r";
6038 else
6039 Constraint = "i";
6042 bool isOutput = (i == 1) && Desc.mayStore();
6043 bool Restricted = Operand.isMemUseUpRegs();
6044 SMLoc Start = SMLoc::getFromPointer(SymName.data());
6045 if (isOutput) {
6046 ++InputIdx;
6047 OutputDecls.push_back(OpDecl);
6048 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
6049 OutputConstraints.push_back(("=" + Constraint).str());
6050 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size(), 0,
6051 Restricted);
6052 } else {
6053 InputDecls.push_back(OpDecl);
6054 InputDeclsAddressOf.push_back(Operand.needAddressOf());
6055 InputConstraints.push_back(Constraint.str());
6056 if (Desc.operands()[i - 1].isBranchTarget())
6057 AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size(), 0,
6058 Restricted);
6059 else
6060 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size(), 0,
6061 Restricted);
6065 // Consider implicit defs to be clobbers. Think of cpuid and push.
6066 llvm::append_range(ClobberRegs, Desc.implicit_defs());
6069 // Set the number of Outputs and Inputs.
6070 NumOutputs = OutputDecls.size();
6071 NumInputs = InputDecls.size();
6073 // Set the unique clobbers.
6074 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
6075 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
6076 ClobberRegs.end());
6077 Clobbers.assign(ClobberRegs.size(), std::string());
6078 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
6079 raw_string_ostream OS(Clobbers[I]);
6080 IP->printRegName(OS, ClobberRegs[I]);
6083 // Merge the various outputs and inputs. Output are expected first.
6084 if (NumOutputs || NumInputs) {
6085 unsigned NumExprs = NumOutputs + NumInputs;
6086 OpDecls.resize(NumExprs);
6087 Constraints.resize(NumExprs);
6088 for (unsigned i = 0; i < NumOutputs; ++i) {
6089 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
6090 Constraints[i] = OutputConstraints[i];
6092 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
6093 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
6094 Constraints[j] = InputConstraints[i];
6098 // Build the IR assembly string.
6099 std::string AsmStringIR;
6100 raw_string_ostream OS(AsmStringIR);
6101 StringRef ASMString =
6102 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
6103 const char *AsmStart = ASMString.begin();
6104 const char *AsmEnd = ASMString.end();
6105 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
6106 for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) {
6107 const AsmRewrite &AR = *it;
6108 // Check if this has already been covered by another rewrite...
6109 if (AR.Done)
6110 continue;
6111 AsmRewriteKind Kind = AR.Kind;
6113 const char *Loc = AR.Loc.getPointer();
6114 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
6116 // Emit everything up to the immediate/expression.
6117 if (unsigned Len = Loc - AsmStart)
6118 OS << StringRef(AsmStart, Len);
6120 // Skip the original expression.
6121 if (Kind == AOK_Skip) {
6122 AsmStart = Loc + AR.Len;
6123 continue;
6126 unsigned AdditionalSkip = 0;
6127 // Rewrite expressions in $N notation.
6128 switch (Kind) {
6129 default:
6130 break;
6131 case AOK_IntelExpr:
6132 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
6133 if (AR.IntelExp.NeedBracs)
6134 OS << "[";
6135 if (AR.IntelExp.hasBaseReg())
6136 OS << AR.IntelExp.BaseReg;
6137 if (AR.IntelExp.hasIndexReg())
6138 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
6139 << AR.IntelExp.IndexReg;
6140 if (AR.IntelExp.Scale > 1)
6141 OS << " * $$" << AR.IntelExp.Scale;
6142 if (AR.IntelExp.hasOffset()) {
6143 if (AR.IntelExp.hasRegs())
6144 OS << " + ";
6145 // Fuse this rewrite with a rewrite of the offset name, if present.
6146 StringRef OffsetName = AR.IntelExp.OffsetName;
6147 SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data());
6148 size_t OffsetLen = OffsetName.size();
6149 auto rewrite_it = std::find_if(
6150 it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) {
6151 return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen &&
6152 (FusingAR.Kind == AOK_Input ||
6153 FusingAR.Kind == AOK_CallInput);
6155 if (rewrite_it == AsmStrRewrites.end()) {
6156 OS << "offset " << OffsetName;
6157 } else if (rewrite_it->Kind == AOK_CallInput) {
6158 OS << "${" << InputIdx++ << ":P}";
6159 rewrite_it->Done = true;
6160 } else {
6161 OS << '$' << InputIdx++;
6162 rewrite_it->Done = true;
6165 if (AR.IntelExp.Imm || AR.IntelExp.emitImm())
6166 OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm;
6167 if (AR.IntelExp.NeedBracs)
6168 OS << "]";
6169 break;
6170 case AOK_Label:
6171 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
6172 break;
6173 case AOK_Input:
6174 if (AR.IntelExpRestricted)
6175 OS << "${" << InputIdx++ << ":P}";
6176 else
6177 OS << '$' << InputIdx++;
6178 break;
6179 case AOK_CallInput:
6180 OS << "${" << InputIdx++ << ":P}";
6181 break;
6182 case AOK_Output:
6183 if (AR.IntelExpRestricted)
6184 OS << "${" << OutputIdx++ << ":P}";
6185 else
6186 OS << '$' << OutputIdx++;
6187 break;
6188 case AOK_SizeDirective:
6189 switch (AR.Val) {
6190 default: break;
6191 case 8: OS << "byte ptr "; break;
6192 case 16: OS << "word ptr "; break;
6193 case 32: OS << "dword ptr "; break;
6194 case 64: OS << "qword ptr "; break;
6195 case 80: OS << "xword ptr "; break;
6196 case 128: OS << "xmmword ptr "; break;
6197 case 256: OS << "ymmword ptr "; break;
6199 break;
6200 case AOK_Emit:
6201 OS << ".byte";
6202 break;
6203 case AOK_Align: {
6204 // MS alignment directives are measured in bytes. If the native assembler
6205 // measures alignment in bytes, we can pass it straight through.
6206 OS << ".align";
6207 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
6208 break;
6210 // Alignment is in log2 form, so print that instead and skip the original
6211 // immediate.
6212 unsigned Val = AR.Val;
6213 OS << ' ' << Val;
6214 assert(Val < 10 && "Expected alignment less then 2^10.");
6215 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
6216 break;
6218 case AOK_EVEN:
6219 OS << ".even";
6220 break;
6221 case AOK_EndOfStatement:
6222 OS << "\n\t";
6223 break;
6226 // Skip the original expression.
6227 AsmStart = Loc + AR.Len + AdditionalSkip;
6230 // Emit the remainder of the asm string.
6231 if (AsmStart != AsmEnd)
6232 OS << StringRef(AsmStart, AsmEnd - AsmStart);
6234 AsmString = OS.str();
6235 return false;
6238 bool HLASMAsmParser::parseAsHLASMLabel(ParseStatementInfo &Info,
6239 MCAsmParserSemaCallback *SI) {
6240 AsmToken LabelTok = getTok();
6241 SMLoc LabelLoc = LabelTok.getLoc();
6242 StringRef LabelVal;
6244 if (parseIdentifier(LabelVal))
6245 return Error(LabelLoc, "The HLASM Label has to be an Identifier");
6247 // We have validated whether the token is an Identifier.
6248 // Now we have to validate whether the token is a
6249 // valid HLASM Label.
6250 if (!getTargetParser().isLabel(LabelTok) || checkForValidSection())
6251 return true;
6253 // Lex leading spaces to get to the next operand.
6254 lexLeadingSpaces();
6256 // We shouldn't emit the label if there is nothing else after the label.
6257 // i.e asm("<token>\n")
6258 if (getTok().is(AsmToken::EndOfStatement))
6259 return Error(LabelLoc,
6260 "Cannot have just a label for an HLASM inline asm statement");
6262 MCSymbol *Sym = getContext().getOrCreateSymbol(
6263 getContext().getAsmInfo()->shouldEmitLabelsInUpperCase()
6264 ? LabelVal.upper()
6265 : LabelVal);
6267 getTargetParser().doBeforeLabelEmit(Sym, LabelLoc);
6269 // Emit the label.
6270 Out.emitLabel(Sym, LabelLoc);
6272 // If we are generating dwarf for assembly source files then gather the
6273 // info to make a dwarf label entry for this label if needed.
6274 if (enabledGenDwarfForAssembly())
6275 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
6276 LabelLoc);
6278 getTargetParser().onLabelParsed(Sym);
6280 return false;
6283 bool HLASMAsmParser::parseAsMachineInstruction(ParseStatementInfo &Info,
6284 MCAsmParserSemaCallback *SI) {
6285 AsmToken OperationEntryTok = Lexer.getTok();
6286 SMLoc OperationEntryLoc = OperationEntryTok.getLoc();
6287 StringRef OperationEntryVal;
6289 // Attempt to parse the first token as an Identifier
6290 if (parseIdentifier(OperationEntryVal))
6291 return Error(OperationEntryLoc, "unexpected token at start of statement");
6293 // Once we've parsed the operation entry successfully, lex
6294 // any spaces to get to the OperandEntries.
6295 lexLeadingSpaces();
6297 return parseAndMatchAndEmitTargetInstruction(
6298 Info, OperationEntryVal, OperationEntryTok, OperationEntryLoc);
6301 bool HLASMAsmParser::parseStatement(ParseStatementInfo &Info,
6302 MCAsmParserSemaCallback *SI) {
6303 assert(!hasPendingError() && "parseStatement started with pending error");
6305 // Should the first token be interpreted as a HLASM Label.
6306 bool ShouldParseAsHLASMLabel = false;
6308 // If a Name Entry exists, it should occur at the very
6309 // start of the string. In this case, we should parse the
6310 // first non-space token as a Label.
6311 // If the Name entry is missing (i.e. there's some other
6312 // token), then we attempt to parse the first non-space
6313 // token as a Machine Instruction.
6314 if (getTok().isNot(AsmToken::Space))
6315 ShouldParseAsHLASMLabel = true;
6317 // If we have an EndOfStatement (which includes the target's comment
6318 // string) we can appropriately lex it early on)
6319 if (Lexer.is(AsmToken::EndOfStatement)) {
6320 // if this is a line comment we can drop it safely
6321 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
6322 getTok().getString().front() == '\n')
6323 Out.addBlankLine();
6324 Lex();
6325 return false;
6328 // We have established how to parse the inline asm statement.
6329 // Now we can safely lex any leading spaces to get to the
6330 // first token.
6331 lexLeadingSpaces();
6333 // If we see a new line or carriage return as the first operand,
6334 // after lexing leading spaces, emit the new line and lex the
6335 // EndOfStatement token.
6336 if (Lexer.is(AsmToken::EndOfStatement)) {
6337 if (getTok().getString().front() == '\n' ||
6338 getTok().getString().front() == '\r') {
6339 Out.addBlankLine();
6340 Lex();
6341 return false;
6345 // Handle the label first if we have to before processing the rest
6346 // of the tokens as a machine instruction.
6347 if (ShouldParseAsHLASMLabel) {
6348 // If there were any errors while handling and emitting the label,
6349 // early return.
6350 if (parseAsHLASMLabel(Info, SI)) {
6351 // If we know we've failed in parsing, simply eat until end of the
6352 // statement. This ensures that we don't process any other statements.
6353 eatToEndOfStatement();
6354 return true;
6358 return parseAsMachineInstruction(Info, SI);
6361 namespace llvm {
6362 namespace MCParserUtils {
6364 /// Returns whether the given symbol is used anywhere in the given expression,
6365 /// or subexpressions.
6366 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
6367 switch (Value->getKind()) {
6368 case MCExpr::Binary: {
6369 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
6370 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
6371 isSymbolUsedInExpression(Sym, BE->getRHS());
6373 case MCExpr::Target:
6374 case MCExpr::Constant:
6375 return false;
6376 case MCExpr::SymbolRef: {
6377 const MCSymbol &S =
6378 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
6379 if (S.isVariable() && !S.isWeakExternal())
6380 return isSymbolUsedInExpression(Sym, S.getVariableValue());
6381 return &S == Sym;
6383 case MCExpr::Unary:
6384 return isSymbolUsedInExpression(
6385 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
6388 llvm_unreachable("Unknown expr kind!");
6391 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
6392 MCAsmParser &Parser, MCSymbol *&Sym,
6393 const MCExpr *&Value) {
6395 // FIXME: Use better location, we should use proper tokens.
6396 SMLoc EqualLoc = Parser.getTok().getLoc();
6397 if (Parser.parseExpression(Value))
6398 return Parser.TokError("missing expression");
6400 // Note: we don't count b as used in "a = b". This is to allow
6401 // a = b
6402 // b = c
6404 if (Parser.parseEOL())
6405 return true;
6407 // Validate that the LHS is allowed to be a variable (either it has not been
6408 // used as a symbol, or it is an absolute symbol).
6409 Sym = Parser.getContext().lookupSymbol(Name);
6410 if (Sym) {
6411 // Diagnose assignment to a label.
6413 // FIXME: Diagnostics. Note the location of the definition as a label.
6414 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6415 if (isSymbolUsedInExpression(Sym, Value))
6416 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
6417 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
6418 !Sym->isVariable())
6419 ; // Allow redefinitions of undefined symbols only used in directives.
6420 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
6421 ; // Allow redefinitions of variables that haven't yet been used.
6422 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
6423 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
6424 else if (!Sym->isVariable())
6425 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
6426 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
6427 return Parser.Error(EqualLoc,
6428 "invalid reassignment of non-absolute variable '" +
6429 Name + "'");
6430 } else if (Name == ".") {
6431 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
6432 return false;
6433 } else
6434 Sym = Parser.getContext().getOrCreateSymbol(Name);
6436 Sym->setRedefinable(allow_redef);
6438 return false;
6441 } // end namespace MCParserUtils
6442 } // end namespace llvm
6444 /// Create an MCAsmParser instance.
6445 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
6446 MCStreamer &Out, const MCAsmInfo &MAI,
6447 unsigned CB) {
6448 if (C.getTargetTriple().isSystemZ() && C.getTargetTriple().isOSzOS())
6449 return new HLASMAsmParser(SM, C, Out, MAI, CB);
6451 return new AsmParser(SM, C, Out, MAI, CB);