1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/AsmCond.h"
26 #include "llvm/MC/MCParser/AsmLexer.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCTargetAsmParser.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
47 FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
63 MCAsmMacroParameters Parameters;
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
73 /// \brief Helper class for storing information about an active macro
75 struct MacroInstantiation {
76 /// The macro being instantiated.
77 const MCAsmMacro *TheMacro;
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
85 /// The buffer where parsing should resume upon instantiation completion.
88 /// The location where parsing should resume upon instantiation completion.
92 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
96 struct ParseStatementInfo {
97 /// \brief The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
100 /// \brief The opcode from the last parsed instruction.
103 /// \brief Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// \brief maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// \brief Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// \brief Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// \brief List of bodies of anonymous macros.
153 std::deque<MCAsmMacro> MacroLikeBodies;
155 /// Boolean tracking whether macro substitution is enabled.
156 unsigned MacrosEnabledFlag : 1;
158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
168 /// and current line. Since this is slow and messes up the SourceMgr's
169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
172 unsigned LastQueryLine;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
177 /// \brief is Darwin compatibility enabled?
180 /// \brief Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm;
184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
185 const MCAsmInfo &MAI);
186 virtual ~AsmParser();
188 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
190 virtual void addDirectiveHandler(StringRef Directive,
191 ExtensionDirectiveHandler Handler) {
192 ExtensionDirectiveMap[Directive] = Handler;
196 /// @name MCAsmParser Interface
199 virtual SourceMgr &getSourceManager() { return SrcMgr; }
200 virtual MCAsmLexer &getLexer() { return Lexer; }
201 virtual MCContext &getContext() { return Ctx; }
202 virtual MCStreamer &getStreamer() { return Out; }
203 virtual unsigned getAssemblerDialect() {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 virtual void setAssemblerDialect(unsigned i) {
210 AssemblerDialect = i;
213 virtual bool Warning(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None);
215 virtual bool Error(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
218 virtual const AsmToken &Lex();
220 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
221 bool isParsingInlineAsm() { return ParsingInlineAsm; }
223 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
224 unsigned &NumOutputs, unsigned &NumInputs,
225 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
226 SmallVectorImpl<std::string> &Constraints,
227 SmallVectorImpl<std::string> &Clobbers,
228 const MCInstrInfo *MII,
229 const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI);
232 bool parseExpression(const MCExpr *&Res);
233 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
234 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseAbsoluteExpression(int64_t &Res);
238 /// \brief Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 virtual bool parseIdentifier(StringRef &Res);
241 virtual void eatToEndOfStatement();
243 virtual void checkForValidSection();
248 bool parseStatement(ParseStatementInfo &Info);
249 void eatToEndOfLine();
250 bool parseCppHashLineFilenameComment(const SMLoc &L);
252 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
253 MCAsmMacroParameters Parameters);
254 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
255 const MCAsmMacroParameters &Parameters,
256 const MCAsmMacroArguments &A,
259 /// \brief Are macros enabled in the parser?
260 bool areMacrosEnabled() {return MacrosEnabledFlag;}
262 /// \brief Control a flag in the parser that enables or disables macros.
263 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
265 /// \brief Lookup a previously defined macro.
266 /// \param Name Macro name.
267 /// \returns Pointer to macro. NULL if no such macro was defined.
268 const MCAsmMacro* lookupMacro(StringRef Name);
270 /// \brief Define a new macro with the given name and information.
271 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
273 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
274 void undefineMacro(StringRef Name);
276 /// \brief Are we inside a macro instantiation?
277 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
279 /// \brief Handle entry to macro instantiation.
281 /// \param M The macro.
282 /// \param NameLoc Instantiation location.
283 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
285 /// \brief Handle exit from macro instantiation.
286 void handleMacroExit();
288 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
289 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
290 /// correct delimiter by the method.
291 bool parseMacroArgument(MCAsmMacroArgument &MA,
292 AsmToken::TokenKind &ArgumentDelimiter);
294 /// \brief Parse all macro arguments for a given macro.
295 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
297 void printMacroInstantiations();
298 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
299 ArrayRef<SMRange> Ranges = None) const {
300 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
302 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
304 /// \brief Enter the specified file. This returns true on failure.
305 bool enterIncludeFile(const std::string &Filename);
307 /// \brief Process the specified file for the .incbin directive.
308 /// This returns true on failure.
309 bool processIncbinFile(const std::string &Filename);
311 /// \brief Reset the current lexer position to that given by \p Loc. The
312 /// current token is not set; clients should ensure Lex() is called
315 /// \param InBuffer If not -1, should be the known buffer id that contains the
317 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
319 /// \brief Parse up to the end of statement and a return the contents from the
320 /// current token until the end of the statement; the current token on exit
321 /// will be either the EndOfStatement or EOF.
322 virtual StringRef parseStringToEndOfStatement();
324 /// \brief Parse until the end of a statement or a comma is encountered,
325 /// return the contents from the current token up to the end or comma.
326 StringRef parseStringToComma();
328 bool parseAssignment(StringRef Name, bool allow_redef,
329 bool NoDeadStrip = false);
331 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
337 // Generic (target and platform independent) directive parsing.
339 DK_NO_DIRECTIVE, // Placeholder
340 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
341 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
342 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
343 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
344 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
345 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
346 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
347 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
348 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
349 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
350 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
351 DK_ELSEIF, DK_ELSE, DK_ENDIF,
352 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
353 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
354 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
355 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
356 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
357 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
359 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128
363 /// \brief Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
367 // ".ascii", ".asciz", ".string"
368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
371 bool parseDirectiveFill(); // ".fill"
372 bool parseDirectiveZero(); // ".zero"
373 // ".set", ".equ", ".equiv"
374 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
375 bool parseDirectiveOrg(); // ".org"
376 // ".align{,32}", ".p2align{,w,l}"
377 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
379 // ".file", ".line", ".loc", ".stabs"
380 bool parseDirectiveFile(SMLoc DirectiveLoc);
381 bool parseDirectiveLine();
382 bool parseDirectiveLoc();
383 bool parseDirectiveStabs();
386 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
387 bool parseDirectiveCFISections();
388 bool parseDirectiveCFIStartProc();
389 bool parseDirectiveCFIEndProc();
390 bool parseDirectiveCFIDefCfaOffset();
391 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIAdjustCfaOffset();
393 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
397 bool parseDirectiveCFIRememberState();
398 bool parseDirectiveCFIRestoreState();
399 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIEscape();
402 bool parseDirectiveCFISignalFrame();
403 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
406 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
407 bool parseDirectiveEndMacro(StringRef Directive);
408 bool parseDirectiveMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveMacrosOnOff(StringRef Directive);
411 // ".bundle_align_mode"
412 bool parseDirectiveBundleAlignMode();
414 bool parseDirectiveBundleLock();
416 bool parseDirectiveBundleUnlock();
419 bool parseDirectiveSpace(StringRef IDVal);
421 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
422 bool parseDirectiveLEB128(bool Signed);
424 /// \brief Parse a directive like ".globl" which
425 /// accepts a single symbol (which should be a label or an external).
426 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
428 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
430 bool parseDirectiveAbort(); // ".abort"
431 bool parseDirectiveInclude(); // ".include"
432 bool parseDirectiveIncbin(); // ".incbin"
434 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
435 // ".ifb" or ".ifnb", depending on ExpectBlank.
436 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
437 // ".ifc" or ".ifnc", depending on ExpectEqual.
438 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
439 // ".ifdef" or ".ifndef", depending on expect_defined
440 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
441 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
442 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
443 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
444 virtual bool parseEscapedString(std::string &Data);
446 const MCExpr *applyModifierToExpr(const MCExpr *E,
447 MCSymbolRefExpr::VariantKind Variant);
449 // Macro-like directives
450 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
451 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
452 raw_svector_ostream &OS);
453 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
454 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
455 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
456 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
458 // "_emit" or "__emit"
459 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
463 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
465 void initializeDirectiveKindMap();
471 extern MCAsmParserExtension *createDarwinAsmParser();
472 extern MCAsmParserExtension *createELFAsmParser();
473 extern MCAsmParserExtension *createCOFFAsmParser();
477 enum { DEFAULT_ADDRSPACE = 0 };
479 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
480 const MCAsmInfo &_MAI)
481 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
482 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
483 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
484 ParsingInlineAsm(false) {
485 // Save the old handler.
486 SavedDiagHandler = SrcMgr.getDiagHandler();
487 SavedDiagContext = SrcMgr.getDiagContext();
488 // Set our own handler which calls the saved handler.
489 SrcMgr.setDiagHandler(DiagHandler, this);
490 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
492 // Initialize the platform / file format parser.
494 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
496 if (_MAI.hasMicrosoftFastStdCallMangling()) {
497 PlatformParser = createCOFFAsmParser();
498 PlatformParser->Initialize(*this);
499 } else if (_MAI.hasSubsectionsViaSymbols()) {
500 PlatformParser = createDarwinAsmParser();
501 PlatformParser->Initialize(*this);
504 PlatformParser = createELFAsmParser();
505 PlatformParser->Initialize(*this);
508 initializeDirectiveKindMap();
511 AsmParser::~AsmParser() {
512 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
514 // Destroy any macros.
515 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
518 delete it->getValue();
520 delete PlatformParser;
523 void AsmParser::printMacroInstantiations() {
524 // Print the active macro instantiation stack.
525 for (std::vector<MacroInstantiation *>::const_reverse_iterator
526 it = ActiveMacros.rbegin(),
527 ie = ActiveMacros.rend();
529 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
530 "while in macro instantiation");
533 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
534 if (FatalAssemblerWarnings)
535 return Error(L, Msg, Ranges);
536 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
537 printMacroInstantiations();
541 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
543 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
544 printMacroInstantiations();
548 bool AsmParser::enterIncludeFile(const std::string &Filename) {
549 std::string IncludedFile;
550 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
556 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
561 /// Process the specified .incbin file by searching for it in the include paths
562 /// then just emitting the byte contents of the file to the streamer. This
563 /// returns true on failure.
564 bool AsmParser::processIncbinFile(const std::string &Filename) {
565 std::string IncludedFile;
566 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
570 // Pick up the bytes from the file and emit them.
571 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
575 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
576 if (InBuffer != -1) {
577 CurBuffer = InBuffer;
579 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
581 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
584 const AsmToken &AsmParser::Lex() {
585 const AsmToken *tok = &Lexer.Lex();
587 if (tok->is(AsmToken::Eof)) {
588 // If this is the end of an included file, pop the parent file off the
590 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
591 if (ParentIncludeLoc != SMLoc()) {
592 jumpToLoc(ParentIncludeLoc);
597 if (tok->is(AsmToken::Error))
598 Error(Lexer.getErrLoc(), Lexer.getErr());
603 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
604 // Create the initial section, if requested.
605 if (!NoInitialTextSection)
612 AsmCond StartingCondState = TheCondState;
614 // If we are generating dwarf for assembly source files save the initial text
615 // section and generate a .file directive.
616 if (getContext().getGenDwarfForAssembly()) {
617 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
618 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
619 getStreamer().EmitLabel(SectionStartSym);
620 getContext().setGenDwarfSectionStartSym(SectionStartSym);
621 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
623 getContext().getMainFileName());
626 // While we have input, parse each statement.
627 while (Lexer.isNot(AsmToken::Eof)) {
628 ParseStatementInfo Info;
629 if (!parseStatement(Info))
632 // We had an error, validate that one was emitted and recover by skipping to
634 assert(HadError && "Parse statement returned an error, but none emitted!");
635 eatToEndOfStatement();
638 if (TheCondState.TheCond != StartingCondState.TheCond ||
639 TheCondState.Ignore != StartingCondState.Ignore)
640 return TokError("unmatched .ifs or .elses");
642 // Check to see there are no empty DwarfFile slots.
643 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
644 getContext().getMCDwarfFiles();
645 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
646 if (!MCDwarfFiles[i])
647 TokError("unassigned file number: " + Twine(i) + " for .file directives");
650 // Check to see that all assembler local symbols were actually defined.
651 // Targets that don't do subsections via symbols may not want this, though,
652 // so conservatively exclude them. Only do this if we're finalizing, though,
653 // as otherwise we won't necessarilly have seen everything yet.
654 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
655 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
656 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
659 MCSymbol *Sym = i->getValue();
660 // Variable symbols may not be marked as defined, so check those
661 // explicitly. If we know it's a variable, we have a definition for
662 // the purposes of this check.
663 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
664 // FIXME: We would really like to refer back to where the symbol was
665 // first referenced for a source location. We need to add something
666 // to track that. Currently, we just point to the end of the file.
668 getLexer().getLoc(), SourceMgr::DK_Error,
669 "assembler local symbol '" + Sym->getName() + "' not defined");
673 // Finalize the output stream if there are no errors and if the client wants
675 if (!HadError && !NoFinalize)
681 void AsmParser::checkForValidSection() {
682 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
683 TokError("expected section directive before assembly directive");
684 Out.InitToTextSection();
688 /// \brief Throw away the rest of the line for testing purposes.
689 void AsmParser::eatToEndOfStatement() {
690 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
694 if (Lexer.is(AsmToken::EndOfStatement))
698 StringRef AsmParser::parseStringToEndOfStatement() {
699 const char *Start = getTok().getLoc().getPointer();
701 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
704 const char *End = getTok().getLoc().getPointer();
705 return StringRef(Start, End - Start);
708 StringRef AsmParser::parseStringToComma() {
709 const char *Start = getTok().getLoc().getPointer();
711 while (Lexer.isNot(AsmToken::EndOfStatement) &&
712 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
719 /// \brief Parse a paren expression and return it.
720 /// NOTE: This assumes the leading '(' has already been consumed.
722 /// parenexpr ::= expr)
724 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (parseExpression(Res))
727 if (Lexer.isNot(AsmToken::RParen))
728 return TokError("expected ')' in parentheses expression");
729 EndLoc = Lexer.getTok().getEndLoc();
734 /// \brief Parse a bracket expression and return it.
735 /// NOTE: This assumes the leading '[' has already been consumed.
737 /// bracketexpr ::= expr]
739 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
740 if (parseExpression(Res))
742 if (Lexer.isNot(AsmToken::RBrac))
743 return TokError("expected ']' in brackets expression");
744 EndLoc = Lexer.getTok().getEndLoc();
749 /// \brief Parse a primary expression and return it.
750 /// primaryexpr ::= (parenexpr
751 /// primaryexpr ::= symbol
752 /// primaryexpr ::= number
753 /// primaryexpr ::= '.'
754 /// primaryexpr ::= ~,+,- primaryexpr
755 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
756 SMLoc FirstTokenLoc = getLexer().getLoc();
757 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
758 switch (FirstTokenKind) {
760 return TokError("unknown token in expression");
761 // If we have an error assume that we've already handled it.
762 case AsmToken::Error:
764 case AsmToken::Exclaim:
765 Lex(); // Eat the operator.
766 if (parsePrimaryExpr(Res, EndLoc))
768 Res = MCUnaryExpr::CreateLNot(Res, getContext());
770 case AsmToken::Dollar:
771 case AsmToken::String:
772 case AsmToken::Identifier: {
773 StringRef Identifier;
774 if (parseIdentifier(Identifier)) {
775 if (FirstTokenKind == AsmToken::Dollar)
776 return Error(FirstTokenLoc, "invalid token in expression");
780 EndLoc = SMLoc::getFromPointer(Identifier.end());
782 // This is a symbol reference.
783 std::pair<StringRef, StringRef> Split = Identifier.split('@');
784 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
786 // Lookup the symbol variant if used.
787 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
788 if (Split.first.size() != Identifier.size()) {
789 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
790 if (Variant == MCSymbolRefExpr::VK_Invalid) {
791 Variant = MCSymbolRefExpr::VK_None;
792 return TokError("invalid variant '" + Split.second + "'");
796 // If this is an absolute variable reference, substitute it now to preserve
797 // semantics in the face of reassignment.
798 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
800 return Error(EndLoc, "unexpected modifier on variable reference");
802 Res = Sym->getVariableValue();
806 // Otherwise create a symbol ref.
807 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
810 case AsmToken::Integer: {
811 SMLoc Loc = getTok().getLoc();
812 int64_t IntVal = getTok().getIntVal();
813 Res = MCConstantExpr::Create(IntVal, getContext());
814 EndLoc = Lexer.getTok().getEndLoc();
816 // Look for 'b' or 'f' following an Integer as a directional label
817 if (Lexer.getKind() == AsmToken::Identifier) {
818 StringRef IDVal = getTok().getString();
819 // Lookup the symbol variant if used.
820 std::pair<StringRef, StringRef> Split = IDVal.split('@');
821 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
822 if (Split.first.size() != IDVal.size()) {
823 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
824 if (Variant == MCSymbolRefExpr::VK_Invalid) {
825 Variant = MCSymbolRefExpr::VK_None;
826 return TokError("invalid variant '" + Split.second + "'");
830 if (IDVal == "f" || IDVal == "b") {
832 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
833 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
834 if (IDVal == "b" && Sym->isUndefined())
835 return Error(Loc, "invalid reference to undefined symbol");
836 EndLoc = Lexer.getTok().getEndLoc();
837 Lex(); // Eat identifier.
842 case AsmToken::Real: {
843 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
844 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
845 Res = MCConstantExpr::Create(IntVal, getContext());
846 EndLoc = Lexer.getTok().getEndLoc();
850 case AsmToken::Dot: {
851 // This is a '.' reference, which references the current PC. Emit a
852 // temporary label to the streamer and refer to it.
853 MCSymbol *Sym = Ctx.CreateTempSymbol();
855 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
856 EndLoc = Lexer.getTok().getEndLoc();
857 Lex(); // Eat identifier.
860 case AsmToken::LParen:
861 Lex(); // Eat the '('.
862 return parseParenExpr(Res, EndLoc);
863 case AsmToken::LBrac:
864 if (!PlatformParser->HasBracketExpressions())
865 return TokError("brackets expression not supported on this target");
866 Lex(); // Eat the '['.
867 return parseBracketExpr(Res, EndLoc);
868 case AsmToken::Minus:
869 Lex(); // Eat the operator.
870 if (parsePrimaryExpr(Res, EndLoc))
872 Res = MCUnaryExpr::CreateMinus(Res, getContext());
875 Lex(); // Eat the operator.
876 if (parsePrimaryExpr(Res, EndLoc))
878 Res = MCUnaryExpr::CreatePlus(Res, getContext());
880 case AsmToken::Tilde:
881 Lex(); // Eat the operator.
882 if (parsePrimaryExpr(Res, EndLoc))
884 Res = MCUnaryExpr::CreateNot(Res, getContext());
889 bool AsmParser::parseExpression(const MCExpr *&Res) {
891 return parseExpression(Res, EndLoc);
895 AsmParser::applyModifierToExpr(const MCExpr *E,
896 MCSymbolRefExpr::VariantKind Variant) {
897 // Ask the target implementation about this expression first.
898 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
901 // Recurse over the given expression, rebuilding it to apply the given variant
902 // if there is exactly one symbol.
903 switch (E->getKind()) {
905 case MCExpr::Constant:
908 case MCExpr::SymbolRef: {
909 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
911 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
912 TokError("invalid variant on expression '" + getTok().getIdentifier() +
913 "' (already modified)");
917 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
920 case MCExpr::Unary: {
921 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
922 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
925 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
928 case MCExpr::Binary: {
929 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
930 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
931 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
941 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
945 llvm_unreachable("Invalid expression kind!");
948 /// \brief Parse an expression and return it.
950 /// expr ::= expr &&,|| expr -> lowest.
951 /// expr ::= expr |,^,&,! expr
952 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
953 /// expr ::= expr <<,>> expr
954 /// expr ::= expr +,- expr
955 /// expr ::= expr *,/,% expr -> highest.
956 /// expr ::= primaryexpr
958 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
959 // Parse the expression.
961 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
964 // As a special case, we support 'a op b @ modifier' by rewriting the
965 // expression to include the modifier. This is inefficient, but in general we
966 // expect users to use 'a@modifier op b'.
967 if (Lexer.getKind() == AsmToken::At) {
970 if (Lexer.isNot(AsmToken::Identifier))
971 return TokError("unexpected symbol modifier following '@'");
973 MCSymbolRefExpr::VariantKind Variant =
974 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
975 if (Variant == MCSymbolRefExpr::VK_Invalid)
976 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
978 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
980 return TokError("invalid modifier '" + getTok().getIdentifier() +
981 "' (no symbols present)");
988 // Try to constant fold it up front, if possible.
990 if (Res->EvaluateAsAbsolute(Value))
991 Res = MCConstantExpr::Create(Value, getContext());
996 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
998 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1001 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1004 SMLoc StartLoc = Lexer.getLoc();
1005 if (parseExpression(Expr))
1008 if (!Expr->EvaluateAsAbsolute(Res))
1009 return Error(StartLoc, "expected absolute expression");
1014 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1015 MCBinaryExpr::Opcode &Kind) {
1018 return 0; // not a binop.
1020 // Lowest Precedence: &&, ||
1021 case AsmToken::AmpAmp:
1022 Kind = MCBinaryExpr::LAnd;
1024 case AsmToken::PipePipe:
1025 Kind = MCBinaryExpr::LOr;
1028 // Low Precedence: |, &, ^
1030 // FIXME: gas seems to support '!' as an infix operator?
1031 case AsmToken::Pipe:
1032 Kind = MCBinaryExpr::Or;
1034 case AsmToken::Caret:
1035 Kind = MCBinaryExpr::Xor;
1038 Kind = MCBinaryExpr::And;
1041 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1042 case AsmToken::EqualEqual:
1043 Kind = MCBinaryExpr::EQ;
1045 case AsmToken::ExclaimEqual:
1046 case AsmToken::LessGreater:
1047 Kind = MCBinaryExpr::NE;
1049 case AsmToken::Less:
1050 Kind = MCBinaryExpr::LT;
1052 case AsmToken::LessEqual:
1053 Kind = MCBinaryExpr::LTE;
1055 case AsmToken::Greater:
1056 Kind = MCBinaryExpr::GT;
1058 case AsmToken::GreaterEqual:
1059 Kind = MCBinaryExpr::GTE;
1062 // Intermediate Precedence: <<, >>
1063 case AsmToken::LessLess:
1064 Kind = MCBinaryExpr::Shl;
1066 case AsmToken::GreaterGreater:
1067 Kind = MCBinaryExpr::Shr;
1070 // High Intermediate Precedence: +, -
1071 case AsmToken::Plus:
1072 Kind = MCBinaryExpr::Add;
1074 case AsmToken::Minus:
1075 Kind = MCBinaryExpr::Sub;
1078 // Highest Precedence: *, /, %
1079 case AsmToken::Star:
1080 Kind = MCBinaryExpr::Mul;
1082 case AsmToken::Slash:
1083 Kind = MCBinaryExpr::Div;
1085 case AsmToken::Percent:
1086 Kind = MCBinaryExpr::Mod;
1091 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1092 /// Res contains the LHS of the expression on input.
1093 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1096 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1097 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1099 // If the next token is lower precedence than we are allowed to eat, return
1100 // successfully with what we ate already.
1101 if (TokPrec < Precedence)
1106 // Eat the next primary expression.
1108 if (parsePrimaryExpr(RHS, EndLoc))
1111 // If BinOp binds less tightly with RHS than the operator after RHS, let
1112 // the pending operator take RHS as its LHS.
1113 MCBinaryExpr::Opcode Dummy;
1114 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1115 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1118 // Merge LHS and RHS according to operator.
1119 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1124 /// ::= EndOfStatement
1125 /// ::= Label* Directive ...Operands... EndOfStatement
1126 /// ::= Label* Identifier OperandList* EndOfStatement
1127 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1128 if (Lexer.is(AsmToken::EndOfStatement)) {
1134 // Statements always start with an identifier or are a full line comment.
1135 AsmToken ID = getTok();
1136 SMLoc IDLoc = ID.getLoc();
1138 int64_t LocalLabelVal = -1;
1139 // A full line comment is a '#' as the first token.
1140 if (Lexer.is(AsmToken::Hash))
1141 return parseCppHashLineFilenameComment(IDLoc);
1143 // Allow an integer followed by a ':' as a directional local label.
1144 if (Lexer.is(AsmToken::Integer)) {
1145 LocalLabelVal = getTok().getIntVal();
1146 if (LocalLabelVal < 0) {
1147 if (!TheCondState.Ignore)
1148 return TokError("unexpected token at start of statement");
1151 IDVal = getTok().getString();
1152 Lex(); // Consume the integer token to be used as an identifier token.
1153 if (Lexer.getKind() != AsmToken::Colon) {
1154 if (!TheCondState.Ignore)
1155 return TokError("unexpected token at start of statement");
1158 } else if (Lexer.is(AsmToken::Dot)) {
1159 // Treat '.' as a valid identifier in this context.
1162 } else if (parseIdentifier(IDVal)) {
1163 if (!TheCondState.Ignore)
1164 return TokError("unexpected token at start of statement");
1168 // Handle conditional assembly here before checking for skipping. We
1169 // have to do this so that .endif isn't skipped in a ".if 0" block for
1171 StringMap<DirectiveKind>::const_iterator DirKindIt =
1172 DirectiveKindMap.find(IDVal);
1173 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1175 : DirKindIt->getValue();
1180 return parseDirectiveIf(IDLoc);
1182 return parseDirectiveIfb(IDLoc, true);
1184 return parseDirectiveIfb(IDLoc, false);
1186 return parseDirectiveIfc(IDLoc, true);
1188 return parseDirectiveIfc(IDLoc, false);
1190 return parseDirectiveIfdef(IDLoc, true);
1193 return parseDirectiveIfdef(IDLoc, false);
1195 return parseDirectiveElseIf(IDLoc);
1197 return parseDirectiveElse(IDLoc);
1199 return parseDirectiveEndIf(IDLoc);
1202 // Ignore the statement if in the middle of inactive conditional
1204 if (TheCondState.Ignore) {
1205 eatToEndOfStatement();
1209 // FIXME: Recurse on local labels?
1211 // See what kind of statement we have.
1212 switch (Lexer.getKind()) {
1213 case AsmToken::Colon: {
1214 checkForValidSection();
1216 // identifier ':' -> Label.
1219 // Diagnose attempt to use '.' as a label.
1221 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1223 // Diagnose attempt to use a variable as a label.
1225 // FIXME: Diagnostics. Note the location of the definition as a label.
1226 // FIXME: This doesn't diagnose assignment to a symbol which has been
1227 // implicitly marked as external.
1229 if (LocalLabelVal == -1)
1230 Sym = getContext().GetOrCreateSymbol(IDVal);
1232 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1233 if (!Sym->isUndefined() || Sym->isVariable())
1234 return Error(IDLoc, "invalid symbol redefinition");
1237 if (!ParsingInlineAsm)
1240 // If we are generating dwarf for assembly source files then gather the
1241 // info to make a dwarf label entry for this label if needed.
1242 if (getContext().getGenDwarfForAssembly())
1243 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1246 // Consume any end of statement token, if present, to avoid spurious
1247 // AddBlankLine calls().
1248 if (Lexer.is(AsmToken::EndOfStatement)) {
1250 if (Lexer.is(AsmToken::Eof))
1257 case AsmToken::Equal:
1258 // identifier '=' ... -> assignment statement
1261 return parseAssignment(IDVal, true);
1263 default: // Normal instruction or directive.
1267 // If macros are enabled, check to see if this is a macro instantiation.
1268 if (areMacrosEnabled())
1269 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1270 return handleMacroEntry(M, IDLoc);
1273 // Otherwise, we have a normal instruction or directive.
1275 // Directives start with "."
1276 if (IDVal[0] == '.' && IDVal != ".") {
1277 // There are several entities interested in parsing directives:
1279 // 1. The target-specific assembly parser. Some directives are target
1280 // specific or may potentially behave differently on certain targets.
1281 // 2. Asm parser extensions. For example, platform-specific parsers
1282 // (like the ELF parser) register themselves as extensions.
1283 // 3. The generic directive parser implemented by this class. These are
1284 // all the directives that behave in a target and platform independent
1285 // manner, or at least have a default behavior that's shared between
1286 // all targets and platforms.
1288 // First query the target-specific parser. It will return 'true' if it
1289 // isn't interested in this directive.
1290 if (!getTargetParser().ParseDirective(ID))
1293 // Next, check the extention directive map to see if any extension has
1294 // registered itself to parse this directive.
1295 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1296 ExtensionDirectiveMap.lookup(IDVal);
1298 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1300 // Finally, if no one else is interested in this directive, it must be
1301 // generic and familiar to this class.
1307 return parseDirectiveSet(IDVal, true);
1309 return parseDirectiveSet(IDVal, false);
1311 return parseDirectiveAscii(IDVal, false);
1314 return parseDirectiveAscii(IDVal, true);
1316 return parseDirectiveValue(1);
1320 return parseDirectiveValue(2);
1324 return parseDirectiveValue(4);
1327 return parseDirectiveValue(8);
1330 return parseDirectiveRealValue(APFloat::IEEEsingle);
1332 return parseDirectiveRealValue(APFloat::IEEEdouble);
1334 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1335 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1338 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1339 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1342 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1344 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1346 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1348 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1350 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1352 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1354 return parseDirectiveOrg();
1356 return parseDirectiveFill();
1358 return parseDirectiveZero();
1360 eatToEndOfStatement(); // .extern is the default, ignore it.
1364 return parseDirectiveSymbolAttribute(MCSA_Global);
1365 case DK_LAZY_REFERENCE:
1366 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1367 case DK_NO_DEAD_STRIP:
1368 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1369 case DK_SYMBOL_RESOLVER:
1370 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1371 case DK_PRIVATE_EXTERN:
1372 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1374 return parseDirectiveSymbolAttribute(MCSA_Reference);
1375 case DK_WEAK_DEFINITION:
1376 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1377 case DK_WEAK_REFERENCE:
1378 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1379 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1380 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1383 return parseDirectiveComm(/*IsLocal=*/false);
1385 return parseDirectiveComm(/*IsLocal=*/true);
1387 return parseDirectiveAbort();
1389 return parseDirectiveInclude();
1391 return parseDirectiveIncbin();
1394 return TokError(Twine(IDVal) + " not supported yet");
1396 return parseDirectiveRept(IDLoc);
1398 return parseDirectiveIrp(IDLoc);
1400 return parseDirectiveIrpc(IDLoc);
1402 return parseDirectiveEndr(IDLoc);
1403 case DK_BUNDLE_ALIGN_MODE:
1404 return parseDirectiveBundleAlignMode();
1405 case DK_BUNDLE_LOCK:
1406 return parseDirectiveBundleLock();
1407 case DK_BUNDLE_UNLOCK:
1408 return parseDirectiveBundleUnlock();
1410 return parseDirectiveLEB128(true);
1412 return parseDirectiveLEB128(false);
1415 return parseDirectiveSpace(IDVal);
1417 return parseDirectiveFile(IDLoc);
1419 return parseDirectiveLine();
1421 return parseDirectiveLoc();
1423 return parseDirectiveStabs();
1424 case DK_CFI_SECTIONS:
1425 return parseDirectiveCFISections();
1426 case DK_CFI_STARTPROC:
1427 return parseDirectiveCFIStartProc();
1428 case DK_CFI_ENDPROC:
1429 return parseDirectiveCFIEndProc();
1430 case DK_CFI_DEF_CFA:
1431 return parseDirectiveCFIDefCfa(IDLoc);
1432 case DK_CFI_DEF_CFA_OFFSET:
1433 return parseDirectiveCFIDefCfaOffset();
1434 case DK_CFI_ADJUST_CFA_OFFSET:
1435 return parseDirectiveCFIAdjustCfaOffset();
1436 case DK_CFI_DEF_CFA_REGISTER:
1437 return parseDirectiveCFIDefCfaRegister(IDLoc);
1439 return parseDirectiveCFIOffset(IDLoc);
1440 case DK_CFI_REL_OFFSET:
1441 return parseDirectiveCFIRelOffset(IDLoc);
1442 case DK_CFI_PERSONALITY:
1443 return parseDirectiveCFIPersonalityOrLsda(true);
1445 return parseDirectiveCFIPersonalityOrLsda(false);
1446 case DK_CFI_REMEMBER_STATE:
1447 return parseDirectiveCFIRememberState();
1448 case DK_CFI_RESTORE_STATE:
1449 return parseDirectiveCFIRestoreState();
1450 case DK_CFI_SAME_VALUE:
1451 return parseDirectiveCFISameValue(IDLoc);
1452 case DK_CFI_RESTORE:
1453 return parseDirectiveCFIRestore(IDLoc);
1455 return parseDirectiveCFIEscape();
1456 case DK_CFI_SIGNAL_FRAME:
1457 return parseDirectiveCFISignalFrame();
1458 case DK_CFI_UNDEFINED:
1459 return parseDirectiveCFIUndefined(IDLoc);
1460 case DK_CFI_REGISTER:
1461 return parseDirectiveCFIRegister(IDLoc);
1464 return parseDirectiveMacrosOnOff(IDVal);
1466 return parseDirectiveMacro(IDLoc);
1469 return parseDirectiveEndMacro(IDVal);
1471 return parseDirectivePurgeMacro(IDLoc);
1474 return Error(IDLoc, "unknown directive");
1477 // __asm _emit or __asm __emit
1478 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1479 IDVal == "_EMIT" || IDVal == "__EMIT"))
1480 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1483 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1484 return parseDirectiveMSAlign(IDLoc, Info);
1486 checkForValidSection();
1488 // Canonicalize the opcode to lower case.
1489 std::string OpcodeStr = IDVal.lower();
1490 ParseInstructionInfo IInfo(Info.AsmRewrites);
1491 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1492 Info.ParsedOperands);
1493 Info.ParseError = HadError;
1495 // Dump the parsed representation, if requested.
1496 if (getShowParsedOperands()) {
1497 SmallString<256> Str;
1498 raw_svector_ostream OS(Str);
1499 OS << "parsed instruction: [";
1500 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1503 Info.ParsedOperands[i]->print(OS);
1507 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1510 // If we are generating dwarf for assembly source files and the current
1511 // section is the initial text section then generate a .loc directive for
1513 if (!HadError && getContext().getGenDwarfForAssembly() &&
1514 getContext().getGenDwarfSection() ==
1515 getStreamer().getCurrentSection().first) {
1517 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1519 // If we previously parsed a cpp hash file line comment then make sure the
1520 // current Dwarf File is for the CppHashFilename if not then emit the
1521 // Dwarf File table for it and adjust the line number for the .loc.
1522 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1523 getContext().getMCDwarfFiles();
1524 if (CppHashFilename.size() != 0) {
1525 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1527 getStreamer().EmitDwarfFileDirective(
1528 getContext().nextGenDwarfFileNumber(), StringRef(),
1531 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1532 // cache with the different Loc from the call above we save the last
1533 // info we queried here with SrcMgr.FindLineNumber().
1534 unsigned CppHashLocLineNo;
1535 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1536 CppHashLocLineNo = LastQueryLine;
1538 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1539 LastQueryLine = CppHashLocLineNo;
1540 LastQueryIDLoc = CppHashLoc;
1541 LastQueryBuffer = CppHashBuf;
1543 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1546 getStreamer().EmitDwarfLocDirective(
1547 getContext().getGenDwarfFileNumber(), Line, 0,
1548 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1552 // If parsing succeeded, match the instruction.
1555 HadError = getTargetParser().MatchAndEmitInstruction(
1556 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1560 // Don't skip the rest of the line, the instruction parser is responsible for
1565 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1566 /// since they may not be able to be tokenized to get to the end of line token.
1567 void AsmParser::eatToEndOfLine() {
1568 if (!Lexer.is(AsmToken::EndOfStatement))
1569 Lexer.LexUntilEndOfLine();
1574 /// parseCppHashLineFilenameComment as this:
1575 /// ::= # number "filename"
1576 /// or just as a full line comment if it doesn't have a number and a string.
1577 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1578 Lex(); // Eat the hash token.
1580 if (getLexer().isNot(AsmToken::Integer)) {
1581 // Consume the line since in cases it is not a well-formed line directive,
1582 // as if were simply a full line comment.
1587 int64_t LineNumber = getTok().getIntVal();
1590 if (getLexer().isNot(AsmToken::String)) {
1595 StringRef Filename = getTok().getString();
1596 // Get rid of the enclosing quotes.
1597 Filename = Filename.substr(1, Filename.size() - 2);
1599 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1601 CppHashFilename = Filename;
1602 CppHashLineNumber = LineNumber;
1603 CppHashBuf = CurBuffer;
1605 // Ignore any trailing characters, they're just comment.
1610 /// \brief will use the last parsed cpp hash line filename comment
1611 /// for the Filename and LineNo if any in the diagnostic.
1612 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1613 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1614 raw_ostream &OS = errs();
1616 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1617 const SMLoc &DiagLoc = Diag.getLoc();
1618 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1619 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1621 // Like SourceMgr::printMessage() we need to print the include stack if any
1622 // before printing the message.
1623 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1624 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1625 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1626 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1629 // If we have not parsed a cpp hash line filename comment or the source
1630 // manager changed or buffer changed (like in a nested include) then just
1631 // print the normal diagnostic using its Filename and LineNo.
1632 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1633 DiagBuf != CppHashBuf) {
1634 if (Parser->SavedDiagHandler)
1635 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1641 // Use the CppHashFilename and calculate a line number based on the
1642 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1644 const std::string &Filename = Parser->CppHashFilename;
1646 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1647 int CppHashLocLineNo =
1648 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1650 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1652 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1653 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1654 Diag.getLineContents(), Diag.getRanges());
1656 if (Parser->SavedDiagHandler)
1657 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1659 NewDiag.print(0, OS);
1662 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1663 // difference being that that function accepts '@' as part of identifiers and
1664 // we can't do that. AsmLexer.cpp should probably be changed to handle
1665 // '@' as a special case when needed.
1666 static bool isIdentifierChar(char c) {
1667 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1671 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1672 const MCAsmMacroParameters &Parameters,
1673 const MCAsmMacroArguments &A, const SMLoc &L) {
1674 unsigned NParameters = Parameters.size();
1675 if (NParameters != 0 && NParameters != A.size())
1676 return Error(L, "Wrong number of arguments");
1678 // A macro without parameters is handled differently on Darwin:
1679 // gas accepts no arguments and does no substitutions
1680 while (!Body.empty()) {
1681 // Scan for the next substitution.
1682 std::size_t End = Body.size(), Pos = 0;
1683 for (; Pos != End; ++Pos) {
1684 // Check for a substitution or escape.
1686 // This macro has no parameters, look for $0, $1, etc.
1687 if (Body[Pos] != '$' || Pos + 1 == End)
1690 char Next = Body[Pos + 1];
1691 if (Next == '$' || Next == 'n' ||
1692 isdigit(static_cast<unsigned char>(Next)))
1695 // This macro has parameters, look for \foo, \bar, etc.
1696 if (Body[Pos] == '\\' && Pos + 1 != End)
1702 OS << Body.slice(0, Pos);
1704 // Check if we reached the end.
1709 switch (Body[Pos + 1]) {
1715 // $n => number of arguments
1720 // $[0-9] => argument
1722 // Missing arguments are ignored.
1723 unsigned Index = Body[Pos + 1] - '0';
1724 if (Index >= A.size())
1727 // Otherwise substitute with the token values, with spaces eliminated.
1728 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1729 ie = A[Index].end();
1731 OS << it->getString();
1737 unsigned I = Pos + 1;
1738 while (isIdentifierChar(Body[I]) && I + 1 != End)
1741 const char *Begin = Body.data() + Pos + 1;
1742 StringRef Argument(Begin, I - (Pos + 1));
1744 for (; Index < NParameters; ++Index)
1745 if (Parameters[Index].first == Argument)
1748 if (Index == NParameters) {
1749 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1752 OS << '\\' << Argument;
1756 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1757 ie = A[Index].end();
1759 if (it->getKind() == AsmToken::String)
1760 OS << it->getStringContents();
1762 OS << it->getString();
1764 Pos += 1 + Argument.size();
1767 // Update the scan point.
1768 Body = Body.substr(Pos);
1774 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1775 SMLoc EL, MemoryBuffer *I)
1776 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1779 static bool isOperator(AsmToken::TokenKind kind) {
1783 case AsmToken::Plus:
1784 case AsmToken::Minus:
1785 case AsmToken::Tilde:
1786 case AsmToken::Slash:
1787 case AsmToken::Star:
1789 case AsmToken::Equal:
1790 case AsmToken::EqualEqual:
1791 case AsmToken::Pipe:
1792 case AsmToken::PipePipe:
1793 case AsmToken::Caret:
1795 case AsmToken::AmpAmp:
1796 case AsmToken::Exclaim:
1797 case AsmToken::ExclaimEqual:
1798 case AsmToken::Percent:
1799 case AsmToken::Less:
1800 case AsmToken::LessEqual:
1801 case AsmToken::LessLess:
1802 case AsmToken::LessGreater:
1803 case AsmToken::Greater:
1804 case AsmToken::GreaterEqual:
1805 case AsmToken::GreaterGreater:
1810 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1811 AsmToken::TokenKind &ArgumentDelimiter) {
1812 unsigned ParenLevel = 0;
1813 unsigned AddTokens = 0;
1815 // gas accepts arguments separated by whitespace, except on Darwin
1817 Lexer.setSkipSpace(false);
1820 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1821 Lexer.setSkipSpace(true);
1822 return TokError("unexpected token in macro instantiation");
1825 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1826 // Spaces and commas cannot be mixed to delimit parameters
1827 if (ArgumentDelimiter == AsmToken::Eof)
1828 ArgumentDelimiter = AsmToken::Comma;
1829 else if (ArgumentDelimiter != AsmToken::Comma) {
1830 Lexer.setSkipSpace(true);
1831 return TokError("expected ' ' for macro argument separator");
1836 if (Lexer.is(AsmToken::Space)) {
1837 Lex(); // Eat spaces
1839 // Spaces can delimit parameters, but could also be part an expression.
1840 // If the token after a space is an operator, add the token and the next
1841 // one into this argument
1842 if (ArgumentDelimiter == AsmToken::Space ||
1843 ArgumentDelimiter == AsmToken::Eof) {
1844 if (isOperator(Lexer.getKind())) {
1845 // Check to see whether the token is used as an operator,
1846 // or part of an identifier
1847 const char *NextChar = getTok().getEndLoc().getPointer();
1848 if (*NextChar == ' ')
1852 if (!AddTokens && ParenLevel == 0) {
1853 if (ArgumentDelimiter == AsmToken::Eof &&
1854 !isOperator(Lexer.getKind()))
1855 ArgumentDelimiter = AsmToken::Space;
1861 // handleMacroEntry relies on not advancing the lexer here
1862 // to be able to fill in the remaining default parameter values
1863 if (Lexer.is(AsmToken::EndOfStatement))
1866 // Adjust the current parentheses level.
1867 if (Lexer.is(AsmToken::LParen))
1869 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1872 // Append the token to the current argument list.
1873 MA.push_back(getTok());
1879 Lexer.setSkipSpace(true);
1880 if (ParenLevel != 0)
1881 return TokError("unbalanced parentheses in macro argument");
1885 // Parse the macro instantiation arguments.
1886 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1887 MCAsmMacroArguments &A) {
1888 const unsigned NParameters = M ? M->Parameters.size() : 0;
1889 // Argument delimiter is initially unknown. It will be set by
1890 // parseMacroArgument()
1891 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1893 // Parse two kinds of macro invocations:
1894 // - macros defined without any parameters accept an arbitrary number of them
1895 // - macros defined with parameters accept at most that many of them
1896 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1898 MCAsmMacroArgument MA;
1900 if (parseMacroArgument(MA, ArgumentDelimiter))
1903 if (!MA.empty() || !NParameters)
1905 else if (NParameters) {
1906 if (!M->Parameters[Parameter].second.empty())
1907 A.push_back(M->Parameters[Parameter].second);
1910 // At the end of the statement, fill in remaining arguments that have
1911 // default values. If there aren't any, then the next argument is
1912 // required but missing
1913 if (Lexer.is(AsmToken::EndOfStatement)) {
1914 if (NParameters && Parameter < NParameters - 1) {
1915 if (M->Parameters[Parameter + 1].second.empty())
1916 return TokError("macro argument '" +
1917 Twine(M->Parameters[Parameter + 1].first) +
1925 if (Lexer.is(AsmToken::Comma))
1928 return TokError("Too many arguments");
1931 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1932 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1933 return (I == MacroMap.end()) ? NULL : I->getValue();
1936 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1937 MacroMap[Name] = new MCAsmMacro(Macro);
1940 void AsmParser::undefineMacro(StringRef Name) {
1941 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1942 if (I != MacroMap.end()) {
1943 delete I->getValue();
1948 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1949 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1950 // this, although we should protect against infinite loops.
1951 if (ActiveMacros.size() == 20)
1952 return TokError("macros cannot be nested more than 20 levels deep");
1954 MCAsmMacroArguments A;
1955 if (parseMacroArguments(M, A))
1958 // Remove any trailing empty arguments. Do this after-the-fact as we have
1959 // to keep empty arguments in the middle of the list or positionality
1960 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1961 while (!A.empty() && A.back().empty())
1964 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1965 // to hold the macro body with substitutions.
1966 SmallString<256> Buf;
1967 StringRef Body = M->Body;
1968 raw_svector_ostream OS(Buf);
1970 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1973 // We include the .endmacro in the buffer as our cue to exit the macro
1975 OS << ".endmacro\n";
1977 MemoryBuffer *Instantiation =
1978 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1980 // Create the macro instantiation object and add to the current macro
1981 // instantiation stack.
1982 MacroInstantiation *MI = new MacroInstantiation(
1983 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
1984 ActiveMacros.push_back(MI);
1986 // Jump to the macro instantiation and prime the lexer.
1987 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1988 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1994 void AsmParser::handleMacroExit() {
1995 // Jump to the EndOfStatement we should return to, and consume it.
1996 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1999 // Pop the instantiation entry.
2000 delete ActiveMacros.back();
2001 ActiveMacros.pop_back();
2004 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2005 switch (Value->getKind()) {
2006 case MCExpr::Binary: {
2007 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2008 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2010 case MCExpr::Target:
2011 case MCExpr::Constant:
2013 case MCExpr::SymbolRef: {
2015 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2017 return isUsedIn(Sym, S.getVariableValue());
2021 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2024 llvm_unreachable("Unknown expr kind!");
2027 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2029 // FIXME: Use better location, we should use proper tokens.
2030 SMLoc EqualLoc = Lexer.getLoc();
2032 const MCExpr *Value;
2033 if (parseExpression(Value))
2036 // Note: we don't count b as used in "a = b". This is to allow
2040 if (Lexer.isNot(AsmToken::EndOfStatement))
2041 return TokError("unexpected token in assignment");
2043 // Error on assignment to '.'.
2045 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2046 "(use '.space' or '.org').)"));
2049 // Eat the end of statement marker.
2052 // Validate that the LHS is allowed to be a variable (either it has not been
2053 // used as a symbol, or it is an absolute symbol).
2054 MCSymbol *Sym = getContext().LookupSymbol(Name);
2056 // Diagnose assignment to a label.
2058 // FIXME: Diagnostics. Note the location of the definition as a label.
2059 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2060 if (isUsedIn(Sym, Value))
2061 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2062 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2063 ; // Allow redefinitions of undefined symbols only used in directives.
2064 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2065 ; // Allow redefinitions of variables that haven't yet been used.
2066 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2067 return Error(EqualLoc, "redefinition of '" + Name + "'");
2068 else if (!Sym->isVariable())
2069 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2070 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2071 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2074 // Don't count these checks as uses.
2075 Sym->setUsed(false);
2077 Sym = getContext().GetOrCreateSymbol(Name);
2079 // FIXME: Handle '.'.
2081 // Do the assignment.
2082 Out.EmitAssignment(Sym, Value);
2084 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2089 /// parseIdentifier:
2092 bool AsmParser::parseIdentifier(StringRef &Res) {
2093 // The assembler has relaxed rules for accepting identifiers, in particular we
2094 // allow things like '.globl $foo', which would normally be separate
2095 // tokens. At this level, we have already lexed so we cannot (currently)
2096 // handle this as a context dependent token, instead we detect adjacent tokens
2097 // and return the combined identifier.
2098 if (Lexer.is(AsmToken::Dollar)) {
2099 SMLoc DollarLoc = getLexer().getLoc();
2101 // Consume the dollar sign, and check for a following identifier.
2103 if (Lexer.isNot(AsmToken::Identifier))
2106 // We have a '$' followed by an identifier, make sure they are adjacent.
2107 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2110 // Construct the joined identifier and consume the token.
2112 StringRef(DollarLoc.getPointer(), getTok().getIdentifier().size() + 1);
2117 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2120 Res = getTok().getIdentifier();
2122 Lex(); // Consume the identifier token.
2127 /// parseDirectiveSet:
2128 /// ::= .equ identifier ',' expression
2129 /// ::= .equiv identifier ',' expression
2130 /// ::= .set identifier ',' expression
2131 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2134 if (parseIdentifier(Name))
2135 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2137 if (getLexer().isNot(AsmToken::Comma))
2138 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2141 return parseAssignment(Name, allow_redef, true);
2144 bool AsmParser::parseEscapedString(std::string &Data) {
2145 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2148 StringRef Str = getTok().getStringContents();
2149 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2150 if (Str[i] != '\\') {
2155 // Recognize escaped characters. Note that this escape semantics currently
2156 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2159 return TokError("unexpected backslash at end of string");
2161 // Recognize octal sequences.
2162 if ((unsigned)(Str[i] - '0') <= 7) {
2163 // Consume up to three octal characters.
2164 unsigned Value = Str[i] - '0';
2166 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2168 Value = Value * 8 + (Str[i] - '0');
2170 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2172 Value = Value * 8 + (Str[i] - '0');
2177 return TokError("invalid octal escape sequence (out of range)");
2179 Data += (unsigned char)Value;
2183 // Otherwise recognize individual escapes.
2186 // Just reject invalid escape sequences for now.
2187 return TokError("invalid escape sequence (unrecognized character)");
2189 case 'b': Data += '\b'; break;
2190 case 'f': Data += '\f'; break;
2191 case 'n': Data += '\n'; break;
2192 case 'r': Data += '\r'; break;
2193 case 't': Data += '\t'; break;
2194 case '"': Data += '"'; break;
2195 case '\\': Data += '\\'; break;
2202 /// parseDirectiveAscii:
2203 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2204 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2205 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2206 checkForValidSection();
2209 if (getLexer().isNot(AsmToken::String))
2210 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2213 if (parseEscapedString(Data))
2216 getStreamer().EmitBytes(Data);
2218 getStreamer().EmitBytes(StringRef("\0", 1));
2222 if (getLexer().is(AsmToken::EndOfStatement))
2225 if (getLexer().isNot(AsmToken::Comma))
2226 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2235 /// parseDirectiveValue
2236 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2237 bool AsmParser::parseDirectiveValue(unsigned Size) {
2238 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2239 checkForValidSection();
2242 const MCExpr *Value;
2243 SMLoc ExprLoc = getLexer().getLoc();
2244 if (parseExpression(Value))
2247 // Special case constant expressions to match code generator.
2248 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2249 assert(Size <= 8 && "Invalid size");
2250 uint64_t IntValue = MCE->getValue();
2251 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2252 return Error(ExprLoc, "literal value out of range for directive");
2253 getStreamer().EmitIntValue(IntValue, Size);
2255 getStreamer().EmitValue(Value, Size);
2257 if (getLexer().is(AsmToken::EndOfStatement))
2260 // FIXME: Improve diagnostic.
2261 if (getLexer().isNot(AsmToken::Comma))
2262 return TokError("unexpected token in directive");
2271 /// parseDirectiveRealValue
2272 /// ::= (.single | .double) [ expression (, expression)* ]
2273 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2274 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2275 checkForValidSection();
2278 // We don't truly support arithmetic on floating point expressions, so we
2279 // have to manually parse unary prefixes.
2281 if (getLexer().is(AsmToken::Minus)) {
2284 } else if (getLexer().is(AsmToken::Plus))
2287 if (getLexer().isNot(AsmToken::Integer) &&
2288 getLexer().isNot(AsmToken::Real) &&
2289 getLexer().isNot(AsmToken::Identifier))
2290 return TokError("unexpected token in directive");
2292 // Convert to an APFloat.
2293 APFloat Value(Semantics);
2294 StringRef IDVal = getTok().getString();
2295 if (getLexer().is(AsmToken::Identifier)) {
2296 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2297 Value = APFloat::getInf(Semantics);
2298 else if (!IDVal.compare_lower("nan"))
2299 Value = APFloat::getNaN(Semantics, false, ~0);
2301 return TokError("invalid floating point literal");
2302 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2303 APFloat::opInvalidOp)
2304 return TokError("invalid floating point literal");
2308 // Consume the numeric token.
2311 // Emit the value as an integer.
2312 APInt AsInt = Value.bitcastToAPInt();
2313 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2314 AsInt.getBitWidth() / 8);
2316 if (getLexer().is(AsmToken::EndOfStatement))
2319 if (getLexer().isNot(AsmToken::Comma))
2320 return TokError("unexpected token in directive");
2329 /// parseDirectiveZero
2330 /// ::= .zero expression
2331 bool AsmParser::parseDirectiveZero() {
2332 checkForValidSection();
2335 if (parseAbsoluteExpression(NumBytes))
2339 if (getLexer().is(AsmToken::Comma)) {
2341 if (parseAbsoluteExpression(Val))
2345 if (getLexer().isNot(AsmToken::EndOfStatement))
2346 return TokError("unexpected token in '.zero' directive");
2350 getStreamer().EmitFill(NumBytes, Val);
2355 /// parseDirectiveFill
2356 /// ::= .fill expression , expression , expression
2357 bool AsmParser::parseDirectiveFill() {
2358 checkForValidSection();
2361 if (parseAbsoluteExpression(NumValues))
2364 if (getLexer().isNot(AsmToken::Comma))
2365 return TokError("unexpected token in '.fill' directive");
2369 if (parseAbsoluteExpression(FillSize))
2372 if (getLexer().isNot(AsmToken::Comma))
2373 return TokError("unexpected token in '.fill' directive");
2377 if (parseAbsoluteExpression(FillExpr))
2380 if (getLexer().isNot(AsmToken::EndOfStatement))
2381 return TokError("unexpected token in '.fill' directive");
2385 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2386 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2388 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2389 getStreamer().EmitIntValue(FillExpr, FillSize);
2394 /// parseDirectiveOrg
2395 /// ::= .org expression [ , expression ]
2396 bool AsmParser::parseDirectiveOrg() {
2397 checkForValidSection();
2399 const MCExpr *Offset;
2400 SMLoc Loc = getTok().getLoc();
2401 if (parseExpression(Offset))
2404 // Parse optional fill expression.
2405 int64_t FillExpr = 0;
2406 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2407 if (getLexer().isNot(AsmToken::Comma))
2408 return TokError("unexpected token in '.org' directive");
2411 if (parseAbsoluteExpression(FillExpr))
2414 if (getLexer().isNot(AsmToken::EndOfStatement))
2415 return TokError("unexpected token in '.org' directive");
2420 // Only limited forms of relocatable expressions are accepted here, it
2421 // has to be relative to the current section. The streamer will return
2422 // 'true' if the expression wasn't evaluatable.
2423 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2424 return Error(Loc, "expected assembly-time absolute expression");
2429 /// parseDirectiveAlign
2430 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2431 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2432 checkForValidSection();
2434 SMLoc AlignmentLoc = getLexer().getLoc();
2436 if (parseAbsoluteExpression(Alignment))
2440 bool HasFillExpr = false;
2441 int64_t FillExpr = 0;
2442 int64_t MaxBytesToFill = 0;
2443 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2444 if (getLexer().isNot(AsmToken::Comma))
2445 return TokError("unexpected token in directive");
2448 // The fill expression can be omitted while specifying a maximum number of
2449 // alignment bytes, e.g:
2451 if (getLexer().isNot(AsmToken::Comma)) {
2453 if (parseAbsoluteExpression(FillExpr))
2457 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2458 if (getLexer().isNot(AsmToken::Comma))
2459 return TokError("unexpected token in directive");
2462 MaxBytesLoc = getLexer().getLoc();
2463 if (parseAbsoluteExpression(MaxBytesToFill))
2466 if (getLexer().isNot(AsmToken::EndOfStatement))
2467 return TokError("unexpected token in directive");
2476 // Compute alignment in bytes.
2478 // FIXME: Diagnose overflow.
2479 if (Alignment >= 32) {
2480 Error(AlignmentLoc, "invalid alignment value");
2484 Alignment = 1ULL << Alignment;
2486 // Reject alignments that aren't a power of two, for gas compatibility.
2487 if (!isPowerOf2_64(Alignment))
2488 Error(AlignmentLoc, "alignment must be a power of 2");
2491 // Diagnose non-sensical max bytes to align.
2492 if (MaxBytesLoc.isValid()) {
2493 if (MaxBytesToFill < 1) {
2494 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2495 "many bytes, ignoring maximum bytes expression");
2499 if (MaxBytesToFill >= Alignment) {
2500 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2506 // Check whether we should use optimal code alignment for this .align
2508 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2509 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2510 ValueSize == 1 && UseCodeAlign) {
2511 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2513 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2514 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2521 /// parseDirectiveFile
2522 /// ::= .file [number] filename
2523 /// ::= .file number directory filename
2524 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2525 // FIXME: I'm not sure what this is.
2526 int64_t FileNumber = -1;
2527 SMLoc FileNumberLoc = getLexer().getLoc();
2528 if (getLexer().is(AsmToken::Integer)) {
2529 FileNumber = getTok().getIntVal();
2533 return TokError("file number less than one");
2536 if (getLexer().isNot(AsmToken::String))
2537 return TokError("unexpected token in '.file' directive");
2539 // Usually the directory and filename together, otherwise just the directory.
2540 // Allow the strings to have escaped octal character sequence.
2541 std::string Path = getTok().getString();
2542 if (parseEscapedString(Path))
2546 StringRef Directory;
2548 std::string FilenameData;
2549 if (getLexer().is(AsmToken::String)) {
2550 if (FileNumber == -1)
2551 return TokError("explicit path specified, but no file number");
2552 if (parseEscapedString(FilenameData))
2554 Filename = FilenameData;
2561 if (getLexer().isNot(AsmToken::EndOfStatement))
2562 return TokError("unexpected token in '.file' directive");
2564 if (FileNumber == -1)
2565 getStreamer().EmitFileDirective(Filename);
2567 if (getContext().getGenDwarfForAssembly() == true)
2569 "input can't have .file dwarf directives when -g is "
2570 "used to generate dwarf debug info for assembly code");
2572 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2573 Error(FileNumberLoc, "file number already allocated");
2579 /// parseDirectiveLine
2580 /// ::= .line [number]
2581 bool AsmParser::parseDirectiveLine() {
2582 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2583 if (getLexer().isNot(AsmToken::Integer))
2584 return TokError("unexpected token in '.line' directive");
2586 int64_t LineNumber = getTok().getIntVal();
2590 // FIXME: Do something with the .line.
2593 if (getLexer().isNot(AsmToken::EndOfStatement))
2594 return TokError("unexpected token in '.line' directive");
2599 /// parseDirectiveLoc
2600 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2601 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2602 /// The first number is a file number, must have been previously assigned with
2603 /// a .file directive, the second number is the line number and optionally the
2604 /// third number is a column position (zero if not specified). The remaining
2605 /// optional items are .loc sub-directives.
2606 bool AsmParser::parseDirectiveLoc() {
2607 if (getLexer().isNot(AsmToken::Integer))
2608 return TokError("unexpected token in '.loc' directive");
2609 int64_t FileNumber = getTok().getIntVal();
2611 return TokError("file number less than one in '.loc' directive");
2612 if (!getContext().isValidDwarfFileNumber(FileNumber))
2613 return TokError("unassigned file number in '.loc' directive");
2616 int64_t LineNumber = 0;
2617 if (getLexer().is(AsmToken::Integer)) {
2618 LineNumber = getTok().getIntVal();
2620 return TokError("line number less than one in '.loc' directive");
2624 int64_t ColumnPos = 0;
2625 if (getLexer().is(AsmToken::Integer)) {
2626 ColumnPos = getTok().getIntVal();
2628 return TokError("column position less than zero in '.loc' directive");
2632 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2634 int64_t Discriminator = 0;
2635 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2637 if (getLexer().is(AsmToken::EndOfStatement))
2641 SMLoc Loc = getTok().getLoc();
2642 if (parseIdentifier(Name))
2643 return TokError("unexpected token in '.loc' directive");
2645 if (Name == "basic_block")
2646 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2647 else if (Name == "prologue_end")
2648 Flags |= DWARF2_FLAG_PROLOGUE_END;
2649 else if (Name == "epilogue_begin")
2650 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2651 else if (Name == "is_stmt") {
2652 Loc = getTok().getLoc();
2653 const MCExpr *Value;
2654 if (parseExpression(Value))
2656 // The expression must be the constant 0 or 1.
2657 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2658 int Value = MCE->getValue();
2660 Flags &= ~DWARF2_FLAG_IS_STMT;
2661 else if (Value == 1)
2662 Flags |= DWARF2_FLAG_IS_STMT;
2664 return Error(Loc, "is_stmt value not 0 or 1");
2666 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2668 } else if (Name == "isa") {
2669 Loc = getTok().getLoc();
2670 const MCExpr *Value;
2671 if (parseExpression(Value))
2673 // The expression must be a constant greater or equal to 0.
2674 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2675 int Value = MCE->getValue();
2677 return Error(Loc, "isa number less than zero");
2680 return Error(Loc, "isa number not a constant value");
2682 } else if (Name == "discriminator") {
2683 if (parseAbsoluteExpression(Discriminator))
2686 return Error(Loc, "unknown sub-directive in '.loc' directive");
2689 if (getLexer().is(AsmToken::EndOfStatement))
2694 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2695 Isa, Discriminator, StringRef());
2700 /// parseDirectiveStabs
2701 /// ::= .stabs string, number, number, number
2702 bool AsmParser::parseDirectiveStabs() {
2703 return TokError("unsupported directive '.stabs'");
2706 /// parseDirectiveCFISections
2707 /// ::= .cfi_sections section [, section]
2708 bool AsmParser::parseDirectiveCFISections() {
2713 if (parseIdentifier(Name))
2714 return TokError("Expected an identifier");
2716 if (Name == ".eh_frame")
2718 else if (Name == ".debug_frame")
2721 if (getLexer().is(AsmToken::Comma)) {
2724 if (parseIdentifier(Name))
2725 return TokError("Expected an identifier");
2727 if (Name == ".eh_frame")
2729 else if (Name == ".debug_frame")
2733 getStreamer().EmitCFISections(EH, Debug);
2737 /// parseDirectiveCFIStartProc
2738 /// ::= .cfi_startproc
2739 bool AsmParser::parseDirectiveCFIStartProc() {
2740 getStreamer().EmitCFIStartProc();
2744 /// parseDirectiveCFIEndProc
2745 /// ::= .cfi_endproc
2746 bool AsmParser::parseDirectiveCFIEndProc() {
2747 getStreamer().EmitCFIEndProc();
2751 /// \brief parse register name or number.
2752 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2753 SMLoc DirectiveLoc) {
2756 if (getLexer().isNot(AsmToken::Integer)) {
2757 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2759 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2761 return parseAbsoluteExpression(Register);
2766 /// parseDirectiveCFIDefCfa
2767 /// ::= .cfi_def_cfa register, offset
2768 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2769 int64_t Register = 0;
2770 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2773 if (getLexer().isNot(AsmToken::Comma))
2774 return TokError("unexpected token in directive");
2778 if (parseAbsoluteExpression(Offset))
2781 getStreamer().EmitCFIDefCfa(Register, Offset);
2785 /// parseDirectiveCFIDefCfaOffset
2786 /// ::= .cfi_def_cfa_offset offset
2787 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2789 if (parseAbsoluteExpression(Offset))
2792 getStreamer().EmitCFIDefCfaOffset(Offset);
2796 /// parseDirectiveCFIRegister
2797 /// ::= .cfi_register register, register
2798 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2799 int64_t Register1 = 0;
2800 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2803 if (getLexer().isNot(AsmToken::Comma))
2804 return TokError("unexpected token in directive");
2807 int64_t Register2 = 0;
2808 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2811 getStreamer().EmitCFIRegister(Register1, Register2);
2815 /// parseDirectiveCFIAdjustCfaOffset
2816 /// ::= .cfi_adjust_cfa_offset adjustment
2817 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2818 int64_t Adjustment = 0;
2819 if (parseAbsoluteExpression(Adjustment))
2822 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2826 /// parseDirectiveCFIDefCfaRegister
2827 /// ::= .cfi_def_cfa_register register
2828 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2829 int64_t Register = 0;
2830 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2833 getStreamer().EmitCFIDefCfaRegister(Register);
2837 /// parseDirectiveCFIOffset
2838 /// ::= .cfi_offset register, offset
2839 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2840 int64_t Register = 0;
2843 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2846 if (getLexer().isNot(AsmToken::Comma))
2847 return TokError("unexpected token in directive");
2850 if (parseAbsoluteExpression(Offset))
2853 getStreamer().EmitCFIOffset(Register, Offset);
2857 /// parseDirectiveCFIRelOffset
2858 /// ::= .cfi_rel_offset register, offset
2859 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2860 int64_t Register = 0;
2862 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2865 if (getLexer().isNot(AsmToken::Comma))
2866 return TokError("unexpected token in directive");
2870 if (parseAbsoluteExpression(Offset))
2873 getStreamer().EmitCFIRelOffset(Register, Offset);
2877 static bool isValidEncoding(int64_t Encoding) {
2878 if (Encoding & ~0xff)
2881 if (Encoding == dwarf::DW_EH_PE_omit)
2884 const unsigned Format = Encoding & 0xf;
2885 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2886 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2887 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2888 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2891 const unsigned Application = Encoding & 0x70;
2892 if (Application != dwarf::DW_EH_PE_absptr &&
2893 Application != dwarf::DW_EH_PE_pcrel)
2899 /// parseDirectiveCFIPersonalityOrLsda
2900 /// IsPersonality true for cfi_personality, false for cfi_lsda
2901 /// ::= .cfi_personality encoding, [symbol_name]
2902 /// ::= .cfi_lsda encoding, [symbol_name]
2903 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2904 int64_t Encoding = 0;
2905 if (parseAbsoluteExpression(Encoding))
2907 if (Encoding == dwarf::DW_EH_PE_omit)
2910 if (!isValidEncoding(Encoding))
2911 return TokError("unsupported encoding.");
2913 if (getLexer().isNot(AsmToken::Comma))
2914 return TokError("unexpected token in directive");
2918 if (parseIdentifier(Name))
2919 return TokError("expected identifier in directive");
2921 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2924 getStreamer().EmitCFIPersonality(Sym, Encoding);
2926 getStreamer().EmitCFILsda(Sym, Encoding);
2930 /// parseDirectiveCFIRememberState
2931 /// ::= .cfi_remember_state
2932 bool AsmParser::parseDirectiveCFIRememberState() {
2933 getStreamer().EmitCFIRememberState();
2937 /// parseDirectiveCFIRestoreState
2938 /// ::= .cfi_remember_state
2939 bool AsmParser::parseDirectiveCFIRestoreState() {
2940 getStreamer().EmitCFIRestoreState();
2944 /// parseDirectiveCFISameValue
2945 /// ::= .cfi_same_value register
2946 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2947 int64_t Register = 0;
2949 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2952 getStreamer().EmitCFISameValue(Register);
2956 /// parseDirectiveCFIRestore
2957 /// ::= .cfi_restore register
2958 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2959 int64_t Register = 0;
2960 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2963 getStreamer().EmitCFIRestore(Register);
2967 /// parseDirectiveCFIEscape
2968 /// ::= .cfi_escape expression[,...]
2969 bool AsmParser::parseDirectiveCFIEscape() {
2972 if (parseAbsoluteExpression(CurrValue))
2975 Values.push_back((uint8_t)CurrValue);
2977 while (getLexer().is(AsmToken::Comma)) {
2980 if (parseAbsoluteExpression(CurrValue))
2983 Values.push_back((uint8_t)CurrValue);
2986 getStreamer().EmitCFIEscape(Values);
2990 /// parseDirectiveCFISignalFrame
2991 /// ::= .cfi_signal_frame
2992 bool AsmParser::parseDirectiveCFISignalFrame() {
2993 if (getLexer().isNot(AsmToken::EndOfStatement))
2994 return Error(getLexer().getLoc(),
2995 "unexpected token in '.cfi_signal_frame'");
2997 getStreamer().EmitCFISignalFrame();
3001 /// parseDirectiveCFIUndefined
3002 /// ::= .cfi_undefined register
3003 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3004 int64_t Register = 0;
3006 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3009 getStreamer().EmitCFIUndefined(Register);
3013 /// parseDirectiveMacrosOnOff
3016 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3017 if (getLexer().isNot(AsmToken::EndOfStatement))
3018 return Error(getLexer().getLoc(),
3019 "unexpected token in '" + Directive + "' directive");
3021 setMacrosEnabled(Directive == ".macros_on");
3025 /// parseDirectiveMacro
3026 /// ::= .macro name [parameters]
3027 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3029 if (parseIdentifier(Name))
3030 return TokError("expected identifier in '.macro' directive");
3032 MCAsmMacroParameters Parameters;
3033 // Argument delimiter is initially unknown. It will be set by
3034 // parseMacroArgument()
3035 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3036 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3038 MCAsmMacroParameter Parameter;
3039 if (parseIdentifier(Parameter.first))
3040 return TokError("expected identifier in '.macro' directive");
3042 if (getLexer().is(AsmToken::Equal)) {
3044 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3048 Parameters.push_back(Parameter);
3050 if (getLexer().is(AsmToken::Comma))
3052 else if (getLexer().is(AsmToken::EndOfStatement))
3057 // Eat the end of statement.
3060 AsmToken EndToken, StartToken = getTok();
3062 // Lex the macro definition.
3064 // Check whether we have reached the end of the file.
3065 if (getLexer().is(AsmToken::Eof))
3066 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3068 // Otherwise, check whether we have reach the .endmacro.
3069 if (getLexer().is(AsmToken::Identifier) &&
3070 (getTok().getIdentifier() == ".endm" ||
3071 getTok().getIdentifier() == ".endmacro")) {
3072 EndToken = getTok();
3074 if (getLexer().isNot(AsmToken::EndOfStatement))
3075 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3080 // Otherwise, scan til the end of the statement.
3081 eatToEndOfStatement();
3084 if (lookupMacro(Name)) {
3085 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3088 const char *BodyStart = StartToken.getLoc().getPointer();
3089 const char *BodyEnd = EndToken.getLoc().getPointer();
3090 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3091 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3092 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3096 /// checkForBadMacro
3098 /// With the support added for named parameters there may be code out there that
3099 /// is transitioning from positional parameters. In versions of gas that did
3100 /// not support named parameters they would be ignored on the macro defintion.
3101 /// But to support both styles of parameters this is not possible so if a macro
3102 /// defintion has named parameters but does not use them and has what appears
3103 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3104 /// warning that the positional parameter found in body which have no effect.
3105 /// Hoping the developer will either remove the named parameters from the macro
3106 /// definiton so the positional parameters get used if that was what was
3107 /// intended or change the macro to use the named parameters. It is possible
3108 /// this warning will trigger when the none of the named parameters are used
3109 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3110 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3112 MCAsmMacroParameters Parameters) {
3113 // If this macro is not defined with named parameters the warning we are
3114 // checking for here doesn't apply.
3115 unsigned NParameters = Parameters.size();
3116 if (NParameters == 0)
3119 bool NamedParametersFound = false;
3120 bool PositionalParametersFound = false;
3122 // Look at the body of the macro for use of both the named parameters and what
3123 // are likely to be positional parameters. This is what expandMacro() is
3124 // doing when it finds the parameters in the body.
3125 while (!Body.empty()) {
3126 // Scan for the next possible parameter.
3127 std::size_t End = Body.size(), Pos = 0;
3128 for (; Pos != End; ++Pos) {
3129 // Check for a substitution or escape.
3130 // This macro is defined with parameters, look for \foo, \bar, etc.
3131 if (Body[Pos] == '\\' && Pos + 1 != End)
3134 // This macro should have parameters, but look for $0, $1, ..., $n too.
3135 if (Body[Pos] != '$' || Pos + 1 == End)
3137 char Next = Body[Pos + 1];
3138 if (Next == '$' || Next == 'n' ||
3139 isdigit(static_cast<unsigned char>(Next)))
3143 // Check if we reached the end.
3147 if (Body[Pos] == '$') {
3148 switch (Body[Pos + 1]) {
3153 // $n => number of arguments
3155 PositionalParametersFound = true;
3158 // $[0-9] => argument
3160 PositionalParametersFound = true;
3166 unsigned I = Pos + 1;
3167 while (isIdentifierChar(Body[I]) && I + 1 != End)
3170 const char *Begin = Body.data() + Pos + 1;
3171 StringRef Argument(Begin, I - (Pos + 1));
3173 for (; Index < NParameters; ++Index)
3174 if (Parameters[Index].first == Argument)
3177 if (Index == NParameters) {
3178 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3184 NamedParametersFound = true;
3185 Pos += 1 + Argument.size();
3188 // Update the scan point.
3189 Body = Body.substr(Pos);
3192 if (!NamedParametersFound && PositionalParametersFound)
3193 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3194 "used in macro body, possible positional parameter "
3195 "found in body which will have no effect");
3198 /// parseDirectiveEndMacro
3201 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3202 if (getLexer().isNot(AsmToken::EndOfStatement))
3203 return TokError("unexpected token in '" + Directive + "' directive");
3205 // If we are inside a macro instantiation, terminate the current
3207 if (isInsideMacroInstantiation()) {
3212 // Otherwise, this .endmacro is a stray entry in the file; well formed
3213 // .endmacro directives are handled during the macro definition parsing.
3214 return TokError("unexpected '" + Directive + "' in file, "
3215 "no current macro definition");
3218 /// parseDirectivePurgeMacro
3220 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3222 if (parseIdentifier(Name))
3223 return TokError("expected identifier in '.purgem' directive");
3225 if (getLexer().isNot(AsmToken::EndOfStatement))
3226 return TokError("unexpected token in '.purgem' directive");
3228 if (!lookupMacro(Name))
3229 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3231 undefineMacro(Name);
3235 /// parseDirectiveBundleAlignMode
3236 /// ::= {.bundle_align_mode} expression
3237 bool AsmParser::parseDirectiveBundleAlignMode() {
3238 checkForValidSection();
3240 // Expect a single argument: an expression that evaluates to a constant
3241 // in the inclusive range 0-30.
3242 SMLoc ExprLoc = getLexer().getLoc();
3243 int64_t AlignSizePow2;
3244 if (parseAbsoluteExpression(AlignSizePow2))
3246 else if (getLexer().isNot(AsmToken::EndOfStatement))
3247 return TokError("unexpected token after expression in"
3248 " '.bundle_align_mode' directive");
3249 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3250 return Error(ExprLoc,
3251 "invalid bundle alignment size (expected between 0 and 30)");
3255 // Because of AlignSizePow2's verified range we can safely truncate it to
3257 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3261 /// parseDirectiveBundleLock
3262 /// ::= {.bundle_lock} [align_to_end]
3263 bool AsmParser::parseDirectiveBundleLock() {
3264 checkForValidSection();
3265 bool AlignToEnd = false;
3267 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3269 SMLoc Loc = getTok().getLoc();
3270 const char *kInvalidOptionError =
3271 "invalid option for '.bundle_lock' directive";
3273 if (parseIdentifier(Option))
3274 return Error(Loc, kInvalidOptionError);
3276 if (Option != "align_to_end")
3277 return Error(Loc, kInvalidOptionError);
3278 else if (getLexer().isNot(AsmToken::EndOfStatement))
3280 "unexpected token after '.bundle_lock' directive option");
3286 getStreamer().EmitBundleLock(AlignToEnd);
3290 /// parseDirectiveBundleLock
3291 /// ::= {.bundle_lock}
3292 bool AsmParser::parseDirectiveBundleUnlock() {
3293 checkForValidSection();
3295 if (getLexer().isNot(AsmToken::EndOfStatement))
3296 return TokError("unexpected token in '.bundle_unlock' directive");
3299 getStreamer().EmitBundleUnlock();
3303 /// parseDirectiveSpace
3304 /// ::= (.skip | .space) expression [ , expression ]
3305 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3306 checkForValidSection();
3309 if (parseAbsoluteExpression(NumBytes))
3312 int64_t FillExpr = 0;
3313 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3314 if (getLexer().isNot(AsmToken::Comma))
3315 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3318 if (parseAbsoluteExpression(FillExpr))
3321 if (getLexer().isNot(AsmToken::EndOfStatement))
3322 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3328 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3331 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3332 getStreamer().EmitFill(NumBytes, FillExpr);
3337 /// parseDirectiveLEB128
3338 /// ::= (.sleb128 | .uleb128) expression
3339 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3340 checkForValidSection();
3341 const MCExpr *Value;
3343 if (parseExpression(Value))
3346 if (getLexer().isNot(AsmToken::EndOfStatement))
3347 return TokError("unexpected token in directive");
3350 getStreamer().EmitSLEB128Value(Value);
3352 getStreamer().EmitULEB128Value(Value);
3357 /// parseDirectiveSymbolAttribute
3358 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3359 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3360 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3363 SMLoc Loc = getTok().getLoc();
3365 if (parseIdentifier(Name))
3366 return Error(Loc, "expected identifier in directive");
3368 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3370 // Assembler local symbols don't make any sense here. Complain loudly.
3371 if (Sym->isTemporary())
3372 return Error(Loc, "non-local symbol required in directive");
3374 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3375 return Error(Loc, "unable to emit symbol attribute");
3377 if (getLexer().is(AsmToken::EndOfStatement))
3380 if (getLexer().isNot(AsmToken::Comma))
3381 return TokError("unexpected token in directive");
3390 /// parseDirectiveComm
3391 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3392 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3393 checkForValidSection();
3395 SMLoc IDLoc = getLexer().getLoc();
3397 if (parseIdentifier(Name))
3398 return TokError("expected identifier in directive");
3400 // Handle the identifier as the key symbol.
3401 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3403 if (getLexer().isNot(AsmToken::Comma))
3404 return TokError("unexpected token in directive");
3408 SMLoc SizeLoc = getLexer().getLoc();
3409 if (parseAbsoluteExpression(Size))
3412 int64_t Pow2Alignment = 0;
3413 SMLoc Pow2AlignmentLoc;
3414 if (getLexer().is(AsmToken::Comma)) {
3416 Pow2AlignmentLoc = getLexer().getLoc();
3417 if (parseAbsoluteExpression(Pow2Alignment))
3420 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3421 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3422 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3424 // If this target takes alignments in bytes (not log) validate and convert.
3425 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3426 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3427 if (!isPowerOf2_64(Pow2Alignment))
3428 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3429 Pow2Alignment = Log2_64(Pow2Alignment);
3433 if (getLexer().isNot(AsmToken::EndOfStatement))
3434 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3438 // NOTE: a size of zero for a .comm should create a undefined symbol
3439 // but a size of .lcomm creates a bss symbol of size zero.
3441 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3442 "be less than zero");
3444 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3445 // may internally end up wanting an alignment in bytes.
3446 // FIXME: Diagnose overflow.
3447 if (Pow2Alignment < 0)
3448 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3449 "alignment, can't be less than zero");
3451 if (!Sym->isUndefined())
3452 return Error(IDLoc, "invalid symbol redefinition");
3454 // Create the Symbol as a common or local common with Size and Pow2Alignment
3456 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3460 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3464 /// parseDirectiveAbort
3465 /// ::= .abort [... message ...]
3466 bool AsmParser::parseDirectiveAbort() {
3467 // FIXME: Use loc from directive.
3468 SMLoc Loc = getLexer().getLoc();
3470 StringRef Str = parseStringToEndOfStatement();
3471 if (getLexer().isNot(AsmToken::EndOfStatement))
3472 return TokError("unexpected token in '.abort' directive");
3477 Error(Loc, ".abort detected. Assembly stopping.");
3479 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3480 // FIXME: Actually abort assembly here.
3485 /// parseDirectiveInclude
3486 /// ::= .include "filename"
3487 bool AsmParser::parseDirectiveInclude() {
3488 if (getLexer().isNot(AsmToken::String))
3489 return TokError("expected string in '.include' directive");
3491 // Allow the strings to have escaped octal character sequence.
3492 std::string Filename;
3493 if (parseEscapedString(Filename))
3495 SMLoc IncludeLoc = getLexer().getLoc();
3498 if (getLexer().isNot(AsmToken::EndOfStatement))
3499 return TokError("unexpected token in '.include' directive");
3501 // Attempt to switch the lexer to the included file before consuming the end
3502 // of statement to avoid losing it when we switch.
3503 if (enterIncludeFile(Filename)) {
3504 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3511 /// parseDirectiveIncbin
3512 /// ::= .incbin "filename"
3513 bool AsmParser::parseDirectiveIncbin() {
3514 if (getLexer().isNot(AsmToken::String))
3515 return TokError("expected string in '.incbin' directive");
3517 // Allow the strings to have escaped octal character sequence.
3518 std::string Filename;
3519 if (parseEscapedString(Filename))
3521 SMLoc IncbinLoc = getLexer().getLoc();
3524 if (getLexer().isNot(AsmToken::EndOfStatement))
3525 return TokError("unexpected token in '.incbin' directive");
3527 // Attempt to process the included file.
3528 if (processIncbinFile(Filename)) {
3529 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3536 /// parseDirectiveIf
3537 /// ::= .if expression
3538 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3539 TheCondStack.push_back(TheCondState);
3540 TheCondState.TheCond = AsmCond::IfCond;
3541 if (TheCondState.Ignore) {
3542 eatToEndOfStatement();
3545 if (parseAbsoluteExpression(ExprValue))
3548 if (getLexer().isNot(AsmToken::EndOfStatement))
3549 return TokError("unexpected token in '.if' directive");
3553 TheCondState.CondMet = ExprValue;
3554 TheCondState.Ignore = !TheCondState.CondMet;
3560 /// parseDirectiveIfb
3562 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3563 TheCondStack.push_back(TheCondState);
3564 TheCondState.TheCond = AsmCond::IfCond;
3566 if (TheCondState.Ignore) {
3567 eatToEndOfStatement();
3569 StringRef Str = parseStringToEndOfStatement();
3571 if (getLexer().isNot(AsmToken::EndOfStatement))
3572 return TokError("unexpected token in '.ifb' directive");
3576 TheCondState.CondMet = ExpectBlank == Str.empty();
3577 TheCondState.Ignore = !TheCondState.CondMet;
3583 /// parseDirectiveIfc
3584 /// ::= .ifc string1, string2
3585 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3586 TheCondStack.push_back(TheCondState);
3587 TheCondState.TheCond = AsmCond::IfCond;
3589 if (TheCondState.Ignore) {
3590 eatToEndOfStatement();
3592 StringRef Str1 = parseStringToComma();
3594 if (getLexer().isNot(AsmToken::Comma))
3595 return TokError("unexpected token in '.ifc' directive");
3599 StringRef Str2 = parseStringToEndOfStatement();
3601 if (getLexer().isNot(AsmToken::EndOfStatement))
3602 return TokError("unexpected token in '.ifc' directive");
3606 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3607 TheCondState.Ignore = !TheCondState.CondMet;
3613 /// parseDirectiveIfdef
3614 /// ::= .ifdef symbol
3615 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3617 TheCondStack.push_back(TheCondState);
3618 TheCondState.TheCond = AsmCond::IfCond;
3620 if (TheCondState.Ignore) {
3621 eatToEndOfStatement();
3623 if (parseIdentifier(Name))
3624 return TokError("expected identifier after '.ifdef'");
3628 MCSymbol *Sym = getContext().LookupSymbol(Name);
3631 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3633 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3634 TheCondState.Ignore = !TheCondState.CondMet;
3640 /// parseDirectiveElseIf
3641 /// ::= .elseif expression
3642 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3643 if (TheCondState.TheCond != AsmCond::IfCond &&
3644 TheCondState.TheCond != AsmCond::ElseIfCond)
3645 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3647 TheCondState.TheCond = AsmCond::ElseIfCond;
3649 bool LastIgnoreState = false;
3650 if (!TheCondStack.empty())
3651 LastIgnoreState = TheCondStack.back().Ignore;
3652 if (LastIgnoreState || TheCondState.CondMet) {
3653 TheCondState.Ignore = true;
3654 eatToEndOfStatement();
3657 if (parseAbsoluteExpression(ExprValue))
3660 if (getLexer().isNot(AsmToken::EndOfStatement))
3661 return TokError("unexpected token in '.elseif' directive");
3664 TheCondState.CondMet = ExprValue;
3665 TheCondState.Ignore = !TheCondState.CondMet;
3671 /// parseDirectiveElse
3673 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3674 if (getLexer().isNot(AsmToken::EndOfStatement))
3675 return TokError("unexpected token in '.else' directive");
3679 if (TheCondState.TheCond != AsmCond::IfCond &&
3680 TheCondState.TheCond != AsmCond::ElseIfCond)
3681 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3683 TheCondState.TheCond = AsmCond::ElseCond;
3684 bool LastIgnoreState = false;
3685 if (!TheCondStack.empty())
3686 LastIgnoreState = TheCondStack.back().Ignore;
3687 if (LastIgnoreState || TheCondState.CondMet)
3688 TheCondState.Ignore = true;
3690 TheCondState.Ignore = false;
3695 /// parseDirectiveEndIf
3697 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3698 if (getLexer().isNot(AsmToken::EndOfStatement))
3699 return TokError("unexpected token in '.endif' directive");
3703 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3704 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3706 if (!TheCondStack.empty()) {
3707 TheCondState = TheCondStack.back();
3708 TheCondStack.pop_back();
3714 void AsmParser::initializeDirectiveKindMap() {
3715 DirectiveKindMap[".set"] = DK_SET;
3716 DirectiveKindMap[".equ"] = DK_EQU;
3717 DirectiveKindMap[".equiv"] = DK_EQUIV;
3718 DirectiveKindMap[".ascii"] = DK_ASCII;
3719 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3720 DirectiveKindMap[".string"] = DK_STRING;
3721 DirectiveKindMap[".byte"] = DK_BYTE;
3722 DirectiveKindMap[".short"] = DK_SHORT;
3723 DirectiveKindMap[".value"] = DK_VALUE;
3724 DirectiveKindMap[".2byte"] = DK_2BYTE;
3725 DirectiveKindMap[".long"] = DK_LONG;
3726 DirectiveKindMap[".int"] = DK_INT;
3727 DirectiveKindMap[".4byte"] = DK_4BYTE;
3728 DirectiveKindMap[".quad"] = DK_QUAD;
3729 DirectiveKindMap[".8byte"] = DK_8BYTE;
3730 DirectiveKindMap[".single"] = DK_SINGLE;
3731 DirectiveKindMap[".float"] = DK_FLOAT;
3732 DirectiveKindMap[".double"] = DK_DOUBLE;
3733 DirectiveKindMap[".align"] = DK_ALIGN;
3734 DirectiveKindMap[".align32"] = DK_ALIGN32;
3735 DirectiveKindMap[".balign"] = DK_BALIGN;
3736 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3737 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3738 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3739 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3740 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3741 DirectiveKindMap[".org"] = DK_ORG;
3742 DirectiveKindMap[".fill"] = DK_FILL;
3743 DirectiveKindMap[".zero"] = DK_ZERO;
3744 DirectiveKindMap[".extern"] = DK_EXTERN;
3745 DirectiveKindMap[".globl"] = DK_GLOBL;
3746 DirectiveKindMap[".global"] = DK_GLOBAL;
3747 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3748 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3749 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3750 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3751 DirectiveKindMap[".reference"] = DK_REFERENCE;
3752 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3753 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3754 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3755 DirectiveKindMap[".comm"] = DK_COMM;
3756 DirectiveKindMap[".common"] = DK_COMMON;
3757 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3758 DirectiveKindMap[".abort"] = DK_ABORT;
3759 DirectiveKindMap[".include"] = DK_INCLUDE;
3760 DirectiveKindMap[".incbin"] = DK_INCBIN;
3761 DirectiveKindMap[".code16"] = DK_CODE16;
3762 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3763 DirectiveKindMap[".rept"] = DK_REPT;
3764 DirectiveKindMap[".irp"] = DK_IRP;
3765 DirectiveKindMap[".irpc"] = DK_IRPC;
3766 DirectiveKindMap[".endr"] = DK_ENDR;
3767 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3768 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3769 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3770 DirectiveKindMap[".if"] = DK_IF;
3771 DirectiveKindMap[".ifb"] = DK_IFB;
3772 DirectiveKindMap[".ifnb"] = DK_IFNB;
3773 DirectiveKindMap[".ifc"] = DK_IFC;
3774 DirectiveKindMap[".ifnc"] = DK_IFNC;
3775 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3776 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3777 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3778 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3779 DirectiveKindMap[".else"] = DK_ELSE;
3780 DirectiveKindMap[".endif"] = DK_ENDIF;
3781 DirectiveKindMap[".skip"] = DK_SKIP;
3782 DirectiveKindMap[".space"] = DK_SPACE;
3783 DirectiveKindMap[".file"] = DK_FILE;
3784 DirectiveKindMap[".line"] = DK_LINE;
3785 DirectiveKindMap[".loc"] = DK_LOC;
3786 DirectiveKindMap[".stabs"] = DK_STABS;
3787 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3788 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3789 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3790 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3791 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3792 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3793 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3794 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3795 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3796 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3797 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3798 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3799 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3800 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3801 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3802 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3803 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3804 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3805 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3806 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3807 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3808 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3809 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3810 DirectiveKindMap[".macro"] = DK_MACRO;
3811 DirectiveKindMap[".endm"] = DK_ENDM;
3812 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3813 DirectiveKindMap[".purgem"] = DK_PURGEM;
3816 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3817 AsmToken EndToken, StartToken = getTok();
3819 unsigned NestLevel = 0;
3821 // Check whether we have reached the end of the file.
3822 if (getLexer().is(AsmToken::Eof)) {
3823 Error(DirectiveLoc, "no matching '.endr' in definition");
3827 if (Lexer.is(AsmToken::Identifier) &&
3828 (getTok().getIdentifier() == ".rept")) {
3832 // Otherwise, check whether we have reached the .endr.
3833 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3834 if (NestLevel == 0) {
3835 EndToken = getTok();
3837 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3838 TokError("unexpected token in '.endr' directive");
3846 // Otherwise, scan till the end of the statement.
3847 eatToEndOfStatement();
3850 const char *BodyStart = StartToken.getLoc().getPointer();
3851 const char *BodyEnd = EndToken.getLoc().getPointer();
3852 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3854 // We Are Anonymous.
3856 MCAsmMacroParameters Parameters;
3857 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3858 return &MacroLikeBodies.back();
3861 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3862 raw_svector_ostream &OS) {
3865 MemoryBuffer *Instantiation =
3866 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3868 // Create the macro instantiation object and add to the current macro
3869 // instantiation stack.
3870 MacroInstantiation *MI = new MacroInstantiation(
3871 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3872 ActiveMacros.push_back(MI);
3874 // Jump to the macro instantiation and prime the lexer.
3875 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3876 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3880 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
3882 if (parseAbsoluteExpression(Count))
3883 return TokError("unexpected token in '.rept' directive");
3886 return TokError("Count is negative");
3888 if (Lexer.isNot(AsmToken::EndOfStatement))
3889 return TokError("unexpected token in '.rept' directive");
3891 // Eat the end of statement.
3894 // Lex the rept definition.
3895 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3899 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3900 // to hold the macro body with substitutions.
3901 SmallString<256> Buf;
3902 MCAsmMacroParameters Parameters;
3903 MCAsmMacroArguments A;
3904 raw_svector_ostream OS(Buf);
3906 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3909 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3914 /// parseDirectiveIrp
3915 /// ::= .irp symbol,values
3916 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
3917 MCAsmMacroParameters Parameters;
3918 MCAsmMacroParameter Parameter;
3920 if (parseIdentifier(Parameter.first))
3921 return TokError("expected identifier in '.irp' directive");
3923 Parameters.push_back(Parameter);
3925 if (Lexer.isNot(AsmToken::Comma))
3926 return TokError("expected comma in '.irp' directive");
3930 MCAsmMacroArguments A;
3931 if (parseMacroArguments(0, A))
3934 // Eat the end of statement.
3937 // Lex the irp definition.
3938 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3942 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3943 // to hold the macro body with substitutions.
3944 SmallString<256> Buf;
3945 raw_svector_ostream OS(Buf);
3947 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3948 MCAsmMacroArguments Args;
3951 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3955 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3960 /// parseDirectiveIrpc
3961 /// ::= .irpc symbol,values
3962 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
3963 MCAsmMacroParameters Parameters;
3964 MCAsmMacroParameter Parameter;
3966 if (parseIdentifier(Parameter.first))
3967 return TokError("expected identifier in '.irpc' directive");
3969 Parameters.push_back(Parameter);
3971 if (Lexer.isNot(AsmToken::Comma))
3972 return TokError("expected comma in '.irpc' directive");
3976 MCAsmMacroArguments A;
3977 if (parseMacroArguments(0, A))
3980 if (A.size() != 1 || A.front().size() != 1)
3981 return TokError("unexpected token in '.irpc' directive");
3983 // Eat the end of statement.
3986 // Lex the irpc definition.
3987 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3991 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3992 // to hold the macro body with substitutions.
3993 SmallString<256> Buf;
3994 raw_svector_ostream OS(Buf);
3996 StringRef Values = A.front().front().getString();
3997 std::size_t I, End = Values.size();
3998 for (I = 0; I < End; ++I) {
3999 MCAsmMacroArgument Arg;
4000 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4002 MCAsmMacroArguments Args;
4003 Args.push_back(Arg);
4005 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4009 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4014 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4015 if (ActiveMacros.empty())
4016 return TokError("unmatched '.endr' directive");
4018 // The only .repl that should get here are the ones created by
4019 // instantiateMacroLikeBody.
4020 assert(getLexer().is(AsmToken::EndOfStatement));
4026 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4028 const MCExpr *Value;
4029 SMLoc ExprLoc = getLexer().getLoc();
4030 if (parseExpression(Value))
4032 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4034 return Error(ExprLoc, "unexpected expression in _emit");
4035 uint64_t IntValue = MCE->getValue();
4036 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4037 return Error(ExprLoc, "literal value out of range for directive");
4039 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4043 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4044 const MCExpr *Value;
4045 SMLoc ExprLoc = getLexer().getLoc();
4046 if (parseExpression(Value))
4048 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4050 return Error(ExprLoc, "unexpected expression in align");
4051 uint64_t IntValue = MCE->getValue();
4052 if (!isPowerOf2_64(IntValue))
4053 return Error(ExprLoc, "literal value not a power of two greater then zero");
4055 Info.AsmRewrites->push_back(
4056 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4060 // We are comparing pointers, but the pointers are relative to a single string.
4061 // Thus, this should always be deterministic.
4062 static int rewritesSort(const void *A, const void *B) {
4063 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4064 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
4065 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4067 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4070 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4071 // rewrite to the same location. Make sure the SizeDirective rewrite is
4072 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4073 // ensures the sort algorithm is stable.
4074 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4075 AsmRewritePrecedence[AsmRewriteB->Kind])
4078 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4079 AsmRewritePrecedence[AsmRewriteB->Kind])
4081 llvm_unreachable("Unstable rewrite sort.");
4084 bool AsmParser::parseMSInlineAsm(
4085 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4086 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4087 SmallVectorImpl<std::string> &Constraints,
4088 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4089 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4090 SmallVector<void *, 4> InputDecls;
4091 SmallVector<void *, 4> OutputDecls;
4092 SmallVector<bool, 4> InputDeclsAddressOf;
4093 SmallVector<bool, 4> OutputDeclsAddressOf;
4094 SmallVector<std::string, 4> InputConstraints;
4095 SmallVector<std::string, 4> OutputConstraints;
4096 SmallVector<unsigned, 4> ClobberRegs;
4098 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4103 // While we have input, parse each statement.
4104 unsigned InputIdx = 0;
4105 unsigned OutputIdx = 0;
4106 while (getLexer().isNot(AsmToken::Eof)) {
4107 ParseStatementInfo Info(&AsmStrRewrites);
4108 if (parseStatement(Info))
4111 if (Info.ParseError)
4114 if (Info.Opcode == ~0U)
4117 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4119 // Build the list of clobbers, outputs and inputs.
4120 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4121 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4124 if (Operand->isImm())
4127 // Register operand.
4128 if (Operand->isReg() && !Operand->needAddressOf()) {
4129 unsigned NumDefs = Desc.getNumDefs();
4131 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4132 ClobberRegs.push_back(Operand->getReg());
4136 // Expr/Input or Output.
4137 StringRef SymName = Operand->getSymName();
4138 if (SymName.empty())
4141 void *OpDecl = Operand->getOpDecl();
4145 bool isOutput = (i == 1) && Desc.mayStore();
4146 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4149 OutputDecls.push_back(OpDecl);
4150 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4151 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4152 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4154 InputDecls.push_back(OpDecl);
4155 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4156 InputConstraints.push_back(Operand->getConstraint().str());
4157 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4162 // Set the number of Outputs and Inputs.
4163 NumOutputs = OutputDecls.size();
4164 NumInputs = InputDecls.size();
4166 // Set the unique clobbers.
4167 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4168 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4170 Clobbers.assign(ClobberRegs.size(), std::string());
4171 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4172 raw_string_ostream OS(Clobbers[I]);
4173 IP->printRegName(OS, ClobberRegs[I]);
4176 // Merge the various outputs and inputs. Output are expected first.
4177 if (NumOutputs || NumInputs) {
4178 unsigned NumExprs = NumOutputs + NumInputs;
4179 OpDecls.resize(NumExprs);
4180 Constraints.resize(NumExprs);
4181 for (unsigned i = 0; i < NumOutputs; ++i) {
4182 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4183 Constraints[i] = OutputConstraints[i];
4185 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4186 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4187 Constraints[j] = InputConstraints[i];
4191 // Build the IR assembly string.
4192 std::string AsmStringIR;
4193 raw_string_ostream OS(AsmStringIR);
4194 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4195 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4196 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4197 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4198 E = AsmStrRewrites.end();
4200 AsmRewriteKind Kind = (*I).Kind;
4201 if (Kind == AOK_Delete)
4204 const char *Loc = (*I).Loc.getPointer();
4205 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4207 // Emit everything up to the immediate/expression.
4208 unsigned Len = Loc - AsmStart;
4210 OS << StringRef(AsmStart, Len);
4212 // Skip the original expression.
4213 if (Kind == AOK_Skip) {
4214 AsmStart = Loc + (*I).Len;
4218 unsigned AdditionalSkip = 0;
4219 // Rewrite expressions in $N notation.
4224 OS << "$$" << (*I).Val;
4230 OS << '$' << InputIdx++;
4233 OS << '$' << OutputIdx++;
4235 case AOK_SizeDirective:
4238 case 8: OS << "byte ptr "; break;
4239 case 16: OS << "word ptr "; break;
4240 case 32: OS << "dword ptr "; break;
4241 case 64: OS << "qword ptr "; break;
4242 case 80: OS << "xword ptr "; break;
4243 case 128: OS << "xmmword ptr "; break;
4244 case 256: OS << "ymmword ptr "; break;
4251 unsigned Val = (*I).Val;
4252 OS << ".align " << Val;
4254 // Skip the original immediate.
4255 assert(Val < 10 && "Expected alignment less then 2^10.");
4256 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4259 case AOK_DotOperator:
4264 // Skip the original expression.
4265 AsmStart = Loc + (*I).Len + AdditionalSkip;
4268 // Emit the remainder of the asm string.
4269 if (AsmStart != AsmEnd)
4270 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4272 AsmString = OS.str();
4276 /// \brief Create an MCAsmParser instance.
4277 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4278 MCStreamer &Out, const MCAsmInfo &MAI) {
4279 return new AsmParser(SM, C, Out, MAI);