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 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
100 /// Opcode - The opcode from the last parsed instruction.
103 /// Error - 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 /// ExtensionDirectiveMap - 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 /// MacroMap - Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// Boolean tracking whether macro substitution is enabled.
153 unsigned MacrosEnabledFlag : 1;
155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
167 /// IsDarwin - is Darwin compatibility enabled?
170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
171 bool ParsingInlineAsm;
174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
175 const MCAsmInfo &MAI);
176 virtual ~AsmParser();
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
180 virtual void addDirectiveHandler(StringRef Directive,
181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
186 /// @name MCAsmParser Interface
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
193 virtual unsigned getAssemblerDialect() {
194 if (AssemblerDialect == ~0U)
195 return MAI.getAssemblerDialect();
197 return AssemblerDialect;
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
203 virtual bool Warning(SMLoc L, const Twine &Msg,
204 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
208 virtual const AsmToken &Lex();
210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
213 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
214 unsigned &NumOutputs, unsigned &NumInputs,
215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
216 SmallVectorImpl<std::string> &Constraints,
217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
222 bool parseExpression(const MCExpr *&Res);
223 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
225 virtual bool parseAbsoluteExpression(int64_t &Res);
227 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
228 /// and set \p Res to the identifier contents.
229 virtual bool parseIdentifier(StringRef &Res);
230 virtual void eatToEndOfStatement();
232 virtual void checkForValidSection();
237 bool ParseStatement(ParseStatementInfo &Info);
238 void EatToEndOfLine();
239 bool ParseCppHashLineFilenameComment(const SMLoc &L);
241 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
242 MCAsmMacroParameters Parameters);
243 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
244 const MCAsmMacroParameters &Parameters,
245 const MCAsmMacroArguments &A,
248 /// \brief Are macros enabled in the parser?
249 bool MacrosEnabled() {return MacrosEnabledFlag;}
251 /// \brief Control a flag in the parser that enables or disables macros.
252 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
254 /// \brief Lookup a previously defined macro.
255 /// \param Name Macro name.
256 /// \returns Pointer to macro. NULL if no such macro was defined.
257 const MCAsmMacro* LookupMacro(StringRef Name);
259 /// \brief Define a new macro with the given name and information.
260 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
262 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
263 void UndefineMacro(StringRef Name);
265 /// \brief Are we inside a macro instantiation?
266 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
268 /// \brief Handle entry to macro instantiation.
270 /// \param M The macro.
271 /// \param NameLoc Instantiation location.
272 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
274 /// \brief Handle exit from macro instantiation.
275 void HandleMacroExit();
277 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
278 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
279 /// correct delimiter by the method.
280 bool ParseMacroArgument(MCAsmMacroArgument &MA,
281 AsmToken::TokenKind &ArgumentDelimiter);
283 /// \brief Parse all macro arguments for a given macro.
284 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
286 void PrintMacroInstantiations();
287 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
288 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
289 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
291 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
293 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
294 bool EnterIncludeFile(const std::string &Filename);
295 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
296 /// This returns true on failure.
297 bool ProcessIncbinFile(const std::string &Filename);
299 /// \brief Reset the current lexer position to that given by \p Loc. The
300 /// current token is not set; clients should ensure Lex() is called
303 /// \param InBuffer If not -1, should be the known buffer id that contains the
305 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
307 /// \brief Parse up to the end of statement and a return the contents from the
308 /// current token until the end of the statement; the current token on exit
309 /// will be either the EndOfStatement or EOF.
310 virtual StringRef parseStringToEndOfStatement();
312 /// \brief Parse until the end of a statement or a comma is encountered,
313 /// return the contents from the current token up to the end or comma.
314 StringRef ParseStringToComma();
316 bool ParseAssignment(StringRef Name, bool allow_redef,
317 bool NoDeadStrip = false);
319 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
322 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
324 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
326 // Generic (target and platform independent) directive parsing.
328 DK_NO_DIRECTIVE, // Placeholder
329 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
330 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
331 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
332 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
333 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
334 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
335 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
336 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
337 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
338 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
339 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
340 DK_ELSEIF, DK_ELSE, DK_ENDIF,
341 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
342 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
343 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
344 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
345 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
346 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
348 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
349 DK_SLEB128, DK_ULEB128
352 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
353 /// directives parsed by this class.
354 StringMap<DirectiveKind> DirectiveKindMap;
356 // ".ascii", ".asciz", ".string"
357 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
358 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
359 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
360 bool ParseDirectiveFill(); // ".fill"
361 bool ParseDirectiveZero(); // ".zero"
362 // ".set", ".equ", ".equiv"
363 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
364 bool ParseDirectiveOrg(); // ".org"
365 // ".align{,32}", ".p2align{,w,l}"
366 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
368 // ".file", ".line", ".loc", ".stabs"
369 bool ParseDirectiveFile(SMLoc DirectiveLoc);
370 bool ParseDirectiveLine();
371 bool ParseDirectiveLoc();
372 bool ParseDirectiveStabs();
375 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
376 bool ParseDirectiveCFISections();
377 bool ParseDirectiveCFIStartProc();
378 bool ParseDirectiveCFIEndProc();
379 bool ParseDirectiveCFIDefCfaOffset();
380 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIAdjustCfaOffset();
382 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
386 bool ParseDirectiveCFIRememberState();
387 bool ParseDirectiveCFIRestoreState();
388 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIEscape();
391 bool ParseDirectiveCFISignalFrame();
392 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
395 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
396 bool ParseDirectiveEndMacro(StringRef Directive);
397 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
398 bool ParseDirectiveMacrosOnOff(StringRef Directive);
400 // ".bundle_align_mode"
401 bool ParseDirectiveBundleAlignMode();
403 bool ParseDirectiveBundleLock();
405 bool ParseDirectiveBundleUnlock();
408 bool ParseDirectiveSpace(StringRef IDVal);
410 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
411 bool ParseDirectiveLEB128(bool Signed);
413 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
414 /// accepts a single symbol (which should be a label or an external).
415 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
417 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
419 bool ParseDirectiveAbort(); // ".abort"
420 bool ParseDirectiveInclude(); // ".include"
421 bool ParseDirectiveIncbin(); // ".incbin"
423 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
424 // ".ifb" or ".ifnb", depending on ExpectBlank.
425 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
426 // ".ifc" or ".ifnc", depending on ExpectEqual.
427 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
428 // ".ifdef" or ".ifndef", depending on expect_defined
429 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
430 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
431 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
432 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
433 virtual bool parseEscapedString(std::string &Data);
435 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
436 MCSymbolRefExpr::VariantKind Variant);
438 // Macro-like directives
439 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
440 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
441 raw_svector_ostream &OS);
442 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
443 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
444 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
445 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
447 // "_emit" or "__emit"
448 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
452 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
454 void initializeDirectiveKindMap();
460 extern MCAsmParserExtension *createDarwinAsmParser();
461 extern MCAsmParserExtension *createELFAsmParser();
462 extern MCAsmParserExtension *createCOFFAsmParser();
466 enum { DEFAULT_ADDRSPACE = 0 };
468 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
469 MCStreamer &_Out, const MCAsmInfo &_MAI)
470 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
472 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
473 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
474 // Save the old handler.
475 SavedDiagHandler = SrcMgr.getDiagHandler();
476 SavedDiagContext = SrcMgr.getDiagContext();
477 // Set our own handler which calls the saved handler.
478 SrcMgr.setDiagHandler(DiagHandler, this);
479 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
481 // Initialize the platform / file format parser.
483 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
485 if (_MAI.hasMicrosoftFastStdCallMangling()) {
486 PlatformParser = createCOFFAsmParser();
487 PlatformParser->Initialize(*this);
488 } else if (_MAI.hasSubsectionsViaSymbols()) {
489 PlatformParser = createDarwinAsmParser();
490 PlatformParser->Initialize(*this);
493 PlatformParser = createELFAsmParser();
494 PlatformParser->Initialize(*this);
497 initializeDirectiveKindMap();
500 AsmParser::~AsmParser() {
501 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
503 // Destroy any macros.
504 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
505 ie = MacroMap.end(); it != ie; ++it)
506 delete it->getValue();
508 delete PlatformParser;
511 void AsmParser::PrintMacroInstantiations() {
512 // Print the active macro instantiation stack.
513 for (std::vector<MacroInstantiation*>::const_reverse_iterator
514 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
515 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
516 "while in macro instantiation");
519 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
520 if (FatalAssemblerWarnings)
521 return Error(L, Msg, Ranges);
522 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
523 PrintMacroInstantiations();
527 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
529 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
530 PrintMacroInstantiations();
534 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
535 std::string IncludedFile;
536 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
542 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
547 /// Process the specified .incbin file by seaching for it in the include paths
548 /// then just emitting the byte contents of the file to the streamer. This
549 /// returns true on failure.
550 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
551 std::string IncludedFile;
552 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
556 // Pick up the bytes from the file and emit them.
557 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
562 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
563 if (InBuffer != -1) {
564 CurBuffer = InBuffer;
566 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
571 const AsmToken &AsmParser::Lex() {
572 const AsmToken *tok = &Lexer.Lex();
574 if (tok->is(AsmToken::Eof)) {
575 // If this is the end of an included file, pop the parent file off the
577 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
578 if (ParentIncludeLoc != SMLoc()) {
579 JumpToLoc(ParentIncludeLoc);
584 if (tok->is(AsmToken::Error))
585 Error(Lexer.getErrLoc(), Lexer.getErr());
590 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
591 // Create the initial section, if requested.
592 if (!NoInitialTextSection)
599 AsmCond StartingCondState = TheCondState;
601 // If we are generating dwarf for assembly source files save the initial text
602 // section and generate a .file directive.
603 if (getContext().getGenDwarfForAssembly()) {
604 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
605 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
606 getStreamer().EmitLabel(SectionStartSym);
607 getContext().setGenDwarfSectionStartSym(SectionStartSym);
608 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
610 getContext().getMainFileName());
613 // While we have input, parse each statement.
614 while (Lexer.isNot(AsmToken::Eof)) {
615 ParseStatementInfo Info;
616 if (!ParseStatement(Info)) continue;
618 // We had an error, validate that one was emitted and recover by skipping to
620 assert(HadError && "Parse statement returned an error, but none emitted!");
621 eatToEndOfStatement();
624 if (TheCondState.TheCond != StartingCondState.TheCond ||
625 TheCondState.Ignore != StartingCondState.Ignore)
626 return TokError("unmatched .ifs or .elses");
628 // Check to see there are no empty DwarfFile slots.
629 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
630 getContext().getMCDwarfFiles();
631 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
632 if (!MCDwarfFiles[i])
633 TokError("unassigned file number: " + Twine(i) + " for .file directives");
636 // Check to see that all assembler local symbols were actually defined.
637 // Targets that don't do subsections via symbols may not want this, though,
638 // so conservatively exclude them. Only do this if we're finalizing, though,
639 // as otherwise we won't necessarilly have seen everything yet.
640 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
641 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
642 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
645 MCSymbol *Sym = i->getValue();
646 // Variable symbols may not be marked as defined, so check those
647 // explicitly. If we know it's a variable, we have a definition for
648 // the purposes of this check.
649 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
650 // FIXME: We would really like to refer back to where the symbol was
651 // first referenced for a source location. We need to add something
652 // to track that. Currently, we just point to the end of the file.
653 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
654 "assembler local symbol '" + Sym->getName() +
660 // Finalize the output stream if there are no errors and if the client wants
662 if (!HadError && !NoFinalize)
668 void AsmParser::checkForValidSection() {
669 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
670 TokError("expected section directive before assembly directive");
671 Out.InitToTextSection();
675 /// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
676 void AsmParser::eatToEndOfStatement() {
677 while (Lexer.isNot(AsmToken::EndOfStatement) &&
678 Lexer.isNot(AsmToken::Eof))
682 if (Lexer.is(AsmToken::EndOfStatement))
686 StringRef AsmParser::parseStringToEndOfStatement() {
687 const char *Start = getTok().getLoc().getPointer();
689 while (Lexer.isNot(AsmToken::EndOfStatement) &&
690 Lexer.isNot(AsmToken::Eof))
693 const char *End = getTok().getLoc().getPointer();
694 return StringRef(Start, End - Start);
697 StringRef AsmParser::ParseStringToComma() {
698 const char *Start = getTok().getLoc().getPointer();
700 while (Lexer.isNot(AsmToken::EndOfStatement) &&
701 Lexer.isNot(AsmToken::Comma) &&
702 Lexer.isNot(AsmToken::Eof))
705 const char *End = getTok().getLoc().getPointer();
706 return StringRef(Start, End - Start);
709 /// ParseParenExpr - Parse a paren expression and return it.
710 /// NOTE: This assumes the leading '(' has already been consumed.
712 /// parenexpr ::= expr)
714 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
715 if (parseExpression(Res)) return true;
716 if (Lexer.isNot(AsmToken::RParen))
717 return TokError("expected ')' in parentheses expression");
718 EndLoc = Lexer.getTok().getEndLoc();
723 /// ParseBracketExpr - Parse a bracket expression and return it.
724 /// NOTE: This assumes the leading '[' has already been consumed.
726 /// bracketexpr ::= expr]
728 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
729 if (parseExpression(Res)) return true;
730 if (Lexer.isNot(AsmToken::RBrac))
731 return TokError("expected ']' in brackets expression");
732 EndLoc = Lexer.getTok().getEndLoc();
737 /// ParsePrimaryExpr - Parse a primary expression and return it.
738 /// primaryexpr ::= (parenexpr
739 /// primaryexpr ::= symbol
740 /// primaryexpr ::= number
741 /// primaryexpr ::= '.'
742 /// primaryexpr ::= ~,+,- primaryexpr
743 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
744 SMLoc FirstTokenLoc = getLexer().getLoc();
745 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
746 switch (FirstTokenKind) {
748 return TokError("unknown token in expression");
749 // If we have an error assume that we've already handled it.
750 case AsmToken::Error:
752 case AsmToken::Exclaim:
753 Lex(); // Eat the operator.
754 if (ParsePrimaryExpr(Res, EndLoc))
756 Res = MCUnaryExpr::CreateLNot(Res, getContext());
758 case AsmToken::Dollar:
759 case AsmToken::String:
760 case AsmToken::Identifier: {
761 StringRef Identifier;
762 if (parseIdentifier(Identifier)) {
763 if (FirstTokenKind == AsmToken::Dollar)
764 return Error(FirstTokenLoc, "invalid token in expression");
768 EndLoc = SMLoc::getFromPointer(Identifier.end());
770 // This is a symbol reference.
771 std::pair<StringRef, StringRef> Split = Identifier.split('@');
772 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
774 // Lookup the symbol variant if used.
775 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
776 if (Split.first.size() != Identifier.size()) {
777 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
778 if (Variant == MCSymbolRefExpr::VK_Invalid) {
779 Variant = MCSymbolRefExpr::VK_None;
780 return TokError("invalid variant '" + Split.second + "'");
784 // If this is an absolute variable reference, substitute it now to preserve
785 // semantics in the face of reassignment.
786 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
788 return Error(EndLoc, "unexpected modifier on variable reference");
790 Res = Sym->getVariableValue();
794 // Otherwise create a symbol ref.
795 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
798 case AsmToken::Integer: {
799 SMLoc Loc = getTok().getLoc();
800 int64_t IntVal = getTok().getIntVal();
801 Res = MCConstantExpr::Create(IntVal, getContext());
802 EndLoc = Lexer.getTok().getEndLoc();
804 // Look for 'b' or 'f' following an Integer as a directional label
805 if (Lexer.getKind() == AsmToken::Identifier) {
806 StringRef IDVal = getTok().getString();
807 if (IDVal == "f" || IDVal == "b"){
808 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
809 IDVal == "f" ? 1 : 0);
810 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
812 if (IDVal == "b" && Sym->isUndefined())
813 return Error(Loc, "invalid reference to undefined symbol");
814 EndLoc = Lexer.getTok().getEndLoc();
815 Lex(); // Eat identifier.
820 case AsmToken::Real: {
821 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
822 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
823 Res = MCConstantExpr::Create(IntVal, getContext());
824 EndLoc = Lexer.getTok().getEndLoc();
828 case AsmToken::Dot: {
829 // This is a '.' reference, which references the current PC. Emit a
830 // temporary label to the streamer and refer to it.
831 MCSymbol *Sym = Ctx.CreateTempSymbol();
833 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
834 EndLoc = Lexer.getTok().getEndLoc();
835 Lex(); // Eat identifier.
838 case AsmToken::LParen:
839 Lex(); // Eat the '('.
840 return ParseParenExpr(Res, EndLoc);
841 case AsmToken::LBrac:
842 if (!PlatformParser->HasBracketExpressions())
843 return TokError("brackets expression not supported on this target");
844 Lex(); // Eat the '['.
845 return ParseBracketExpr(Res, EndLoc);
846 case AsmToken::Minus:
847 Lex(); // Eat the operator.
848 if (ParsePrimaryExpr(Res, EndLoc))
850 Res = MCUnaryExpr::CreateMinus(Res, getContext());
853 Lex(); // Eat the operator.
854 if (ParsePrimaryExpr(Res, EndLoc))
856 Res = MCUnaryExpr::CreatePlus(Res, getContext());
858 case AsmToken::Tilde:
859 Lex(); // Eat the operator.
860 if (ParsePrimaryExpr(Res, EndLoc))
862 Res = MCUnaryExpr::CreateNot(Res, getContext());
867 bool AsmParser::parseExpression(const MCExpr *&Res) {
869 return parseExpression(Res, EndLoc);
873 AsmParser::ApplyModifierToExpr(const MCExpr *E,
874 MCSymbolRefExpr::VariantKind Variant) {
875 // Recurse over the given expression, rebuilding it to apply the given variant
876 // if there is exactly one symbol.
877 switch (E->getKind()) {
879 case MCExpr::Constant:
882 case MCExpr::SymbolRef: {
883 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
885 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
886 TokError("invalid variant on expression '" +
887 getTok().getIdentifier() + "' (already modified)");
891 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
894 case MCExpr::Unary: {
895 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
896 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
899 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
902 case MCExpr::Binary: {
903 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
904 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
905 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
910 if (!LHS) LHS = BE->getLHS();
911 if (!RHS) RHS = BE->getRHS();
913 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
917 llvm_unreachable("Invalid expression kind!");
920 /// parseExpression - Parse an expression and return it.
922 /// expr ::= expr &&,|| expr -> lowest.
923 /// expr ::= expr |,^,&,! expr
924 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
925 /// expr ::= expr <<,>> expr
926 /// expr ::= expr +,- expr
927 /// expr ::= expr *,/,% expr -> highest.
928 /// expr ::= primaryexpr
930 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
931 // Parse the expression.
933 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
936 // As a special case, we support 'a op b @ modifier' by rewriting the
937 // expression to include the modifier. This is inefficient, but in general we
938 // expect users to use 'a@modifier op b'.
939 if (Lexer.getKind() == AsmToken::At) {
942 if (Lexer.isNot(AsmToken::Identifier))
943 return TokError("unexpected symbol modifier following '@'");
945 MCSymbolRefExpr::VariantKind Variant =
946 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
947 if (Variant == MCSymbolRefExpr::VK_Invalid)
948 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
950 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
952 return TokError("invalid modifier '" + getTok().getIdentifier() +
953 "' (no symbols present)");
960 // Try to constant fold it up front, if possible.
962 if (Res->EvaluateAsAbsolute(Value))
963 Res = MCConstantExpr::Create(Value, getContext());
968 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
970 return ParseParenExpr(Res, EndLoc) ||
971 ParseBinOpRHS(1, Res, EndLoc);
974 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
977 SMLoc StartLoc = Lexer.getLoc();
978 if (parseExpression(Expr))
981 if (!Expr->EvaluateAsAbsolute(Res))
982 return Error(StartLoc, "expected absolute expression");
987 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
988 MCBinaryExpr::Opcode &Kind) {
991 return 0; // not a binop.
993 // Lowest Precedence: &&, ||
994 case AsmToken::AmpAmp:
995 Kind = MCBinaryExpr::LAnd;
997 case AsmToken::PipePipe:
998 Kind = MCBinaryExpr::LOr;
1002 // Low Precedence: |, &, ^
1004 // FIXME: gas seems to support '!' as an infix operator?
1005 case AsmToken::Pipe:
1006 Kind = MCBinaryExpr::Or;
1008 case AsmToken::Caret:
1009 Kind = MCBinaryExpr::Xor;
1012 Kind = MCBinaryExpr::And;
1015 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1016 case AsmToken::EqualEqual:
1017 Kind = MCBinaryExpr::EQ;
1019 case AsmToken::ExclaimEqual:
1020 case AsmToken::LessGreater:
1021 Kind = MCBinaryExpr::NE;
1023 case AsmToken::Less:
1024 Kind = MCBinaryExpr::LT;
1026 case AsmToken::LessEqual:
1027 Kind = MCBinaryExpr::LTE;
1029 case AsmToken::Greater:
1030 Kind = MCBinaryExpr::GT;
1032 case AsmToken::GreaterEqual:
1033 Kind = MCBinaryExpr::GTE;
1036 // Intermediate Precedence: <<, >>
1037 case AsmToken::LessLess:
1038 Kind = MCBinaryExpr::Shl;
1040 case AsmToken::GreaterGreater:
1041 Kind = MCBinaryExpr::Shr;
1044 // High Intermediate Precedence: +, -
1045 case AsmToken::Plus:
1046 Kind = MCBinaryExpr::Add;
1048 case AsmToken::Minus:
1049 Kind = MCBinaryExpr::Sub;
1052 // Highest Precedence: *, /, %
1053 case AsmToken::Star:
1054 Kind = MCBinaryExpr::Mul;
1056 case AsmToken::Slash:
1057 Kind = MCBinaryExpr::Div;
1059 case AsmToken::Percent:
1060 Kind = MCBinaryExpr::Mod;
1066 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1067 /// Res contains the LHS of the expression on input.
1068 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1071 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1072 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1074 // If the next token is lower precedence than we are allowed to eat, return
1075 // successfully with what we ate already.
1076 if (TokPrec < Precedence)
1081 // Eat the next primary expression.
1083 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1085 // If BinOp binds less tightly with RHS than the operator after RHS, let
1086 // the pending operator take RHS as its LHS.
1087 MCBinaryExpr::Opcode Dummy;
1088 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1089 if (TokPrec < NextTokPrec) {
1090 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1093 // Merge LHS and RHS according to operator.
1094 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1099 /// ::= EndOfStatement
1100 /// ::= Label* Directive ...Operands... EndOfStatement
1101 /// ::= Label* Identifier OperandList* EndOfStatement
1102 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1103 if (Lexer.is(AsmToken::EndOfStatement)) {
1109 // Statements always start with an identifier or are a full line comment.
1110 AsmToken ID = getTok();
1111 SMLoc IDLoc = ID.getLoc();
1113 int64_t LocalLabelVal = -1;
1114 // A full line comment is a '#' as the first token.
1115 if (Lexer.is(AsmToken::Hash))
1116 return ParseCppHashLineFilenameComment(IDLoc);
1118 // Allow an integer followed by a ':' as a directional local label.
1119 if (Lexer.is(AsmToken::Integer)) {
1120 LocalLabelVal = getTok().getIntVal();
1121 if (LocalLabelVal < 0) {
1122 if (!TheCondState.Ignore)
1123 return TokError("unexpected token at start of statement");
1126 IDVal = getTok().getString();
1127 Lex(); // Consume the integer token to be used as an identifier token.
1128 if (Lexer.getKind() != AsmToken::Colon) {
1129 if (!TheCondState.Ignore)
1130 return TokError("unexpected token at start of statement");
1133 } else if (Lexer.is(AsmToken::Dot)) {
1134 // Treat '.' as a valid identifier in this context.
1137 } else if (parseIdentifier(IDVal)) {
1138 if (!TheCondState.Ignore)
1139 return TokError("unexpected token at start of statement");
1143 // Handle conditional assembly here before checking for skipping. We
1144 // have to do this so that .endif isn't skipped in a ".if 0" block for
1146 StringMap<DirectiveKind>::const_iterator DirKindIt =
1147 DirectiveKindMap.find(IDVal);
1148 DirectiveKind DirKind =
1149 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1150 DirKindIt->getValue();
1155 return ParseDirectiveIf(IDLoc);
1157 return ParseDirectiveIfb(IDLoc, true);
1159 return ParseDirectiveIfb(IDLoc, false);
1161 return ParseDirectiveIfc(IDLoc, true);
1163 return ParseDirectiveIfc(IDLoc, false);
1165 return ParseDirectiveIfdef(IDLoc, true);
1168 return ParseDirectiveIfdef(IDLoc, false);
1170 return ParseDirectiveElseIf(IDLoc);
1172 return ParseDirectiveElse(IDLoc);
1174 return ParseDirectiveEndIf(IDLoc);
1177 // Ignore the statement if in the middle of inactive conditional
1179 if (TheCondState.Ignore) {
1180 eatToEndOfStatement();
1184 // FIXME: Recurse on local labels?
1186 // See what kind of statement we have.
1187 switch (Lexer.getKind()) {
1188 case AsmToken::Colon: {
1189 checkForValidSection();
1191 // identifier ':' -> Label.
1194 // Diagnose attempt to use '.' as a label.
1196 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1198 // Diagnose attempt to use a variable as a label.
1200 // FIXME: Diagnostics. Note the location of the definition as a label.
1201 // FIXME: This doesn't diagnose assignment to a symbol which has been
1202 // implicitly marked as external.
1204 if (LocalLabelVal == -1)
1205 Sym = getContext().GetOrCreateSymbol(IDVal);
1207 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1208 if (!Sym->isUndefined() || Sym->isVariable())
1209 return Error(IDLoc, "invalid symbol redefinition");
1212 if (!ParsingInlineAsm)
1215 // If we are generating dwarf for assembly source files then gather the
1216 // info to make a dwarf label entry for this label if needed.
1217 if (getContext().getGenDwarfForAssembly())
1218 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1221 // Consume any end of statement token, if present, to avoid spurious
1222 // AddBlankLine calls().
1223 if (Lexer.is(AsmToken::EndOfStatement)) {
1225 if (Lexer.is(AsmToken::Eof))
1232 case AsmToken::Equal:
1233 // identifier '=' ... -> assignment statement
1236 return ParseAssignment(IDVal, true);
1238 default: // Normal instruction or directive.
1242 // If macros are enabled, check to see if this is a macro instantiation.
1243 if (MacrosEnabled())
1244 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1245 return HandleMacroEntry(M, IDLoc);
1248 // Otherwise, we have a normal instruction or directive.
1250 // Directives start with "."
1251 if (IDVal[0] == '.' && IDVal != ".") {
1252 // There are several entities interested in parsing directives:
1254 // 1. The target-specific assembly parser. Some directives are target
1255 // specific or may potentially behave differently on certain targets.
1256 // 2. Asm parser extensions. For example, platform-specific parsers
1257 // (like the ELF parser) register themselves as extensions.
1258 // 3. The generic directive parser implemented by this class. These are
1259 // all the directives that behave in a target and platform independent
1260 // manner, or at least have a default behavior that's shared between
1261 // all targets and platforms.
1263 // First query the target-specific parser. It will return 'true' if it
1264 // isn't interested in this directive.
1265 if (!getTargetParser().ParseDirective(ID))
1268 // Next, check the extention directive map to see if any extension has
1269 // registered itself to parse this directive.
1270 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1271 ExtensionDirectiveMap.lookup(IDVal);
1273 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1275 // Finally, if no one else is interested in this directive, it must be
1276 // generic and familiar to this class.
1282 return ParseDirectiveSet(IDVal, true);
1284 return ParseDirectiveSet(IDVal, false);
1286 return ParseDirectiveAscii(IDVal, false);
1289 return ParseDirectiveAscii(IDVal, true);
1291 return ParseDirectiveValue(1);
1295 return ParseDirectiveValue(2);
1299 return ParseDirectiveValue(4);
1302 return ParseDirectiveValue(8);
1305 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1307 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1309 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1310 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1313 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1314 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1317 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1319 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1321 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1323 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1325 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1327 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1329 return ParseDirectiveOrg();
1331 return ParseDirectiveFill();
1333 return ParseDirectiveZero();
1335 eatToEndOfStatement(); // .extern is the default, ignore it.
1339 return ParseDirectiveSymbolAttribute(MCSA_Global);
1340 case DK_INDIRECT_SYMBOL:
1341 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1342 case DK_LAZY_REFERENCE:
1343 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1344 case DK_NO_DEAD_STRIP:
1345 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1346 case DK_SYMBOL_RESOLVER:
1347 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1348 case DK_PRIVATE_EXTERN:
1349 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1351 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1352 case DK_WEAK_DEFINITION:
1353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1354 case DK_WEAK_REFERENCE:
1355 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1356 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1357 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1360 return ParseDirectiveComm(/*IsLocal=*/false);
1362 return ParseDirectiveComm(/*IsLocal=*/true);
1364 return ParseDirectiveAbort();
1366 return ParseDirectiveInclude();
1368 return ParseDirectiveIncbin();
1371 return TokError(Twine(IDVal) + " not supported yet");
1373 return ParseDirectiveRept(IDLoc);
1375 return ParseDirectiveIrp(IDLoc);
1377 return ParseDirectiveIrpc(IDLoc);
1379 return ParseDirectiveEndr(IDLoc);
1380 case DK_BUNDLE_ALIGN_MODE:
1381 return ParseDirectiveBundleAlignMode();
1382 case DK_BUNDLE_LOCK:
1383 return ParseDirectiveBundleLock();
1384 case DK_BUNDLE_UNLOCK:
1385 return ParseDirectiveBundleUnlock();
1387 return ParseDirectiveLEB128(true);
1389 return ParseDirectiveLEB128(false);
1392 return ParseDirectiveSpace(IDVal);
1394 return ParseDirectiveFile(IDLoc);
1396 return ParseDirectiveLine();
1398 return ParseDirectiveLoc();
1400 return ParseDirectiveStabs();
1401 case DK_CFI_SECTIONS:
1402 return ParseDirectiveCFISections();
1403 case DK_CFI_STARTPROC:
1404 return ParseDirectiveCFIStartProc();
1405 case DK_CFI_ENDPROC:
1406 return ParseDirectiveCFIEndProc();
1407 case DK_CFI_DEF_CFA:
1408 return ParseDirectiveCFIDefCfa(IDLoc);
1409 case DK_CFI_DEF_CFA_OFFSET:
1410 return ParseDirectiveCFIDefCfaOffset();
1411 case DK_CFI_ADJUST_CFA_OFFSET:
1412 return ParseDirectiveCFIAdjustCfaOffset();
1413 case DK_CFI_DEF_CFA_REGISTER:
1414 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1416 return ParseDirectiveCFIOffset(IDLoc);
1417 case DK_CFI_REL_OFFSET:
1418 return ParseDirectiveCFIRelOffset(IDLoc);
1419 case DK_CFI_PERSONALITY:
1420 return ParseDirectiveCFIPersonalityOrLsda(true);
1422 return ParseDirectiveCFIPersonalityOrLsda(false);
1423 case DK_CFI_REMEMBER_STATE:
1424 return ParseDirectiveCFIRememberState();
1425 case DK_CFI_RESTORE_STATE:
1426 return ParseDirectiveCFIRestoreState();
1427 case DK_CFI_SAME_VALUE:
1428 return ParseDirectiveCFISameValue(IDLoc);
1429 case DK_CFI_RESTORE:
1430 return ParseDirectiveCFIRestore(IDLoc);
1432 return ParseDirectiveCFIEscape();
1433 case DK_CFI_SIGNAL_FRAME:
1434 return ParseDirectiveCFISignalFrame();
1435 case DK_CFI_UNDEFINED:
1436 return ParseDirectiveCFIUndefined(IDLoc);
1437 case DK_CFI_REGISTER:
1438 return ParseDirectiveCFIRegister(IDLoc);
1441 return ParseDirectiveMacrosOnOff(IDVal);
1443 return ParseDirectiveMacro(IDLoc);
1446 return ParseDirectiveEndMacro(IDVal);
1448 return ParseDirectivePurgeMacro(IDLoc);
1451 return Error(IDLoc, "unknown directive");
1454 // __asm _emit or __asm __emit
1455 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1456 IDVal == "_EMIT" || IDVal == "__EMIT"))
1457 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1460 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1461 return ParseDirectiveMSAlign(IDLoc, Info);
1463 checkForValidSection();
1465 // Canonicalize the opcode to lower case.
1466 std::string OpcodeStr = IDVal.lower();
1467 ParseInstructionInfo IInfo(Info.AsmRewrites);
1468 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1469 IDLoc, Info.ParsedOperands);
1470 Info.ParseError = HadError;
1472 // Dump the parsed representation, if requested.
1473 if (getShowParsedOperands()) {
1474 SmallString<256> Str;
1475 raw_svector_ostream OS(Str);
1476 OS << "parsed instruction: [";
1477 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1480 Info.ParsedOperands[i]->print(OS);
1484 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1487 // If we are generating dwarf for assembly source files and the current
1488 // section is the initial text section then generate a .loc directive for
1490 if (!HadError && getContext().getGenDwarfForAssembly() &&
1491 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1493 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1495 // If we previously parsed a cpp hash file line comment then make sure the
1496 // current Dwarf File is for the CppHashFilename if not then emit the
1497 // Dwarf File table for it and adjust the line number for the .loc.
1498 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1499 getContext().getMCDwarfFiles();
1500 if (CppHashFilename.size() != 0) {
1501 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1503 getStreamer().EmitDwarfFileDirective(
1504 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1506 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1507 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1510 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1511 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1512 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1516 // If parsing succeeded, match the instruction.
1519 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1520 Info.ParsedOperands,
1525 // Don't skip the rest of the line, the instruction parser is responsible for
1530 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1531 /// since they may not be able to be tokenized to get to the end of line token.
1532 void AsmParser::EatToEndOfLine() {
1533 if (!Lexer.is(AsmToken::EndOfStatement))
1534 Lexer.LexUntilEndOfLine();
1539 /// ParseCppHashLineFilenameComment as this:
1540 /// ::= # number "filename"
1541 /// or just as a full line comment if it doesn't have a number and a string.
1542 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1543 Lex(); // Eat the hash token.
1545 if (getLexer().isNot(AsmToken::Integer)) {
1546 // Consume the line since in cases it is not a well-formed line directive,
1547 // as if were simply a full line comment.
1552 int64_t LineNumber = getTok().getIntVal();
1555 if (getLexer().isNot(AsmToken::String)) {
1560 StringRef Filename = getTok().getString();
1561 // Get rid of the enclosing quotes.
1562 Filename = Filename.substr(1, Filename.size()-2);
1564 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1566 CppHashFilename = Filename;
1567 CppHashLineNumber = LineNumber;
1568 CppHashBuf = CurBuffer;
1570 // Ignore any trailing characters, they're just comment.
1575 /// DiagHandler - will use the last parsed cpp hash line filename comment
1576 /// for the Filename and LineNo if any in the diagnostic.
1577 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1578 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1579 raw_ostream &OS = errs();
1581 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1582 const SMLoc &DiagLoc = Diag.getLoc();
1583 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1584 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1586 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1587 // before printing the message.
1588 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1589 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1590 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1591 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1594 // If we have not parsed a cpp hash line filename comment or the source
1595 // manager changed or buffer changed (like in a nested include) then just
1596 // print the normal diagnostic using its Filename and LineNo.
1597 if (!Parser->CppHashLineNumber ||
1598 &DiagSrcMgr != &Parser->SrcMgr ||
1599 DiagBuf != CppHashBuf) {
1600 if (Parser->SavedDiagHandler)
1601 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1607 // Use the CppHashFilename and calculate a line number based on the
1608 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1610 const std::string Filename = Parser->CppHashFilename;
1612 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1613 int CppHashLocLineNo =
1614 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1615 int LineNo = Parser->CppHashLineNumber - 1 +
1616 (DiagLocLineNo - CppHashLocLineNo);
1618 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1619 Filename, LineNo, Diag.getColumnNo(),
1620 Diag.getKind(), Diag.getMessage(),
1621 Diag.getLineContents(), Diag.getRanges());
1623 if (Parser->SavedDiagHandler)
1624 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1626 NewDiag.print(0, OS);
1629 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1630 // difference being that that function accepts '@' as part of identifiers and
1631 // we can't do that. AsmLexer.cpp should probably be changed to handle
1632 // '@' as a special case when needed.
1633 static bool isIdentifierChar(char c) {
1634 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1638 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1639 const MCAsmMacroParameters &Parameters,
1640 const MCAsmMacroArguments &A,
1642 unsigned NParameters = Parameters.size();
1643 if (NParameters != 0 && NParameters != A.size())
1644 return Error(L, "Wrong number of arguments");
1646 // A macro without parameters is handled differently on Darwin:
1647 // gas accepts no arguments and does no substitutions
1648 while (!Body.empty()) {
1649 // Scan for the next substitution.
1650 std::size_t End = Body.size(), Pos = 0;
1651 for (; Pos != End; ++Pos) {
1652 // Check for a substitution or escape.
1654 // This macro has no parameters, look for $0, $1, etc.
1655 if (Body[Pos] != '$' || Pos + 1 == End)
1658 char Next = Body[Pos + 1];
1659 if (Next == '$' || Next == 'n' ||
1660 isdigit(static_cast<unsigned char>(Next)))
1663 // This macro has parameters, look for \foo, \bar, etc.
1664 if (Body[Pos] == '\\' && Pos + 1 != End)
1670 OS << Body.slice(0, Pos);
1672 // Check if we reached the end.
1677 switch (Body[Pos+1]) {
1683 // $n => number of arguments
1688 // $[0-9] => argument
1690 // Missing arguments are ignored.
1691 unsigned Index = Body[Pos+1] - '0';
1692 if (Index >= A.size())
1695 // Otherwise substitute with the token values, with spaces eliminated.
1696 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1697 ie = A[Index].end(); it != ie; ++it)
1698 OS << it->getString();
1704 unsigned I = Pos + 1;
1705 while (isIdentifierChar(Body[I]) && I + 1 != End)
1708 const char *Begin = Body.data() + Pos +1;
1709 StringRef Argument(Begin, I - (Pos +1));
1711 for (; Index < NParameters; ++Index)
1712 if (Parameters[Index].first == Argument)
1715 if (Index == NParameters) {
1716 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1719 OS << '\\' << Argument;
1723 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1724 ie = A[Index].end(); it != ie; ++it)
1725 if (it->getKind() == AsmToken::String)
1726 OS << it->getStringContents();
1728 OS << it->getString();
1730 Pos += 1 + Argument.size();
1733 // Update the scan point.
1734 Body = Body.substr(Pos);
1740 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1743 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1748 static bool IsOperator(AsmToken::TokenKind kind)
1754 case AsmToken::Plus:
1755 case AsmToken::Minus:
1756 case AsmToken::Tilde:
1757 case AsmToken::Slash:
1758 case AsmToken::Star:
1760 case AsmToken::Equal:
1761 case AsmToken::EqualEqual:
1762 case AsmToken::Pipe:
1763 case AsmToken::PipePipe:
1764 case AsmToken::Caret:
1766 case AsmToken::AmpAmp:
1767 case AsmToken::Exclaim:
1768 case AsmToken::ExclaimEqual:
1769 case AsmToken::Percent:
1770 case AsmToken::Less:
1771 case AsmToken::LessEqual:
1772 case AsmToken::LessLess:
1773 case AsmToken::LessGreater:
1774 case AsmToken::Greater:
1775 case AsmToken::GreaterEqual:
1776 case AsmToken::GreaterGreater:
1781 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1782 AsmToken::TokenKind &ArgumentDelimiter) {
1783 unsigned ParenLevel = 0;
1784 unsigned AddTokens = 0;
1786 // gas accepts arguments separated by whitespace, except on Darwin
1788 Lexer.setSkipSpace(false);
1791 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1792 Lexer.setSkipSpace(true);
1793 return TokError("unexpected token in macro instantiation");
1796 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1797 // Spaces and commas cannot be mixed to delimit parameters
1798 if (ArgumentDelimiter == AsmToken::Eof)
1799 ArgumentDelimiter = AsmToken::Comma;
1800 else if (ArgumentDelimiter != AsmToken::Comma) {
1801 Lexer.setSkipSpace(true);
1802 return TokError("expected ' ' for macro argument separator");
1807 if (Lexer.is(AsmToken::Space)) {
1808 Lex(); // Eat spaces
1810 // Spaces can delimit parameters, but could also be part an expression.
1811 // If the token after a space is an operator, add the token and the next
1812 // one into this argument
1813 if (ArgumentDelimiter == AsmToken::Space ||
1814 ArgumentDelimiter == AsmToken::Eof) {
1815 if (IsOperator(Lexer.getKind())) {
1816 // Check to see whether the token is used as an operator,
1817 // or part of an identifier
1818 const char *NextChar = getTok().getEndLoc().getPointer();
1819 if (*NextChar == ' ')
1823 if (!AddTokens && ParenLevel == 0) {
1824 if (ArgumentDelimiter == AsmToken::Eof &&
1825 !IsOperator(Lexer.getKind()))
1826 ArgumentDelimiter = AsmToken::Space;
1832 // HandleMacroEntry relies on not advancing the lexer here
1833 // to be able to fill in the remaining default parameter values
1834 if (Lexer.is(AsmToken::EndOfStatement))
1837 // Adjust the current parentheses level.
1838 if (Lexer.is(AsmToken::LParen))
1840 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1843 // Append the token to the current argument list.
1844 MA.push_back(getTok());
1850 Lexer.setSkipSpace(true);
1851 if (ParenLevel != 0)
1852 return TokError("unbalanced parentheses in macro argument");
1856 // Parse the macro instantiation arguments.
1857 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1858 const unsigned NParameters = M ? M->Parameters.size() : 0;
1859 // Argument delimiter is initially unknown. It will be set by
1860 // ParseMacroArgument()
1861 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1863 // Parse two kinds of macro invocations:
1864 // - macros defined without any parameters accept an arbitrary number of them
1865 // - macros defined with parameters accept at most that many of them
1866 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1868 MCAsmMacroArgument MA;
1870 if (ParseMacroArgument(MA, ArgumentDelimiter))
1873 if (!MA.empty() || !NParameters)
1875 else if (NParameters) {
1876 if (!M->Parameters[Parameter].second.empty())
1877 A.push_back(M->Parameters[Parameter].second);
1880 // At the end of the statement, fill in remaining arguments that have
1881 // default values. If there aren't any, then the next argument is
1882 // required but missing
1883 if (Lexer.is(AsmToken::EndOfStatement)) {
1884 if (NParameters && Parameter < NParameters - 1) {
1885 if (M->Parameters[Parameter + 1].second.empty())
1886 return TokError("macro argument '" +
1887 Twine(M->Parameters[Parameter + 1].first) +
1895 if (Lexer.is(AsmToken::Comma))
1898 return TokError("Too many arguments");
1901 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1902 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1903 return (I == MacroMap.end()) ? NULL : I->getValue();
1906 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1907 MacroMap[Name] = new MCAsmMacro(Macro);
1910 void AsmParser::UndefineMacro(StringRef Name) {
1911 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1912 if (I != MacroMap.end()) {
1913 delete I->getValue();
1918 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1919 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1920 // this, although we should protect against infinite loops.
1921 if (ActiveMacros.size() == 20)
1922 return TokError("macros cannot be nested more than 20 levels deep");
1924 MCAsmMacroArguments A;
1925 if (ParseMacroArguments(M, A))
1928 // Remove any trailing empty arguments. Do this after-the-fact as we have
1929 // to keep empty arguments in the middle of the list or positionality
1930 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1931 while (!A.empty() && A.back().empty())
1934 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1935 // to hold the macro body with substitutions.
1936 SmallString<256> Buf;
1937 StringRef Body = M->Body;
1938 raw_svector_ostream OS(Buf);
1940 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1943 // We include the .endmacro in the buffer as our cue to exit the macro
1945 OS << ".endmacro\n";
1947 MemoryBuffer *Instantiation =
1948 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1950 // Create the macro instantiation object and add to the current macro
1951 // instantiation stack.
1952 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1956 ActiveMacros.push_back(MI);
1958 // Jump to the macro instantiation and prime the lexer.
1959 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1960 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1966 void AsmParser::HandleMacroExit() {
1967 // Jump to the EndOfStatement we should return to, and consume it.
1968 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1971 // Pop the instantiation entry.
1972 delete ActiveMacros.back();
1973 ActiveMacros.pop_back();
1976 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1977 switch (Value->getKind()) {
1978 case MCExpr::Binary: {
1979 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1980 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1983 case MCExpr::Target:
1984 case MCExpr::Constant:
1986 case MCExpr::SymbolRef: {
1987 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1989 return IsUsedIn(Sym, S.getVariableValue());
1993 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1996 llvm_unreachable("Unknown expr kind!");
1999 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2001 // FIXME: Use better location, we should use proper tokens.
2002 SMLoc EqualLoc = Lexer.getLoc();
2004 const MCExpr *Value;
2005 if (parseExpression(Value))
2008 // Note: we don't count b as used in "a = b". This is to allow
2012 if (Lexer.isNot(AsmToken::EndOfStatement))
2013 return TokError("unexpected token in assignment");
2015 // Error on assignment to '.'.
2017 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2018 "(use '.space' or '.org').)"));
2021 // Eat the end of statement marker.
2024 // Validate that the LHS is allowed to be a variable (either it has not been
2025 // used as a symbol, or it is an absolute symbol).
2026 MCSymbol *Sym = getContext().LookupSymbol(Name);
2028 // Diagnose assignment to a label.
2030 // FIXME: Diagnostics. Note the location of the definition as a label.
2031 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2032 if (IsUsedIn(Sym, Value))
2033 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2034 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2035 ; // Allow redefinitions of undefined symbols only used in directives.
2036 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2037 ; // Allow redefinitions of variables that haven't yet been used.
2038 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2039 return Error(EqualLoc, "redefinition of '" + Name + "'");
2040 else if (!Sym->isVariable())
2041 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2042 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2043 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2046 // Don't count these checks as uses.
2047 Sym->setUsed(false);
2049 Sym = getContext().GetOrCreateSymbol(Name);
2051 // FIXME: Handle '.'.
2053 // Do the assignment.
2054 Out.EmitAssignment(Sym, Value);
2056 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2062 /// parseIdentifier:
2065 bool AsmParser::parseIdentifier(StringRef &Res) {
2066 // The assembler has relaxed rules for accepting identifiers, in particular we
2067 // allow things like '.globl $foo', which would normally be separate
2068 // tokens. At this level, we have already lexed so we cannot (currently)
2069 // handle this as a context dependent token, instead we detect adjacent tokens
2070 // and return the combined identifier.
2071 if (Lexer.is(AsmToken::Dollar)) {
2072 SMLoc DollarLoc = getLexer().getLoc();
2074 // Consume the dollar sign, and check for a following identifier.
2076 if (Lexer.isNot(AsmToken::Identifier))
2079 // We have a '$' followed by an identifier, make sure they are adjacent.
2080 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2083 // Construct the joined identifier and consume the token.
2084 Res = StringRef(DollarLoc.getPointer(),
2085 getTok().getIdentifier().size() + 1);
2090 if (Lexer.isNot(AsmToken::Identifier) &&
2091 Lexer.isNot(AsmToken::String))
2094 Res = getTok().getIdentifier();
2096 Lex(); // Consume the identifier token.
2101 /// ParseDirectiveSet:
2102 /// ::= .equ identifier ',' expression
2103 /// ::= .equiv identifier ',' expression
2104 /// ::= .set identifier ',' expression
2105 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2108 if (parseIdentifier(Name))
2109 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2111 if (getLexer().isNot(AsmToken::Comma))
2112 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2115 return ParseAssignment(Name, allow_redef, true);
2118 bool AsmParser::parseEscapedString(std::string &Data) {
2119 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2122 StringRef Str = getTok().getStringContents();
2123 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2124 if (Str[i] != '\\') {
2129 // Recognize escaped characters. Note that this escape semantics currently
2130 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2133 return TokError("unexpected backslash at end of string");
2135 // Recognize octal sequences.
2136 if ((unsigned) (Str[i] - '0') <= 7) {
2137 // Consume up to three octal characters.
2138 unsigned Value = Str[i] - '0';
2140 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2142 Value = Value * 8 + (Str[i] - '0');
2144 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2146 Value = Value * 8 + (Str[i] - '0');
2151 return TokError("invalid octal escape sequence (out of range)");
2153 Data += (unsigned char) Value;
2157 // Otherwise recognize individual escapes.
2160 // Just reject invalid escape sequences for now.
2161 return TokError("invalid escape sequence (unrecognized character)");
2163 case 'b': Data += '\b'; break;
2164 case 'f': Data += '\f'; break;
2165 case 'n': Data += '\n'; break;
2166 case 'r': Data += '\r'; break;
2167 case 't': Data += '\t'; break;
2168 case '"': Data += '"'; break;
2169 case '\\': Data += '\\'; break;
2176 /// ParseDirectiveAscii:
2177 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2178 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2179 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2180 checkForValidSection();
2183 if (getLexer().isNot(AsmToken::String))
2184 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2187 if (parseEscapedString(Data))
2190 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2192 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2196 if (getLexer().is(AsmToken::EndOfStatement))
2199 if (getLexer().isNot(AsmToken::Comma))
2200 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2209 /// ParseDirectiveValue
2210 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2211 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2212 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2213 checkForValidSection();
2216 const MCExpr *Value;
2217 SMLoc ExprLoc = getLexer().getLoc();
2218 if (parseExpression(Value))
2221 // Special case constant expressions to match code generator.
2222 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2223 assert(Size <= 8 && "Invalid size");
2224 uint64_t IntValue = MCE->getValue();
2225 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2226 return Error(ExprLoc, "literal value out of range for directive");
2227 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2229 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2231 if (getLexer().is(AsmToken::EndOfStatement))
2234 // FIXME: Improve diagnostic.
2235 if (getLexer().isNot(AsmToken::Comma))
2236 return TokError("unexpected token in directive");
2245 /// ParseDirectiveRealValue
2246 /// ::= (.single | .double) [ expression (, expression)* ]
2247 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2248 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2249 checkForValidSection();
2252 // We don't truly support arithmetic on floating point expressions, so we
2253 // have to manually parse unary prefixes.
2255 if (getLexer().is(AsmToken::Minus)) {
2258 } else if (getLexer().is(AsmToken::Plus))
2261 if (getLexer().isNot(AsmToken::Integer) &&
2262 getLexer().isNot(AsmToken::Real) &&
2263 getLexer().isNot(AsmToken::Identifier))
2264 return TokError("unexpected token in directive");
2266 // Convert to an APFloat.
2267 APFloat Value(Semantics);
2268 StringRef IDVal = getTok().getString();
2269 if (getLexer().is(AsmToken::Identifier)) {
2270 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2271 Value = APFloat::getInf(Semantics);
2272 else if (!IDVal.compare_lower("nan"))
2273 Value = APFloat::getNaN(Semantics, false, ~0);
2275 return TokError("invalid floating point literal");
2276 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2277 APFloat::opInvalidOp)
2278 return TokError("invalid floating point literal");
2282 // Consume the numeric token.
2285 // Emit the value as an integer.
2286 APInt AsInt = Value.bitcastToAPInt();
2287 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2288 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2290 if (getLexer().is(AsmToken::EndOfStatement))
2293 if (getLexer().isNot(AsmToken::Comma))
2294 return TokError("unexpected token in directive");
2303 /// ParseDirectiveZero
2304 /// ::= .zero expression
2305 bool AsmParser::ParseDirectiveZero() {
2306 checkForValidSection();
2309 if (parseAbsoluteExpression(NumBytes))
2313 if (getLexer().is(AsmToken::Comma)) {
2315 if (parseAbsoluteExpression(Val))
2319 if (getLexer().isNot(AsmToken::EndOfStatement))
2320 return TokError("unexpected token in '.zero' directive");
2324 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2329 /// ParseDirectiveFill
2330 /// ::= .fill expression , expression , expression
2331 bool AsmParser::ParseDirectiveFill() {
2332 checkForValidSection();
2335 if (parseAbsoluteExpression(NumValues))
2338 if (getLexer().isNot(AsmToken::Comma))
2339 return TokError("unexpected token in '.fill' directive");
2343 if (parseAbsoluteExpression(FillSize))
2346 if (getLexer().isNot(AsmToken::Comma))
2347 return TokError("unexpected token in '.fill' directive");
2351 if (parseAbsoluteExpression(FillExpr))
2354 if (getLexer().isNot(AsmToken::EndOfStatement))
2355 return TokError("unexpected token in '.fill' directive");
2359 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2360 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2362 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2363 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2368 /// ParseDirectiveOrg
2369 /// ::= .org expression [ , expression ]
2370 bool AsmParser::ParseDirectiveOrg() {
2371 checkForValidSection();
2373 const MCExpr *Offset;
2374 SMLoc Loc = getTok().getLoc();
2375 if (parseExpression(Offset))
2378 // Parse optional fill expression.
2379 int64_t FillExpr = 0;
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 if (getLexer().isNot(AsmToken::Comma))
2382 return TokError("unexpected token in '.org' directive");
2385 if (parseAbsoluteExpression(FillExpr))
2388 if (getLexer().isNot(AsmToken::EndOfStatement))
2389 return TokError("unexpected token in '.org' directive");
2394 // Only limited forms of relocatable expressions are accepted here, it
2395 // has to be relative to the current section. The streamer will return
2396 // 'true' if the expression wasn't evaluatable.
2397 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2398 return Error(Loc, "expected assembly-time absolute expression");
2403 /// ParseDirectiveAlign
2404 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2405 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2406 checkForValidSection();
2408 SMLoc AlignmentLoc = getLexer().getLoc();
2410 if (parseAbsoluteExpression(Alignment))
2414 bool HasFillExpr = false;
2415 int64_t FillExpr = 0;
2416 int64_t MaxBytesToFill = 0;
2417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
2419 return TokError("unexpected token in directive");
2422 // The fill expression can be omitted while specifying a maximum number of
2423 // alignment bytes, e.g:
2425 if (getLexer().isNot(AsmToken::Comma)) {
2427 if (parseAbsoluteExpression(FillExpr))
2431 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2432 if (getLexer().isNot(AsmToken::Comma))
2433 return TokError("unexpected token in directive");
2436 MaxBytesLoc = getLexer().getLoc();
2437 if (parseAbsoluteExpression(MaxBytesToFill))
2440 if (getLexer().isNot(AsmToken::EndOfStatement))
2441 return TokError("unexpected token in directive");
2450 // Compute alignment in bytes.
2452 // FIXME: Diagnose overflow.
2453 if (Alignment >= 32) {
2454 Error(AlignmentLoc, "invalid alignment value");
2458 Alignment = 1ULL << Alignment;
2460 // Reject alignments that aren't a power of two, for gas compatibility.
2461 if (!isPowerOf2_64(Alignment))
2462 Error(AlignmentLoc, "alignment must be a power of 2");
2465 // Diagnose non-sensical max bytes to align.
2466 if (MaxBytesLoc.isValid()) {
2467 if (MaxBytesToFill < 1) {
2468 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2469 "many bytes, ignoring maximum bytes expression");
2473 if (MaxBytesToFill >= Alignment) {
2474 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2480 // Check whether we should use optimal code alignment for this .align
2482 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2483 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2484 ValueSize == 1 && UseCodeAlign) {
2485 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2487 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2488 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2495 /// ParseDirectiveFile
2496 /// ::= .file [number] filename
2497 /// ::= .file number directory filename
2498 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2499 // FIXME: I'm not sure what this is.
2500 int64_t FileNumber = -1;
2501 SMLoc FileNumberLoc = getLexer().getLoc();
2502 if (getLexer().is(AsmToken::Integer)) {
2503 FileNumber = getTok().getIntVal();
2507 return TokError("file number less than one");
2510 if (getLexer().isNot(AsmToken::String))
2511 return TokError("unexpected token in '.file' directive");
2513 // Usually the directory and filename together, otherwise just the directory.
2514 StringRef Path = getTok().getString();
2515 Path = Path.substr(1, Path.size()-2);
2518 StringRef Directory;
2520 if (getLexer().is(AsmToken::String)) {
2521 if (FileNumber == -1)
2522 return TokError("explicit path specified, but no file number");
2523 Filename = getTok().getString();
2524 Filename = Filename.substr(1, Filename.size()-2);
2531 if (getLexer().isNot(AsmToken::EndOfStatement))
2532 return TokError("unexpected token in '.file' directive");
2534 if (FileNumber == -1)
2535 getStreamer().EmitFileDirective(Filename);
2537 if (getContext().getGenDwarfForAssembly() == true)
2538 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2539 "used to generate dwarf debug info for assembly code");
2541 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2542 Error(FileNumberLoc, "file number already allocated");
2548 /// ParseDirectiveLine
2549 /// ::= .line [number]
2550 bool AsmParser::ParseDirectiveLine() {
2551 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2552 if (getLexer().isNot(AsmToken::Integer))
2553 return TokError("unexpected token in '.line' directive");
2555 int64_t LineNumber = getTok().getIntVal();
2559 // FIXME: Do something with the .line.
2562 if (getLexer().isNot(AsmToken::EndOfStatement))
2563 return TokError("unexpected token in '.line' directive");
2568 /// ParseDirectiveLoc
2569 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2570 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2571 /// The first number is a file number, must have been previously assigned with
2572 /// a .file directive, the second number is the line number and optionally the
2573 /// third number is a column position (zero if not specified). The remaining
2574 /// optional items are .loc sub-directives.
2575 bool AsmParser::ParseDirectiveLoc() {
2576 if (getLexer().isNot(AsmToken::Integer))
2577 return TokError("unexpected token in '.loc' directive");
2578 int64_t FileNumber = getTok().getIntVal();
2580 return TokError("file number less than one in '.loc' directive");
2581 if (!getContext().isValidDwarfFileNumber(FileNumber))
2582 return TokError("unassigned file number in '.loc' directive");
2585 int64_t LineNumber = 0;
2586 if (getLexer().is(AsmToken::Integer)) {
2587 LineNumber = getTok().getIntVal();
2589 return TokError("line number less than one in '.loc' directive");
2593 int64_t ColumnPos = 0;
2594 if (getLexer().is(AsmToken::Integer)) {
2595 ColumnPos = getTok().getIntVal();
2597 return TokError("column position less than zero in '.loc' directive");
2601 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2603 int64_t Discriminator = 0;
2604 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2606 if (getLexer().is(AsmToken::EndOfStatement))
2610 SMLoc Loc = getTok().getLoc();
2611 if (parseIdentifier(Name))
2612 return TokError("unexpected token in '.loc' directive");
2614 if (Name == "basic_block")
2615 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2616 else if (Name == "prologue_end")
2617 Flags |= DWARF2_FLAG_PROLOGUE_END;
2618 else if (Name == "epilogue_begin")
2619 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2620 else if (Name == "is_stmt") {
2621 Loc = getTok().getLoc();
2622 const MCExpr *Value;
2623 if (parseExpression(Value))
2625 // The expression must be the constant 0 or 1.
2626 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2627 int Value = MCE->getValue();
2629 Flags &= ~DWARF2_FLAG_IS_STMT;
2630 else if (Value == 1)
2631 Flags |= DWARF2_FLAG_IS_STMT;
2633 return Error(Loc, "is_stmt value not 0 or 1");
2636 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2639 else if (Name == "isa") {
2640 Loc = getTok().getLoc();
2641 const MCExpr *Value;
2642 if (parseExpression(Value))
2644 // The expression must be a constant greater or equal to 0.
2645 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2646 int Value = MCE->getValue();
2648 return Error(Loc, "isa number less than zero");
2652 return Error(Loc, "isa number not a constant value");
2655 else if (Name == "discriminator") {
2656 if (parseAbsoluteExpression(Discriminator))
2660 return Error(Loc, "unknown sub-directive in '.loc' directive");
2663 if (getLexer().is(AsmToken::EndOfStatement))
2668 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2669 Isa, Discriminator, StringRef());
2674 /// ParseDirectiveStabs
2675 /// ::= .stabs string, number, number, number
2676 bool AsmParser::ParseDirectiveStabs() {
2677 return TokError("unsupported directive '.stabs'");
2680 /// ParseDirectiveCFISections
2681 /// ::= .cfi_sections section [, section]
2682 bool AsmParser::ParseDirectiveCFISections() {
2687 if (parseIdentifier(Name))
2688 return TokError("Expected an identifier");
2690 if (Name == ".eh_frame")
2692 else if (Name == ".debug_frame")
2695 if (getLexer().is(AsmToken::Comma)) {
2698 if (parseIdentifier(Name))
2699 return TokError("Expected an identifier");
2701 if (Name == ".eh_frame")
2703 else if (Name == ".debug_frame")
2707 getStreamer().EmitCFISections(EH, Debug);
2711 /// ParseDirectiveCFIStartProc
2712 /// ::= .cfi_startproc
2713 bool AsmParser::ParseDirectiveCFIStartProc() {
2714 getStreamer().EmitCFIStartProc();
2718 /// ParseDirectiveCFIEndProc
2719 /// ::= .cfi_endproc
2720 bool AsmParser::ParseDirectiveCFIEndProc() {
2721 getStreamer().EmitCFIEndProc();
2725 /// ParseRegisterOrRegisterNumber - parse register name or number.
2726 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2727 SMLoc DirectiveLoc) {
2730 if (getLexer().isNot(AsmToken::Integer)) {
2731 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2733 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2735 return parseAbsoluteExpression(Register);
2740 /// ParseDirectiveCFIDefCfa
2741 /// ::= .cfi_def_cfa register, offset
2742 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2743 int64_t Register = 0;
2744 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2747 if (getLexer().isNot(AsmToken::Comma))
2748 return TokError("unexpected token in directive");
2752 if (parseAbsoluteExpression(Offset))
2755 getStreamer().EmitCFIDefCfa(Register, Offset);
2759 /// ParseDirectiveCFIDefCfaOffset
2760 /// ::= .cfi_def_cfa_offset offset
2761 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2763 if (parseAbsoluteExpression(Offset))
2766 getStreamer().EmitCFIDefCfaOffset(Offset);
2770 /// ParseDirectiveCFIRegister
2771 /// ::= .cfi_register register, register
2772 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2773 int64_t Register1 = 0;
2774 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2777 if (getLexer().isNot(AsmToken::Comma))
2778 return TokError("unexpected token in directive");
2781 int64_t Register2 = 0;
2782 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2785 getStreamer().EmitCFIRegister(Register1, Register2);
2789 /// ParseDirectiveCFIAdjustCfaOffset
2790 /// ::= .cfi_adjust_cfa_offset adjustment
2791 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2792 int64_t Adjustment = 0;
2793 if (parseAbsoluteExpression(Adjustment))
2796 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2800 /// ParseDirectiveCFIDefCfaRegister
2801 /// ::= .cfi_def_cfa_register register
2802 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2803 int64_t Register = 0;
2804 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2807 getStreamer().EmitCFIDefCfaRegister(Register);
2811 /// ParseDirectiveCFIOffset
2812 /// ::= .cfi_offset register, offset
2813 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2814 int64_t Register = 0;
2817 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2820 if (getLexer().isNot(AsmToken::Comma))
2821 return TokError("unexpected token in directive");
2824 if (parseAbsoluteExpression(Offset))
2827 getStreamer().EmitCFIOffset(Register, Offset);
2831 /// ParseDirectiveCFIRelOffset
2832 /// ::= .cfi_rel_offset register, offset
2833 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2834 int64_t Register = 0;
2836 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2839 if (getLexer().isNot(AsmToken::Comma))
2840 return TokError("unexpected token in directive");
2844 if (parseAbsoluteExpression(Offset))
2847 getStreamer().EmitCFIRelOffset(Register, Offset);
2851 static bool isValidEncoding(int64_t Encoding) {
2852 if (Encoding & ~0xff)
2855 if (Encoding == dwarf::DW_EH_PE_omit)
2858 const unsigned Format = Encoding & 0xf;
2859 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2860 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2861 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2862 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2865 const unsigned Application = Encoding & 0x70;
2866 if (Application != dwarf::DW_EH_PE_absptr &&
2867 Application != dwarf::DW_EH_PE_pcrel)
2873 /// ParseDirectiveCFIPersonalityOrLsda
2874 /// IsPersonality true for cfi_personality, false for cfi_lsda
2875 /// ::= .cfi_personality encoding, [symbol_name]
2876 /// ::= .cfi_lsda encoding, [symbol_name]
2877 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2878 int64_t Encoding = 0;
2879 if (parseAbsoluteExpression(Encoding))
2881 if (Encoding == dwarf::DW_EH_PE_omit)
2884 if (!isValidEncoding(Encoding))
2885 return TokError("unsupported encoding.");
2887 if (getLexer().isNot(AsmToken::Comma))
2888 return TokError("unexpected token in directive");
2892 if (parseIdentifier(Name))
2893 return TokError("expected identifier in directive");
2895 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2898 getStreamer().EmitCFIPersonality(Sym, Encoding);
2900 getStreamer().EmitCFILsda(Sym, Encoding);
2904 /// ParseDirectiveCFIRememberState
2905 /// ::= .cfi_remember_state
2906 bool AsmParser::ParseDirectiveCFIRememberState() {
2907 getStreamer().EmitCFIRememberState();
2911 /// ParseDirectiveCFIRestoreState
2912 /// ::= .cfi_remember_state
2913 bool AsmParser::ParseDirectiveCFIRestoreState() {
2914 getStreamer().EmitCFIRestoreState();
2918 /// ParseDirectiveCFISameValue
2919 /// ::= .cfi_same_value register
2920 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2921 int64_t Register = 0;
2923 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2926 getStreamer().EmitCFISameValue(Register);
2930 /// ParseDirectiveCFIRestore
2931 /// ::= .cfi_restore register
2932 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2933 int64_t Register = 0;
2934 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2937 getStreamer().EmitCFIRestore(Register);
2941 /// ParseDirectiveCFIEscape
2942 /// ::= .cfi_escape expression[,...]
2943 bool AsmParser::ParseDirectiveCFIEscape() {
2946 if (parseAbsoluteExpression(CurrValue))
2949 Values.push_back((uint8_t)CurrValue);
2951 while (getLexer().is(AsmToken::Comma)) {
2954 if (parseAbsoluteExpression(CurrValue))
2957 Values.push_back((uint8_t)CurrValue);
2960 getStreamer().EmitCFIEscape(Values);
2964 /// ParseDirectiveCFISignalFrame
2965 /// ::= .cfi_signal_frame
2966 bool AsmParser::ParseDirectiveCFISignalFrame() {
2967 if (getLexer().isNot(AsmToken::EndOfStatement))
2968 return Error(getLexer().getLoc(),
2969 "unexpected token in '.cfi_signal_frame'");
2971 getStreamer().EmitCFISignalFrame();
2975 /// ParseDirectiveCFIUndefined
2976 /// ::= .cfi_undefined register
2977 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2978 int64_t Register = 0;
2980 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2983 getStreamer().EmitCFIUndefined(Register);
2987 /// ParseDirectiveMacrosOnOff
2990 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2991 if (getLexer().isNot(AsmToken::EndOfStatement))
2992 return Error(getLexer().getLoc(),
2993 "unexpected token in '" + Directive + "' directive");
2995 SetMacrosEnabled(Directive == ".macros_on");
2999 /// ParseDirectiveMacro
3000 /// ::= .macro name [parameters]
3001 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3003 if (parseIdentifier(Name))
3004 return TokError("expected identifier in '.macro' directive");
3006 MCAsmMacroParameters Parameters;
3007 // Argument delimiter is initially unknown. It will be set by
3008 // ParseMacroArgument()
3009 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3010 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3012 MCAsmMacroParameter Parameter;
3013 if (parseIdentifier(Parameter.first))
3014 return TokError("expected identifier in '.macro' directive");
3016 if (getLexer().is(AsmToken::Equal)) {
3018 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3022 Parameters.push_back(Parameter);
3024 if (getLexer().is(AsmToken::Comma))
3026 else if (getLexer().is(AsmToken::EndOfStatement))
3031 // Eat the end of statement.
3034 AsmToken EndToken, StartToken = getTok();
3036 // Lex the macro definition.
3038 // Check whether we have reached the end of the file.
3039 if (getLexer().is(AsmToken::Eof))
3040 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3042 // Otherwise, check whether we have reach the .endmacro.
3043 if (getLexer().is(AsmToken::Identifier) &&
3044 (getTok().getIdentifier() == ".endm" ||
3045 getTok().getIdentifier() == ".endmacro")) {
3046 EndToken = getTok();
3048 if (getLexer().isNot(AsmToken::EndOfStatement))
3049 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3054 // Otherwise, scan til the end of the statement.
3055 eatToEndOfStatement();
3058 if (LookupMacro(Name)) {
3059 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3062 const char *BodyStart = StartToken.getLoc().getPointer();
3063 const char *BodyEnd = EndToken.getLoc().getPointer();
3064 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3065 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
3066 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3070 /// CheckForBadMacro
3072 /// With the support added for named parameters there may be code out there that
3073 /// is transitioning from positional parameters. In versions of gas that did
3074 /// not support named parameters they would be ignored on the macro defintion.
3075 /// But to support both styles of parameters this is not possible so if a macro
3076 /// defintion has named parameters but does not use them and has what appears
3077 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3078 /// warning that the positional parameter found in body which have no effect.
3079 /// Hoping the developer will either remove the named parameters from the macro
3080 /// definiton so the positional parameters get used if that was what was
3081 /// intended or change the macro to use the named parameters. It is possible
3082 /// this warning will trigger when the none of the named parameters are used
3083 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3084 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3086 MCAsmMacroParameters Parameters) {
3087 // If this macro is not defined with named parameters the warning we are
3088 // checking for here doesn't apply.
3089 unsigned NParameters = Parameters.size();
3090 if (NParameters == 0)
3093 bool NamedParametersFound = false;
3094 bool PositionalParametersFound = false;
3096 // Look at the body of the macro for use of both the named parameters and what
3097 // are likely to be positional parameters. This is what expandMacro() is
3098 // doing when it finds the parameters in the body.
3099 while (!Body.empty()) {
3100 // Scan for the next possible parameter.
3101 std::size_t End = Body.size(), Pos = 0;
3102 for (; Pos != End; ++Pos) {
3103 // Check for a substitution or escape.
3104 // This macro is defined with parameters, look for \foo, \bar, etc.
3105 if (Body[Pos] == '\\' && Pos + 1 != End)
3108 // This macro should have parameters, but look for $0, $1, ..., $n too.
3109 if (Body[Pos] != '$' || Pos + 1 == End)
3111 char Next = Body[Pos + 1];
3112 if (Next == '$' || Next == 'n' ||
3113 isdigit(static_cast<unsigned char>(Next)))
3117 // Check if we reached the end.
3121 if (Body[Pos] == '$') {
3122 switch (Body[Pos+1]) {
3127 // $n => number of arguments
3129 PositionalParametersFound = true;
3132 // $[0-9] => argument
3134 PositionalParametersFound = true;
3140 unsigned I = Pos + 1;
3141 while (isIdentifierChar(Body[I]) && I + 1 != End)
3144 const char *Begin = Body.data() + Pos +1;
3145 StringRef Argument(Begin, I - (Pos +1));
3147 for (; Index < NParameters; ++Index)
3148 if (Parameters[Index].first == Argument)
3151 if (Index == NParameters) {
3152 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3158 NamedParametersFound = true;
3159 Pos += 1 + Argument.size();
3162 // Update the scan point.
3163 Body = Body.substr(Pos);
3166 if (!NamedParametersFound && PositionalParametersFound)
3167 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3168 "used in macro body, possible positional parameter "
3169 "found in body which will have no effect");
3172 /// ParseDirectiveEndMacro
3175 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3176 if (getLexer().isNot(AsmToken::EndOfStatement))
3177 return TokError("unexpected token in '" + Directive + "' directive");
3179 // If we are inside a macro instantiation, terminate the current
3181 if (InsideMacroInstantiation()) {
3186 // Otherwise, this .endmacro is a stray entry in the file; well formed
3187 // .endmacro directives are handled during the macro definition parsing.
3188 return TokError("unexpected '" + Directive + "' in file, "
3189 "no current macro definition");
3192 /// ParseDirectivePurgeMacro
3194 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3196 if (parseIdentifier(Name))
3197 return TokError("expected identifier in '.purgem' directive");
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return TokError("unexpected token in '.purgem' directive");
3202 if (!LookupMacro(Name))
3203 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3205 UndefineMacro(Name);
3209 /// ParseDirectiveBundleAlignMode
3210 /// ::= {.bundle_align_mode} expression
3211 bool AsmParser::ParseDirectiveBundleAlignMode() {
3212 checkForValidSection();
3214 // Expect a single argument: an expression that evaluates to a constant
3215 // in the inclusive range 0-30.
3216 SMLoc ExprLoc = getLexer().getLoc();
3217 int64_t AlignSizePow2;
3218 if (parseAbsoluteExpression(AlignSizePow2))
3220 else if (getLexer().isNot(AsmToken::EndOfStatement))
3221 return TokError("unexpected token after expression in"
3222 " '.bundle_align_mode' directive");
3223 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3224 return Error(ExprLoc,
3225 "invalid bundle alignment size (expected between 0 and 30)");
3229 // Because of AlignSizePow2's verified range we can safely truncate it to
3231 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3235 /// ParseDirectiveBundleLock
3236 /// ::= {.bundle_lock} [align_to_end]
3237 bool AsmParser::ParseDirectiveBundleLock() {
3238 checkForValidSection();
3239 bool AlignToEnd = false;
3241 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3243 SMLoc Loc = getTok().getLoc();
3244 const char *kInvalidOptionError =
3245 "invalid option for '.bundle_lock' directive";
3247 if (parseIdentifier(Option))
3248 return Error(Loc, kInvalidOptionError);
3250 if (Option != "align_to_end")
3251 return Error(Loc, kInvalidOptionError);
3252 else if (getLexer().isNot(AsmToken::EndOfStatement))
3254 "unexpected token after '.bundle_lock' directive option");
3260 getStreamer().EmitBundleLock(AlignToEnd);
3264 /// ParseDirectiveBundleLock
3265 /// ::= {.bundle_lock}
3266 bool AsmParser::ParseDirectiveBundleUnlock() {
3267 checkForValidSection();
3269 if (getLexer().isNot(AsmToken::EndOfStatement))
3270 return TokError("unexpected token in '.bundle_unlock' directive");
3273 getStreamer().EmitBundleUnlock();
3277 /// ParseDirectiveSpace
3278 /// ::= (.skip | .space) expression [ , expression ]
3279 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3280 checkForValidSection();
3283 if (parseAbsoluteExpression(NumBytes))
3286 int64_t FillExpr = 0;
3287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3288 if (getLexer().isNot(AsmToken::Comma))
3289 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3292 if (parseAbsoluteExpression(FillExpr))
3295 if (getLexer().isNot(AsmToken::EndOfStatement))
3296 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3302 return TokError("invalid number of bytes in '" +
3303 Twine(IDVal) + "' directive");
3305 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3306 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3311 /// ParseDirectiveLEB128
3312 /// ::= (.sleb128 | .uleb128) expression
3313 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3314 checkForValidSection();
3315 const MCExpr *Value;
3317 if (parseExpression(Value))
3320 if (getLexer().isNot(AsmToken::EndOfStatement))
3321 return TokError("unexpected token in directive");
3324 getStreamer().EmitSLEB128Value(Value);
3326 getStreamer().EmitULEB128Value(Value);
3331 /// ParseDirectiveSymbolAttribute
3332 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3333 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3334 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3337 SMLoc Loc = getTok().getLoc();
3339 if (parseIdentifier(Name))
3340 return Error(Loc, "expected identifier in directive");
3342 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3344 // Assembler local symbols don't make any sense here. Complain loudly.
3345 if (Sym->isTemporary())
3346 return Error(Loc, "non-local symbol required in directive");
3348 getStreamer().EmitSymbolAttribute(Sym, Attr);
3350 if (getLexer().is(AsmToken::EndOfStatement))
3353 if (getLexer().isNot(AsmToken::Comma))
3354 return TokError("unexpected token in directive");
3363 /// ParseDirectiveComm
3364 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3365 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3366 checkForValidSection();
3368 SMLoc IDLoc = getLexer().getLoc();
3370 if (parseIdentifier(Name))
3371 return TokError("expected identifier in directive");
3373 // Handle the identifier as the key symbol.
3374 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3376 if (getLexer().isNot(AsmToken::Comma))
3377 return TokError("unexpected token in directive");
3381 SMLoc SizeLoc = getLexer().getLoc();
3382 if (parseAbsoluteExpression(Size))
3385 int64_t Pow2Alignment = 0;
3386 SMLoc Pow2AlignmentLoc;
3387 if (getLexer().is(AsmToken::Comma)) {
3389 Pow2AlignmentLoc = getLexer().getLoc();
3390 if (parseAbsoluteExpression(Pow2Alignment))
3393 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3394 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3395 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3397 // If this target takes alignments in bytes (not log) validate and convert.
3398 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3399 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3400 if (!isPowerOf2_64(Pow2Alignment))
3401 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3402 Pow2Alignment = Log2_64(Pow2Alignment);
3406 if (getLexer().isNot(AsmToken::EndOfStatement))
3407 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3411 // NOTE: a size of zero for a .comm should create a undefined symbol
3412 // but a size of .lcomm creates a bss symbol of size zero.
3414 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3415 "be less than zero");
3417 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3418 // may internally end up wanting an alignment in bytes.
3419 // FIXME: Diagnose overflow.
3420 if (Pow2Alignment < 0)
3421 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3422 "alignment, can't be less than zero");
3424 if (!Sym->isUndefined())
3425 return Error(IDLoc, "invalid symbol redefinition");
3427 // Create the Symbol as a common or local common with Size and Pow2Alignment
3429 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3433 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3437 /// ParseDirectiveAbort
3438 /// ::= .abort [... message ...]
3439 bool AsmParser::ParseDirectiveAbort() {
3440 // FIXME: Use loc from directive.
3441 SMLoc Loc = getLexer().getLoc();
3443 StringRef Str = parseStringToEndOfStatement();
3444 if (getLexer().isNot(AsmToken::EndOfStatement))
3445 return TokError("unexpected token in '.abort' directive");
3450 Error(Loc, ".abort detected. Assembly stopping.");
3452 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3453 // FIXME: Actually abort assembly here.
3458 /// ParseDirectiveInclude
3459 /// ::= .include "filename"
3460 bool AsmParser::ParseDirectiveInclude() {
3461 if (getLexer().isNot(AsmToken::String))
3462 return TokError("expected string in '.include' directive");
3464 std::string Filename = getTok().getString();
3465 SMLoc IncludeLoc = getLexer().getLoc();
3468 if (getLexer().isNot(AsmToken::EndOfStatement))
3469 return TokError("unexpected token in '.include' directive");
3471 // Strip the quotes.
3472 Filename = Filename.substr(1, Filename.size()-2);
3474 // Attempt to switch the lexer to the included file before consuming the end
3475 // of statement to avoid losing it when we switch.
3476 if (EnterIncludeFile(Filename)) {
3477 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3484 /// ParseDirectiveIncbin
3485 /// ::= .incbin "filename"
3486 bool AsmParser::ParseDirectiveIncbin() {
3487 if (getLexer().isNot(AsmToken::String))
3488 return TokError("expected string in '.incbin' directive");
3490 std::string Filename = getTok().getString();
3491 SMLoc IncbinLoc = getLexer().getLoc();
3494 if (getLexer().isNot(AsmToken::EndOfStatement))
3495 return TokError("unexpected token in '.incbin' directive");
3497 // Strip the quotes.
3498 Filename = Filename.substr(1, Filename.size()-2);
3500 // Attempt to process the included file.
3501 if (ProcessIncbinFile(Filename)) {
3502 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3509 /// ParseDirectiveIf
3510 /// ::= .if expression
3511 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3512 TheCondStack.push_back(TheCondState);
3513 TheCondState.TheCond = AsmCond::IfCond;
3514 if (TheCondState.Ignore) {
3515 eatToEndOfStatement();
3518 if (parseAbsoluteExpression(ExprValue))
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token in '.if' directive");
3526 TheCondState.CondMet = ExprValue;
3527 TheCondState.Ignore = !TheCondState.CondMet;
3533 /// ParseDirectiveIfb
3535 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3536 TheCondStack.push_back(TheCondState);
3537 TheCondState.TheCond = AsmCond::IfCond;
3539 if (TheCondState.Ignore) {
3540 eatToEndOfStatement();
3542 StringRef Str = parseStringToEndOfStatement();
3544 if (getLexer().isNot(AsmToken::EndOfStatement))
3545 return TokError("unexpected token in '.ifb' directive");
3549 TheCondState.CondMet = ExpectBlank == Str.empty();
3550 TheCondState.Ignore = !TheCondState.CondMet;
3556 /// ParseDirectiveIfc
3557 /// ::= .ifc string1, string2
3558 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3559 TheCondStack.push_back(TheCondState);
3560 TheCondState.TheCond = AsmCond::IfCond;
3562 if (TheCondState.Ignore) {
3563 eatToEndOfStatement();
3565 StringRef Str1 = ParseStringToComma();
3567 if (getLexer().isNot(AsmToken::Comma))
3568 return TokError("unexpected token in '.ifc' directive");
3572 StringRef Str2 = parseStringToEndOfStatement();
3574 if (getLexer().isNot(AsmToken::EndOfStatement))
3575 return TokError("unexpected token in '.ifc' directive");
3579 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3580 TheCondState.Ignore = !TheCondState.CondMet;
3586 /// ParseDirectiveIfdef
3587 /// ::= .ifdef symbol
3588 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3590 TheCondStack.push_back(TheCondState);
3591 TheCondState.TheCond = AsmCond::IfCond;
3593 if (TheCondState.Ignore) {
3594 eatToEndOfStatement();
3596 if (parseIdentifier(Name))
3597 return TokError("expected identifier after '.ifdef'");
3601 MCSymbol *Sym = getContext().LookupSymbol(Name);
3604 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3606 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3607 TheCondState.Ignore = !TheCondState.CondMet;
3613 /// ParseDirectiveElseIf
3614 /// ::= .elseif expression
3615 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3616 if (TheCondState.TheCond != AsmCond::IfCond &&
3617 TheCondState.TheCond != AsmCond::ElseIfCond)
3618 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3620 TheCondState.TheCond = AsmCond::ElseIfCond;
3622 bool LastIgnoreState = false;
3623 if (!TheCondStack.empty())
3624 LastIgnoreState = TheCondStack.back().Ignore;
3625 if (LastIgnoreState || TheCondState.CondMet) {
3626 TheCondState.Ignore = true;
3627 eatToEndOfStatement();
3631 if (parseAbsoluteExpression(ExprValue))
3634 if (getLexer().isNot(AsmToken::EndOfStatement))
3635 return TokError("unexpected token in '.elseif' directive");
3638 TheCondState.CondMet = ExprValue;
3639 TheCondState.Ignore = !TheCondState.CondMet;
3645 /// ParseDirectiveElse
3647 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3648 if (getLexer().isNot(AsmToken::EndOfStatement))
3649 return TokError("unexpected token in '.else' directive");
3653 if (TheCondState.TheCond != AsmCond::IfCond &&
3654 TheCondState.TheCond != AsmCond::ElseIfCond)
3655 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3657 TheCondState.TheCond = AsmCond::ElseCond;
3658 bool LastIgnoreState = false;
3659 if (!TheCondStack.empty())
3660 LastIgnoreState = TheCondStack.back().Ignore;
3661 if (LastIgnoreState || TheCondState.CondMet)
3662 TheCondState.Ignore = true;
3664 TheCondState.Ignore = false;
3669 /// ParseDirectiveEndIf
3671 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3672 if (getLexer().isNot(AsmToken::EndOfStatement))
3673 return TokError("unexpected token in '.endif' directive");
3677 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3678 TheCondStack.empty())
3679 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3681 if (!TheCondStack.empty()) {
3682 TheCondState = TheCondStack.back();
3683 TheCondStack.pop_back();
3689 void AsmParser::initializeDirectiveKindMap() {
3690 DirectiveKindMap[".set"] = DK_SET;
3691 DirectiveKindMap[".equ"] = DK_EQU;
3692 DirectiveKindMap[".equiv"] = DK_EQUIV;
3693 DirectiveKindMap[".ascii"] = DK_ASCII;
3694 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3695 DirectiveKindMap[".string"] = DK_STRING;
3696 DirectiveKindMap[".byte"] = DK_BYTE;
3697 DirectiveKindMap[".short"] = DK_SHORT;
3698 DirectiveKindMap[".value"] = DK_VALUE;
3699 DirectiveKindMap[".2byte"] = DK_2BYTE;
3700 DirectiveKindMap[".long"] = DK_LONG;
3701 DirectiveKindMap[".int"] = DK_INT;
3702 DirectiveKindMap[".4byte"] = DK_4BYTE;
3703 DirectiveKindMap[".quad"] = DK_QUAD;
3704 DirectiveKindMap[".8byte"] = DK_8BYTE;
3705 DirectiveKindMap[".single"] = DK_SINGLE;
3706 DirectiveKindMap[".float"] = DK_FLOAT;
3707 DirectiveKindMap[".double"] = DK_DOUBLE;
3708 DirectiveKindMap[".align"] = DK_ALIGN;
3709 DirectiveKindMap[".align32"] = DK_ALIGN32;
3710 DirectiveKindMap[".balign"] = DK_BALIGN;
3711 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3712 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3713 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3714 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3715 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3716 DirectiveKindMap[".org"] = DK_ORG;
3717 DirectiveKindMap[".fill"] = DK_FILL;
3718 DirectiveKindMap[".zero"] = DK_ZERO;
3719 DirectiveKindMap[".extern"] = DK_EXTERN;
3720 DirectiveKindMap[".globl"] = DK_GLOBL;
3721 DirectiveKindMap[".global"] = DK_GLOBAL;
3722 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3723 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3724 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3725 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3726 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3727 DirectiveKindMap[".reference"] = DK_REFERENCE;
3728 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3729 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3730 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3731 DirectiveKindMap[".comm"] = DK_COMM;
3732 DirectiveKindMap[".common"] = DK_COMMON;
3733 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3734 DirectiveKindMap[".abort"] = DK_ABORT;
3735 DirectiveKindMap[".include"] = DK_INCLUDE;
3736 DirectiveKindMap[".incbin"] = DK_INCBIN;
3737 DirectiveKindMap[".code16"] = DK_CODE16;
3738 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3739 DirectiveKindMap[".rept"] = DK_REPT;
3740 DirectiveKindMap[".irp"] = DK_IRP;
3741 DirectiveKindMap[".irpc"] = DK_IRPC;
3742 DirectiveKindMap[".endr"] = DK_ENDR;
3743 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3744 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3745 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3746 DirectiveKindMap[".if"] = DK_IF;
3747 DirectiveKindMap[".ifb"] = DK_IFB;
3748 DirectiveKindMap[".ifnb"] = DK_IFNB;
3749 DirectiveKindMap[".ifc"] = DK_IFC;
3750 DirectiveKindMap[".ifnc"] = DK_IFNC;
3751 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3752 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3753 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3754 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3755 DirectiveKindMap[".else"] = DK_ELSE;
3756 DirectiveKindMap[".endif"] = DK_ENDIF;
3757 DirectiveKindMap[".skip"] = DK_SKIP;
3758 DirectiveKindMap[".space"] = DK_SPACE;
3759 DirectiveKindMap[".file"] = DK_FILE;
3760 DirectiveKindMap[".line"] = DK_LINE;
3761 DirectiveKindMap[".loc"] = DK_LOC;
3762 DirectiveKindMap[".stabs"] = DK_STABS;
3763 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3764 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3765 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3766 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3767 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3768 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3769 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3770 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3771 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3772 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3773 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3774 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3775 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3776 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3777 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3778 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3779 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3780 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3781 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3782 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3783 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3784 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3785 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3786 DirectiveKindMap[".macro"] = DK_MACRO;
3787 DirectiveKindMap[".endm"] = DK_ENDM;
3788 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3789 DirectiveKindMap[".purgem"] = DK_PURGEM;
3793 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3794 AsmToken EndToken, StartToken = getTok();
3796 unsigned NestLevel = 0;
3798 // Check whether we have reached the end of the file.
3799 if (getLexer().is(AsmToken::Eof)) {
3800 Error(DirectiveLoc, "no matching '.endr' in definition");
3804 if (Lexer.is(AsmToken::Identifier) &&
3805 (getTok().getIdentifier() == ".rept")) {
3809 // Otherwise, check whether we have reached the .endr.
3810 if (Lexer.is(AsmToken::Identifier) &&
3811 getTok().getIdentifier() == ".endr") {
3812 if (NestLevel == 0) {
3813 EndToken = getTok();
3815 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3816 TokError("unexpected token in '.endr' directive");
3824 // Otherwise, scan till the end of the statement.
3825 eatToEndOfStatement();
3828 const char *BodyStart = StartToken.getLoc().getPointer();
3829 const char *BodyEnd = EndToken.getLoc().getPointer();
3830 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3832 // We Are Anonymous.
3834 MCAsmMacroParameters Parameters;
3835 return new MCAsmMacro(Name, Body, Parameters);
3838 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3839 raw_svector_ostream &OS) {
3842 MemoryBuffer *Instantiation =
3843 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3845 // Create the macro instantiation object and add to the current macro
3846 // instantiation stack.
3847 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3851 ActiveMacros.push_back(MI);
3853 // Jump to the macro instantiation and prime the lexer.
3854 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3855 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3859 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3861 if (parseAbsoluteExpression(Count))
3862 return TokError("unexpected token in '.rept' directive");
3865 return TokError("Count is negative");
3867 if (Lexer.isNot(AsmToken::EndOfStatement))
3868 return TokError("unexpected token in '.rept' directive");
3870 // Eat the end of statement.
3873 // Lex the rept definition.
3874 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3878 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3879 // to hold the macro body with substitutions.
3880 SmallString<256> Buf;
3881 MCAsmMacroParameters Parameters;
3882 MCAsmMacroArguments A;
3883 raw_svector_ostream OS(Buf);
3885 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3888 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3893 /// ParseDirectiveIrp
3894 /// ::= .irp symbol,values
3895 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3896 MCAsmMacroParameters Parameters;
3897 MCAsmMacroParameter Parameter;
3899 if (parseIdentifier(Parameter.first))
3900 return TokError("expected identifier in '.irp' directive");
3902 Parameters.push_back(Parameter);
3904 if (Lexer.isNot(AsmToken::Comma))
3905 return TokError("expected comma in '.irp' directive");
3909 MCAsmMacroArguments A;
3910 if (ParseMacroArguments(0, A))
3913 // Eat the end of statement.
3916 // Lex the irp definition.
3917 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3921 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3922 // to hold the macro body with substitutions.
3923 SmallString<256> Buf;
3924 raw_svector_ostream OS(Buf);
3926 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3927 MCAsmMacroArguments Args;
3930 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3934 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3939 /// ParseDirectiveIrpc
3940 /// ::= .irpc symbol,values
3941 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3942 MCAsmMacroParameters Parameters;
3943 MCAsmMacroParameter Parameter;
3945 if (parseIdentifier(Parameter.first))
3946 return TokError("expected identifier in '.irpc' directive");
3948 Parameters.push_back(Parameter);
3950 if (Lexer.isNot(AsmToken::Comma))
3951 return TokError("expected comma in '.irpc' directive");
3955 MCAsmMacroArguments A;
3956 if (ParseMacroArguments(0, A))
3959 if (A.size() != 1 || A.front().size() != 1)
3960 return TokError("unexpected token in '.irpc' directive");
3962 // Eat the end of statement.
3965 // Lex the irpc definition.
3966 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3970 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3971 // to hold the macro body with substitutions.
3972 SmallString<256> Buf;
3973 raw_svector_ostream OS(Buf);
3975 StringRef Values = A.front().front().getString();
3976 std::size_t I, End = Values.size();
3977 for (I = 0; I < End; ++I) {
3978 MCAsmMacroArgument Arg;
3979 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3981 MCAsmMacroArguments Args;
3982 Args.push_back(Arg);
3984 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3988 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3993 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3994 if (ActiveMacros.empty())
3995 return TokError("unmatched '.endr' directive");
3997 // The only .repl that should get here are the ones created by
3998 // InstantiateMacroLikeBody.
3999 assert(getLexer().is(AsmToken::EndOfStatement));
4005 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4007 const MCExpr *Value;
4008 SMLoc ExprLoc = getLexer().getLoc();
4009 if (parseExpression(Value))
4011 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4013 return Error(ExprLoc, "unexpected expression in _emit");
4014 uint64_t IntValue = MCE->getValue();
4015 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4016 return Error(ExprLoc, "literal value out of range for directive");
4018 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4022 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4023 const MCExpr *Value;
4024 SMLoc ExprLoc = getLexer().getLoc();
4025 if (parseExpression(Value))
4027 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4029 return Error(ExprLoc, "unexpected expression in align");
4030 uint64_t IntValue = MCE->getValue();
4031 if (!isPowerOf2_64(IntValue))
4032 return Error(ExprLoc, "literal value not a power of two greater then zero");
4034 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4035 Log2_64(IntValue)));
4039 // We are comparing pointers, but the pointers are relative to a single string.
4040 // Thus, this should always be deterministic.
4041 static int RewritesSort(const void *A, const void *B) {
4042 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4043 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
4044 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4046 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4049 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4050 // rewrite to the same location. Make sure the SizeDirective rewrite is
4051 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4052 // ensures the sort algorithm is stable.
4053 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4054 AsmRewritePrecedence [AsmRewriteB->Kind])
4057 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4058 AsmRewritePrecedence [AsmRewriteB->Kind])
4060 llvm_unreachable ("Unstable rewrite sort.");
4064 AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4065 unsigned &NumOutputs, unsigned &NumInputs,
4066 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4067 SmallVectorImpl<std::string> &Constraints,
4068 SmallVectorImpl<std::string> &Clobbers,
4069 const MCInstrInfo *MII,
4070 const MCInstPrinter *IP,
4071 MCAsmParserSemaCallback &SI) {
4072 SmallVector<void *, 4> InputDecls;
4073 SmallVector<void *, 4> OutputDecls;
4074 SmallVector<bool, 4> InputDeclsAddressOf;
4075 SmallVector<bool, 4> OutputDeclsAddressOf;
4076 SmallVector<std::string, 4> InputConstraints;
4077 SmallVector<std::string, 4> OutputConstraints;
4078 SmallVector<unsigned, 4> ClobberRegs;
4080 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4085 // While we have input, parse each statement.
4086 unsigned InputIdx = 0;
4087 unsigned OutputIdx = 0;
4088 while (getLexer().isNot(AsmToken::Eof)) {
4089 ParseStatementInfo Info(&AsmStrRewrites);
4090 if (ParseStatement(Info))
4093 if (Info.ParseError)
4096 if (Info.Opcode == ~0U)
4099 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4101 // Build the list of clobbers, outputs and inputs.
4102 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4103 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4106 if (Operand->isImm())
4109 // Register operand.
4110 if (Operand->isReg() && !Operand->needAddressOf()) {
4111 unsigned NumDefs = Desc.getNumDefs();
4113 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4114 ClobberRegs.push_back(Operand->getReg());
4118 // Expr/Input or Output.
4120 unsigned Length, Size, Type;
4121 StringRef SymName = Operand->getSymName();
4122 if (SymName.empty())
4125 void *OpDecl = SI.LookupInlineAsmIdentifier(SymName, AsmLoc,
4131 bool isOutput = (i == 1) && Desc.mayStore();
4132 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4135 OutputDecls.push_back(OpDecl);
4136 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4137 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4138 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4140 InputDecls.push_back(OpDecl);
4141 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4142 InputConstraints.push_back(Operand->getConstraint().str());
4143 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4148 // Set the number of Outputs and Inputs.
4149 NumOutputs = OutputDecls.size();
4150 NumInputs = InputDecls.size();
4152 // Set the unique clobbers.
4153 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4154 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4156 Clobbers.assign(ClobberRegs.size(), std::string());
4157 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4158 raw_string_ostream OS(Clobbers[I]);
4159 IP->printRegName(OS, ClobberRegs[I]);
4162 // Merge the various outputs and inputs. Output are expected first.
4163 if (NumOutputs || NumInputs) {
4164 unsigned NumExprs = NumOutputs + NumInputs;
4165 OpDecls.resize(NumExprs);
4166 Constraints.resize(NumExprs);
4167 for (unsigned i = 0; i < NumOutputs; ++i) {
4168 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4169 Constraints[i] = OutputConstraints[i];
4171 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4172 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4173 Constraints[j] = InputConstraints[i];
4177 // Build the IR assembly string.
4178 std::string AsmStringIR;
4179 raw_string_ostream OS(AsmStringIR);
4180 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4181 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4182 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4183 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4184 E = AsmStrRewrites.end();
4186 const char *Loc = (*I).Loc.getPointer();
4187 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4189 unsigned AdditionalSkip = 0;
4190 AsmRewriteKind Kind = (*I).Kind;
4192 // Emit everything up to the immediate/expression.
4193 unsigned Len = Loc - AsmStart;
4195 // For Input/Output operands we need to remove the brackets, if present.
4196 if ((Kind == AOK_Input || Kind == AOK_Output) && Loc[-1] == '[')
4198 OS << StringRef(AsmStart, Len);
4201 // Skip the original expression.
4202 if (Kind == AOK_Skip) {
4203 AsmStart = Loc + (*I).Len;
4207 // Rewrite expressions in $N notation.
4211 OS << "$$" << (*I).Val;
4217 OS << '$' << InputIdx++;
4220 OS << '$' << OutputIdx++;
4222 case AOK_SizeDirective:
4225 case 8: OS << "byte ptr "; break;
4226 case 16: OS << "word ptr "; break;
4227 case 32: OS << "dword ptr "; break;
4228 case 64: OS << "qword ptr "; break;
4229 case 80: OS << "xword ptr "; break;
4230 case 128: OS << "xmmword ptr "; break;
4231 case 256: OS << "ymmword ptr "; break;
4238 unsigned Val = (*I).Val;
4239 OS << ".align " << Val;
4241 // Skip the original immediate.
4242 assert(Val < 10 && "Expected alignment less then 2^10.");
4243 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4246 case AOK_DotOperator:
4251 // Skip the original expression.
4252 AsmStart = Loc + (*I).Len + AdditionalSkip;
4254 // For Input/Output operands we need to remove the brackets, if present.
4255 if ((Kind == AOK_Input || Kind == AOK_Output) && AsmStart != AsmEnd &&
4260 // Emit the remainder of the asm string.
4261 if (AsmStart != AsmEnd)
4262 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4264 AsmString = OS.str();
4268 /// \brief Create an MCAsmParser instance.
4269 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4270 MCContext &C, MCStreamer &Out,
4271 const MCAsmInfo &MAI) {
4272 return new AsmParser(SM, C, Out, MAI);