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 = None);
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = None);
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 parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
225 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool parseAbsoluteExpression(int64_t &Res);
228 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
229 /// and set \p Res to the identifier contents.
230 virtual bool parseIdentifier(StringRef &Res);
231 virtual void eatToEndOfStatement();
233 virtual void checkForValidSection();
238 bool ParseStatement(ParseStatementInfo &Info);
239 void EatToEndOfLine();
240 bool ParseCppHashLineFilenameComment(const SMLoc &L);
242 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
243 MCAsmMacroParameters Parameters);
244 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
245 const MCAsmMacroParameters &Parameters,
246 const MCAsmMacroArguments &A,
249 /// \brief Are macros enabled in the parser?
250 bool MacrosEnabled() {return MacrosEnabledFlag;}
252 /// \brief Control a flag in the parser that enables or disables macros.
253 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
255 /// \brief Lookup a previously defined macro.
256 /// \param Name Macro name.
257 /// \returns Pointer to macro. NULL if no such macro was defined.
258 const MCAsmMacro* LookupMacro(StringRef Name);
260 /// \brief Define a new macro with the given name and information.
261 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
263 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
264 void UndefineMacro(StringRef Name);
266 /// \brief Are we inside a macro instantiation?
267 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
269 /// \brief Handle entry to macro instantiation.
271 /// \param M The macro.
272 /// \param NameLoc Instantiation location.
273 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
275 /// \brief Handle exit from macro instantiation.
276 void HandleMacroExit();
278 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
279 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
280 /// correct delimiter by the method.
281 bool ParseMacroArgument(MCAsmMacroArgument &MA,
282 AsmToken::TokenKind &ArgumentDelimiter);
284 /// \brief Parse all macro arguments for a given macro.
285 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
287 void PrintMacroInstantiations();
288 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
289 ArrayRef<SMRange> Ranges = None) const {
290 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
292 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
294 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
295 bool EnterIncludeFile(const std::string &Filename);
296 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
297 /// This returns true on failure.
298 bool ProcessIncbinFile(const std::string &Filename);
300 /// \brief Reset the current lexer position to that given by \p Loc. The
301 /// current token is not set; clients should ensure Lex() is called
304 /// \param InBuffer If not -1, should be the known buffer id that contains the
306 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
308 /// \brief Parse up to the end of statement and a return the contents from the
309 /// current token until the end of the statement; the current token on exit
310 /// will be either the EndOfStatement or EOF.
311 virtual StringRef parseStringToEndOfStatement();
313 /// \brief Parse until the end of a statement or a comma is encountered,
314 /// return the contents from the current token up to the end or comma.
315 StringRef ParseStringToComma();
317 bool ParseAssignment(StringRef Name, bool allow_redef,
318 bool NoDeadStrip = false);
320 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
322 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
323 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
325 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
327 // Generic (target and platform independent) directive parsing.
329 DK_NO_DIRECTIVE, // Placeholder
330 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
331 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
332 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
333 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
334 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
335 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
336 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
337 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
338 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
339 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
340 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
341 DK_ELSEIF, DK_ELSE, DK_ENDIF,
342 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
343 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
344 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
345 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
346 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
347 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
349 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
350 DK_SLEB128, DK_ULEB128
353 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
354 /// directives parsed by this class.
355 StringMap<DirectiveKind> DirectiveKindMap;
357 // ".ascii", ".asciz", ".string"
358 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
359 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
360 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
361 bool ParseDirectiveFill(); // ".fill"
362 bool ParseDirectiveZero(); // ".zero"
363 // ".set", ".equ", ".equiv"
364 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
365 bool ParseDirectiveOrg(); // ".org"
366 // ".align{,32}", ".p2align{,w,l}"
367 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
369 // ".file", ".line", ".loc", ".stabs"
370 bool ParseDirectiveFile(SMLoc DirectiveLoc);
371 bool ParseDirectiveLine();
372 bool ParseDirectiveLoc();
373 bool ParseDirectiveStabs();
376 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISections();
378 bool ParseDirectiveCFIStartProc();
379 bool ParseDirectiveCFIEndProc();
380 bool ParseDirectiveCFIDefCfaOffset();
381 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIAdjustCfaOffset();
383 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
387 bool ParseDirectiveCFIRememberState();
388 bool ParseDirectiveCFIRestoreState();
389 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIEscape();
392 bool ParseDirectiveCFISignalFrame();
393 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
396 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveEndMacro(StringRef Directive);
398 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
399 bool ParseDirectiveMacrosOnOff(StringRef Directive);
401 // ".bundle_align_mode"
402 bool ParseDirectiveBundleAlignMode();
404 bool ParseDirectiveBundleLock();
406 bool ParseDirectiveBundleUnlock();
409 bool ParseDirectiveSpace(StringRef IDVal);
411 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
412 bool ParseDirectiveLEB128(bool Signed);
414 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
415 /// accepts a single symbol (which should be a label or an external).
416 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
418 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
420 bool ParseDirectiveAbort(); // ".abort"
421 bool ParseDirectiveInclude(); // ".include"
422 bool ParseDirectiveIncbin(); // ".incbin"
424 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
425 // ".ifb" or ".ifnb", depending on ExpectBlank.
426 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
427 // ".ifc" or ".ifnc", depending on ExpectEqual.
428 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
429 // ".ifdef" or ".ifndef", depending on expect_defined
430 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
431 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
432 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
433 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
434 virtual bool parseEscapedString(std::string &Data);
436 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
437 MCSymbolRefExpr::VariantKind Variant);
439 // Macro-like directives
440 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
441 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
442 raw_svector_ostream &OS);
443 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
444 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
445 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
446 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
448 // "_emit" or "__emit"
449 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
453 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
455 void initializeDirectiveKindMap();
461 extern MCAsmParserExtension *createDarwinAsmParser();
462 extern MCAsmParserExtension *createELFAsmParser();
463 extern MCAsmParserExtension *createCOFFAsmParser();
467 enum { DEFAULT_ADDRSPACE = 0 };
469 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
470 MCStreamer &_Out, const MCAsmInfo &_MAI)
471 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
473 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
474 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
475 // Save the old handler.
476 SavedDiagHandler = SrcMgr.getDiagHandler();
477 SavedDiagContext = SrcMgr.getDiagContext();
478 // Set our own handler which calls the saved handler.
479 SrcMgr.setDiagHandler(DiagHandler, this);
480 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
482 // Initialize the platform / file format parser.
484 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
486 if (_MAI.hasMicrosoftFastStdCallMangling()) {
487 PlatformParser = createCOFFAsmParser();
488 PlatformParser->Initialize(*this);
489 } else if (_MAI.hasSubsectionsViaSymbols()) {
490 PlatformParser = createDarwinAsmParser();
491 PlatformParser->Initialize(*this);
494 PlatformParser = createELFAsmParser();
495 PlatformParser->Initialize(*this);
498 initializeDirectiveKindMap();
501 AsmParser::~AsmParser() {
502 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
504 // Destroy any macros.
505 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
506 ie = MacroMap.end(); it != ie; ++it)
507 delete it->getValue();
509 delete PlatformParser;
512 void AsmParser::PrintMacroInstantiations() {
513 // Print the active macro instantiation stack.
514 for (std::vector<MacroInstantiation*>::const_reverse_iterator
515 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
516 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
517 "while in macro instantiation");
520 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
521 if (FatalAssemblerWarnings)
522 return Error(L, Msg, Ranges);
523 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
524 PrintMacroInstantiations();
528 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
530 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
531 PrintMacroInstantiations();
535 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
536 std::string IncludedFile;
537 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
543 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
548 /// Process the specified .incbin file by searching for it in the include paths
549 /// then just emitting the byte contents of the file to the streamer. This
550 /// returns true on failure.
551 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
552 std::string IncludedFile;
553 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
557 // Pick up the bytes from the file and emit them.
558 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
563 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
564 if (InBuffer != -1) {
565 CurBuffer = InBuffer;
567 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
572 const AsmToken &AsmParser::Lex() {
573 const AsmToken *tok = &Lexer.Lex();
575 if (tok->is(AsmToken::Eof)) {
576 // If this is the end of an included file, pop the parent file off the
578 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
579 if (ParentIncludeLoc != SMLoc()) {
580 JumpToLoc(ParentIncludeLoc);
585 if (tok->is(AsmToken::Error))
586 Error(Lexer.getErrLoc(), Lexer.getErr());
591 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
592 // Create the initial section, if requested.
593 if (!NoInitialTextSection)
600 AsmCond StartingCondState = TheCondState;
602 // If we are generating dwarf for assembly source files save the initial text
603 // section and generate a .file directive.
604 if (getContext().getGenDwarfForAssembly()) {
605 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
606 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
607 getStreamer().EmitLabel(SectionStartSym);
608 getContext().setGenDwarfSectionStartSym(SectionStartSym);
609 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
611 getContext().getMainFileName());
614 // While we have input, parse each statement.
615 while (Lexer.isNot(AsmToken::Eof)) {
616 ParseStatementInfo Info;
617 if (!ParseStatement(Info)) continue;
619 // We had an error, validate that one was emitted and recover by skipping to
621 assert(HadError && "Parse statement returned an error, but none emitted!");
622 eatToEndOfStatement();
625 if (TheCondState.TheCond != StartingCondState.TheCond ||
626 TheCondState.Ignore != StartingCondState.Ignore)
627 return TokError("unmatched .ifs or .elses");
629 // Check to see there are no empty DwarfFile slots.
630 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
631 getContext().getMCDwarfFiles();
632 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
633 if (!MCDwarfFiles[i])
634 TokError("unassigned file number: " + Twine(i) + " for .file directives");
637 // Check to see that all assembler local symbols were actually defined.
638 // Targets that don't do subsections via symbols may not want this, though,
639 // so conservatively exclude them. Only do this if we're finalizing, though,
640 // as otherwise we won't necessarilly have seen everything yet.
641 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
642 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
643 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
646 MCSymbol *Sym = i->getValue();
647 // Variable symbols may not be marked as defined, so check those
648 // explicitly. If we know it's a variable, we have a definition for
649 // the purposes of this check.
650 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
651 // FIXME: We would really like to refer back to where the symbol was
652 // first referenced for a source location. We need to add something
653 // to track that. Currently, we just point to the end of the file.
654 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
655 "assembler local symbol '" + Sym->getName() +
661 // Finalize the output stream if there are no errors and if the client wants
663 if (!HadError && !NoFinalize)
669 void AsmParser::checkForValidSection() {
670 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
671 TokError("expected section directive before assembly directive");
672 Out.InitToTextSection();
676 /// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
677 void AsmParser::eatToEndOfStatement() {
678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
683 if (Lexer.is(AsmToken::EndOfStatement))
687 StringRef AsmParser::parseStringToEndOfStatement() {
688 const char *Start = getTok().getLoc().getPointer();
690 while (Lexer.isNot(AsmToken::EndOfStatement) &&
691 Lexer.isNot(AsmToken::Eof))
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
698 StringRef AsmParser::ParseStringToComma() {
699 const char *Start = getTok().getLoc().getPointer();
701 while (Lexer.isNot(AsmToken::EndOfStatement) &&
702 Lexer.isNot(AsmToken::Comma) &&
703 Lexer.isNot(AsmToken::Eof))
706 const char *End = getTok().getLoc().getPointer();
707 return StringRef(Start, End - Start);
710 /// ParseParenExpr - Parse a paren expression and return it.
711 /// NOTE: This assumes the leading '(' has already been consumed.
713 /// parenexpr ::= expr)
715 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
716 if (parseExpression(Res)) return true;
717 if (Lexer.isNot(AsmToken::RParen))
718 return TokError("expected ')' in parentheses expression");
719 EndLoc = Lexer.getTok().getEndLoc();
724 /// ParseBracketExpr - Parse a bracket expression and return it.
725 /// NOTE: This assumes the leading '[' has already been consumed.
727 /// bracketexpr ::= expr]
729 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
730 if (parseExpression(Res)) return true;
731 if (Lexer.isNot(AsmToken::RBrac))
732 return TokError("expected ']' in brackets expression");
733 EndLoc = Lexer.getTok().getEndLoc();
738 /// ParsePrimaryExpr - Parse a primary expression and return it.
739 /// primaryexpr ::= (parenexpr
740 /// primaryexpr ::= symbol
741 /// primaryexpr ::= number
742 /// primaryexpr ::= '.'
743 /// primaryexpr ::= ~,+,- primaryexpr
744 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
745 SMLoc FirstTokenLoc = getLexer().getLoc();
746 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
747 switch (FirstTokenKind) {
749 return TokError("unknown token in expression");
750 // If we have an error assume that we've already handled it.
751 case AsmToken::Error:
753 case AsmToken::Exclaim:
754 Lex(); // Eat the operator.
755 if (ParsePrimaryExpr(Res, EndLoc))
757 Res = MCUnaryExpr::CreateLNot(Res, getContext());
759 case AsmToken::Dollar:
760 case AsmToken::String:
761 case AsmToken::Identifier: {
762 StringRef Identifier;
763 if (parseIdentifier(Identifier)) {
764 if (FirstTokenKind == AsmToken::Dollar)
765 return Error(FirstTokenLoc, "invalid token in expression");
769 EndLoc = SMLoc::getFromPointer(Identifier.end());
771 // This is a symbol reference.
772 std::pair<StringRef, StringRef> Split = Identifier.split('@');
773 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
775 // Lookup the symbol variant if used.
776 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
777 if (Split.first.size() != Identifier.size()) {
778 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
779 if (Variant == MCSymbolRefExpr::VK_Invalid) {
780 Variant = MCSymbolRefExpr::VK_None;
781 return TokError("invalid variant '" + Split.second + "'");
785 // If this is an absolute variable reference, substitute it now to preserve
786 // semantics in the face of reassignment.
787 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
789 return Error(EndLoc, "unexpected modifier on variable reference");
791 Res = Sym->getVariableValue();
795 // Otherwise create a symbol ref.
796 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
799 case AsmToken::Integer: {
800 SMLoc Loc = getTok().getLoc();
801 int64_t IntVal = getTok().getIntVal();
802 Res = MCConstantExpr::Create(IntVal, getContext());
803 EndLoc = Lexer.getTok().getEndLoc();
805 // Look for 'b' or 'f' following an Integer as a directional label
806 if (Lexer.getKind() == AsmToken::Identifier) {
807 StringRef IDVal = getTok().getString();
808 if (IDVal == "f" || IDVal == "b"){
809 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
810 IDVal == "f" ? 1 : 0);
811 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
813 if (IDVal == "b" && Sym->isUndefined())
814 return Error(Loc, "invalid reference to undefined symbol");
815 EndLoc = Lexer.getTok().getEndLoc();
816 Lex(); // Eat identifier.
821 case AsmToken::Real: {
822 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
823 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
824 Res = MCConstantExpr::Create(IntVal, getContext());
825 EndLoc = Lexer.getTok().getEndLoc();
829 case AsmToken::Dot: {
830 // This is a '.' reference, which references the current PC. Emit a
831 // temporary label to the streamer and refer to it.
832 MCSymbol *Sym = Ctx.CreateTempSymbol();
834 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
835 EndLoc = Lexer.getTok().getEndLoc();
836 Lex(); // Eat identifier.
839 case AsmToken::LParen:
840 Lex(); // Eat the '('.
841 return ParseParenExpr(Res, EndLoc);
842 case AsmToken::LBrac:
843 if (!PlatformParser->HasBracketExpressions())
844 return TokError("brackets expression not supported on this target");
845 Lex(); // Eat the '['.
846 return ParseBracketExpr(Res, EndLoc);
847 case AsmToken::Minus:
848 Lex(); // Eat the operator.
849 if (ParsePrimaryExpr(Res, EndLoc))
851 Res = MCUnaryExpr::CreateMinus(Res, getContext());
854 Lex(); // Eat the operator.
855 if (ParsePrimaryExpr(Res, EndLoc))
857 Res = MCUnaryExpr::CreatePlus(Res, getContext());
859 case AsmToken::Tilde:
860 Lex(); // Eat the operator.
861 if (ParsePrimaryExpr(Res, EndLoc))
863 Res = MCUnaryExpr::CreateNot(Res, getContext());
868 bool AsmParser::parseExpression(const MCExpr *&Res) {
870 return parseExpression(Res, EndLoc);
873 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
874 return ParsePrimaryExpr(Res, EndLoc);
878 AsmParser::ApplyModifierToExpr(const MCExpr *E,
879 MCSymbolRefExpr::VariantKind Variant) {
880 // Recurse over the given expression, rebuilding it to apply the given variant
881 // if there is exactly one symbol.
882 switch (E->getKind()) {
884 case MCExpr::Constant:
887 case MCExpr::SymbolRef: {
888 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
890 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
891 TokError("invalid variant on expression '" +
892 getTok().getIdentifier() + "' (already modified)");
896 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
899 case MCExpr::Unary: {
900 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
901 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
904 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
907 case MCExpr::Binary: {
908 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
909 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
910 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
915 if (!LHS) LHS = BE->getLHS();
916 if (!RHS) RHS = BE->getRHS();
918 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
922 llvm_unreachable("Invalid expression kind!");
925 /// parseExpression - Parse an expression and return it.
927 /// expr ::= expr &&,|| expr -> lowest.
928 /// expr ::= expr |,^,&,! expr
929 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
930 /// expr ::= expr <<,>> expr
931 /// expr ::= expr +,- expr
932 /// expr ::= expr *,/,% expr -> highest.
933 /// expr ::= primaryexpr
935 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
936 // Parse the expression.
938 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
941 // As a special case, we support 'a op b @ modifier' by rewriting the
942 // expression to include the modifier. This is inefficient, but in general we
943 // expect users to use 'a@modifier op b'.
944 if (Lexer.getKind() == AsmToken::At) {
947 if (Lexer.isNot(AsmToken::Identifier))
948 return TokError("unexpected symbol modifier following '@'");
950 MCSymbolRefExpr::VariantKind Variant =
951 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
952 if (Variant == MCSymbolRefExpr::VK_Invalid)
953 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
955 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
957 return TokError("invalid modifier '" + getTok().getIdentifier() +
958 "' (no symbols present)");
965 // Try to constant fold it up front, if possible.
967 if (Res->EvaluateAsAbsolute(Value))
968 Res = MCConstantExpr::Create(Value, getContext());
973 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
975 return ParseParenExpr(Res, EndLoc) ||
976 ParseBinOpRHS(1, Res, EndLoc);
979 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
982 SMLoc StartLoc = Lexer.getLoc();
983 if (parseExpression(Expr))
986 if (!Expr->EvaluateAsAbsolute(Res))
987 return Error(StartLoc, "expected absolute expression");
992 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
993 MCBinaryExpr::Opcode &Kind) {
996 return 0; // not a binop.
998 // Lowest Precedence: &&, ||
999 case AsmToken::AmpAmp:
1000 Kind = MCBinaryExpr::LAnd;
1002 case AsmToken::PipePipe:
1003 Kind = MCBinaryExpr::LOr;
1007 // Low Precedence: |, &, ^
1009 // FIXME: gas seems to support '!' as an infix operator?
1010 case AsmToken::Pipe:
1011 Kind = MCBinaryExpr::Or;
1013 case AsmToken::Caret:
1014 Kind = MCBinaryExpr::Xor;
1017 Kind = MCBinaryExpr::And;
1020 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1021 case AsmToken::EqualEqual:
1022 Kind = MCBinaryExpr::EQ;
1024 case AsmToken::ExclaimEqual:
1025 case AsmToken::LessGreater:
1026 Kind = MCBinaryExpr::NE;
1028 case AsmToken::Less:
1029 Kind = MCBinaryExpr::LT;
1031 case AsmToken::LessEqual:
1032 Kind = MCBinaryExpr::LTE;
1034 case AsmToken::Greater:
1035 Kind = MCBinaryExpr::GT;
1037 case AsmToken::GreaterEqual:
1038 Kind = MCBinaryExpr::GTE;
1041 // Intermediate Precedence: <<, >>
1042 case AsmToken::LessLess:
1043 Kind = MCBinaryExpr::Shl;
1045 case AsmToken::GreaterGreater:
1046 Kind = MCBinaryExpr::Shr;
1049 // High Intermediate Precedence: +, -
1050 case AsmToken::Plus:
1051 Kind = MCBinaryExpr::Add;
1053 case AsmToken::Minus:
1054 Kind = MCBinaryExpr::Sub;
1057 // Highest Precedence: *, /, %
1058 case AsmToken::Star:
1059 Kind = MCBinaryExpr::Mul;
1061 case AsmToken::Slash:
1062 Kind = MCBinaryExpr::Div;
1064 case AsmToken::Percent:
1065 Kind = MCBinaryExpr::Mod;
1071 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1072 /// Res contains the LHS of the expression on input.
1073 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1076 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1077 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1079 // If the next token is lower precedence than we are allowed to eat, return
1080 // successfully with what we ate already.
1081 if (TokPrec < Precedence)
1086 // Eat the next primary expression.
1088 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1090 // If BinOp binds less tightly with RHS than the operator after RHS, let
1091 // the pending operator take RHS as its LHS.
1092 MCBinaryExpr::Opcode Dummy;
1093 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1094 if (TokPrec < NextTokPrec) {
1095 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
1098 // Merge LHS and RHS according to operator.
1099 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1104 /// ::= EndOfStatement
1105 /// ::= Label* Directive ...Operands... EndOfStatement
1106 /// ::= Label* Identifier OperandList* EndOfStatement
1107 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1108 if (Lexer.is(AsmToken::EndOfStatement)) {
1114 // Statements always start with an identifier or are a full line comment.
1115 AsmToken ID = getTok();
1116 SMLoc IDLoc = ID.getLoc();
1118 int64_t LocalLabelVal = -1;
1119 // A full line comment is a '#' as the first token.
1120 if (Lexer.is(AsmToken::Hash))
1121 return ParseCppHashLineFilenameComment(IDLoc);
1123 // Allow an integer followed by a ':' as a directional local label.
1124 if (Lexer.is(AsmToken::Integer)) {
1125 LocalLabelVal = getTok().getIntVal();
1126 if (LocalLabelVal < 0) {
1127 if (!TheCondState.Ignore)
1128 return TokError("unexpected token at start of statement");
1131 IDVal = getTok().getString();
1132 Lex(); // Consume the integer token to be used as an identifier token.
1133 if (Lexer.getKind() != AsmToken::Colon) {
1134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
1138 } else if (Lexer.is(AsmToken::Dot)) {
1139 // Treat '.' as a valid identifier in this context.
1142 } else if (parseIdentifier(IDVal)) {
1143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1148 // Handle conditional assembly here before checking for skipping. We
1149 // have to do this so that .endif isn't skipped in a ".if 0" block for
1151 StringMap<DirectiveKind>::const_iterator DirKindIt =
1152 DirectiveKindMap.find(IDVal);
1153 DirectiveKind DirKind =
1154 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1155 DirKindIt->getValue();
1160 return ParseDirectiveIf(IDLoc);
1162 return ParseDirectiveIfb(IDLoc, true);
1164 return ParseDirectiveIfb(IDLoc, false);
1166 return ParseDirectiveIfc(IDLoc, true);
1168 return ParseDirectiveIfc(IDLoc, false);
1170 return ParseDirectiveIfdef(IDLoc, true);
1173 return ParseDirectiveIfdef(IDLoc, false);
1175 return ParseDirectiveElseIf(IDLoc);
1177 return ParseDirectiveElse(IDLoc);
1179 return ParseDirectiveEndIf(IDLoc);
1182 // Ignore the statement if in the middle of inactive conditional
1184 if (TheCondState.Ignore) {
1185 eatToEndOfStatement();
1189 // FIXME: Recurse on local labels?
1191 // See what kind of statement we have.
1192 switch (Lexer.getKind()) {
1193 case AsmToken::Colon: {
1194 checkForValidSection();
1196 // identifier ':' -> Label.
1199 // Diagnose attempt to use '.' as a label.
1201 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1203 // Diagnose attempt to use a variable as a label.
1205 // FIXME: Diagnostics. Note the location of the definition as a label.
1206 // FIXME: This doesn't diagnose assignment to a symbol which has been
1207 // implicitly marked as external.
1209 if (LocalLabelVal == -1)
1210 Sym = getContext().GetOrCreateSymbol(IDVal);
1212 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1213 if (!Sym->isUndefined() || Sym->isVariable())
1214 return Error(IDLoc, "invalid symbol redefinition");
1217 if (!ParsingInlineAsm)
1220 // If we are generating dwarf for assembly source files then gather the
1221 // info to make a dwarf label entry for this label if needed.
1222 if (getContext().getGenDwarfForAssembly())
1223 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1226 // Consume any end of statement token, if present, to avoid spurious
1227 // AddBlankLine calls().
1228 if (Lexer.is(AsmToken::EndOfStatement)) {
1230 if (Lexer.is(AsmToken::Eof))
1237 case AsmToken::Equal:
1238 // identifier '=' ... -> assignment statement
1241 return ParseAssignment(IDVal, true);
1243 default: // Normal instruction or directive.
1247 // If macros are enabled, check to see if this is a macro instantiation.
1248 if (MacrosEnabled())
1249 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1250 return HandleMacroEntry(M, IDLoc);
1253 // Otherwise, we have a normal instruction or directive.
1255 // Directives start with "."
1256 if (IDVal[0] == '.' && IDVal != ".") {
1257 // There are several entities interested in parsing directives:
1259 // 1. The target-specific assembly parser. Some directives are target
1260 // specific or may potentially behave differently on certain targets.
1261 // 2. Asm parser extensions. For example, platform-specific parsers
1262 // (like the ELF parser) register themselves as extensions.
1263 // 3. The generic directive parser implemented by this class. These are
1264 // all the directives that behave in a target and platform independent
1265 // manner, or at least have a default behavior that's shared between
1266 // all targets and platforms.
1268 // First query the target-specific parser. It will return 'true' if it
1269 // isn't interested in this directive.
1270 if (!getTargetParser().ParseDirective(ID))
1273 // Next, check the extention directive map to see if any extension has
1274 // registered itself to parse this directive.
1275 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1276 ExtensionDirectiveMap.lookup(IDVal);
1278 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1280 // Finally, if no one else is interested in this directive, it must be
1281 // generic and familiar to this class.
1287 return ParseDirectiveSet(IDVal, true);
1289 return ParseDirectiveSet(IDVal, false);
1291 return ParseDirectiveAscii(IDVal, false);
1294 return ParseDirectiveAscii(IDVal, true);
1296 return ParseDirectiveValue(1);
1300 return ParseDirectiveValue(2);
1304 return ParseDirectiveValue(4);
1307 return ParseDirectiveValue(8);
1310 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1312 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1314 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1315 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1318 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1319 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1322 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1324 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1326 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1328 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1330 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1332 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1334 return ParseDirectiveOrg();
1336 return ParseDirectiveFill();
1338 return ParseDirectiveZero();
1340 eatToEndOfStatement(); // .extern is the default, ignore it.
1344 return ParseDirectiveSymbolAttribute(MCSA_Global);
1345 case DK_INDIRECT_SYMBOL:
1346 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1347 case DK_LAZY_REFERENCE:
1348 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1349 case DK_NO_DEAD_STRIP:
1350 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1351 case DK_SYMBOL_RESOLVER:
1352 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1353 case DK_PRIVATE_EXTERN:
1354 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1356 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1357 case DK_WEAK_DEFINITION:
1358 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1359 case DK_WEAK_REFERENCE:
1360 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1361 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1362 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1365 return ParseDirectiveComm(/*IsLocal=*/false);
1367 return ParseDirectiveComm(/*IsLocal=*/true);
1369 return ParseDirectiveAbort();
1371 return ParseDirectiveInclude();
1373 return ParseDirectiveIncbin();
1376 return TokError(Twine(IDVal) + " not supported yet");
1378 return ParseDirectiveRept(IDLoc);
1380 return ParseDirectiveIrp(IDLoc);
1382 return ParseDirectiveIrpc(IDLoc);
1384 return ParseDirectiveEndr(IDLoc);
1385 case DK_BUNDLE_ALIGN_MODE:
1386 return ParseDirectiveBundleAlignMode();
1387 case DK_BUNDLE_LOCK:
1388 return ParseDirectiveBundleLock();
1389 case DK_BUNDLE_UNLOCK:
1390 return ParseDirectiveBundleUnlock();
1392 return ParseDirectiveLEB128(true);
1394 return ParseDirectiveLEB128(false);
1397 return ParseDirectiveSpace(IDVal);
1399 return ParseDirectiveFile(IDLoc);
1401 return ParseDirectiveLine();
1403 return ParseDirectiveLoc();
1405 return ParseDirectiveStabs();
1406 case DK_CFI_SECTIONS:
1407 return ParseDirectiveCFISections();
1408 case DK_CFI_STARTPROC:
1409 return ParseDirectiveCFIStartProc();
1410 case DK_CFI_ENDPROC:
1411 return ParseDirectiveCFIEndProc();
1412 case DK_CFI_DEF_CFA:
1413 return ParseDirectiveCFIDefCfa(IDLoc);
1414 case DK_CFI_DEF_CFA_OFFSET:
1415 return ParseDirectiveCFIDefCfaOffset();
1416 case DK_CFI_ADJUST_CFA_OFFSET:
1417 return ParseDirectiveCFIAdjustCfaOffset();
1418 case DK_CFI_DEF_CFA_REGISTER:
1419 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1421 return ParseDirectiveCFIOffset(IDLoc);
1422 case DK_CFI_REL_OFFSET:
1423 return ParseDirectiveCFIRelOffset(IDLoc);
1424 case DK_CFI_PERSONALITY:
1425 return ParseDirectiveCFIPersonalityOrLsda(true);
1427 return ParseDirectiveCFIPersonalityOrLsda(false);
1428 case DK_CFI_REMEMBER_STATE:
1429 return ParseDirectiveCFIRememberState();
1430 case DK_CFI_RESTORE_STATE:
1431 return ParseDirectiveCFIRestoreState();
1432 case DK_CFI_SAME_VALUE:
1433 return ParseDirectiveCFISameValue(IDLoc);
1434 case DK_CFI_RESTORE:
1435 return ParseDirectiveCFIRestore(IDLoc);
1437 return ParseDirectiveCFIEscape();
1438 case DK_CFI_SIGNAL_FRAME:
1439 return ParseDirectiveCFISignalFrame();
1440 case DK_CFI_UNDEFINED:
1441 return ParseDirectiveCFIUndefined(IDLoc);
1442 case DK_CFI_REGISTER:
1443 return ParseDirectiveCFIRegister(IDLoc);
1446 return ParseDirectiveMacrosOnOff(IDVal);
1448 return ParseDirectiveMacro(IDLoc);
1451 return ParseDirectiveEndMacro(IDVal);
1453 return ParseDirectivePurgeMacro(IDLoc);
1456 return Error(IDLoc, "unknown directive");
1459 // __asm _emit or __asm __emit
1460 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1461 IDVal == "_EMIT" || IDVal == "__EMIT"))
1462 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1465 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1466 return ParseDirectiveMSAlign(IDLoc, Info);
1468 checkForValidSection();
1470 // Canonicalize the opcode to lower case.
1471 std::string OpcodeStr = IDVal.lower();
1472 ParseInstructionInfo IInfo(Info.AsmRewrites);
1473 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1474 IDLoc, Info.ParsedOperands);
1475 Info.ParseError = HadError;
1477 // Dump the parsed representation, if requested.
1478 if (getShowParsedOperands()) {
1479 SmallString<256> Str;
1480 raw_svector_ostream OS(Str);
1481 OS << "parsed instruction: [";
1482 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1485 Info.ParsedOperands[i]->print(OS);
1489 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1492 // If we are generating dwarf for assembly source files and the current
1493 // section is the initial text section then generate a .loc directive for
1495 if (!HadError && getContext().getGenDwarfForAssembly() &&
1496 getContext().getGenDwarfSection() ==
1497 getStreamer().getCurrentSection().first) {
1499 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1501 // If we previously parsed a cpp hash file line comment then make sure the
1502 // current Dwarf File is for the CppHashFilename if not then emit the
1503 // Dwarf File table for it and adjust the line number for the .loc.
1504 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1505 getContext().getMCDwarfFiles();
1506 if (CppHashFilename.size() != 0) {
1507 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1509 getStreamer().EmitDwarfFileDirective(
1510 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1512 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1513 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1516 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1517 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1518 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1522 // If parsing succeeded, match the instruction.
1525 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1526 Info.ParsedOperands,
1531 // Don't skip the rest of the line, the instruction parser is responsible for
1536 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1537 /// since they may not be able to be tokenized to get to the end of line token.
1538 void AsmParser::EatToEndOfLine() {
1539 if (!Lexer.is(AsmToken::EndOfStatement))
1540 Lexer.LexUntilEndOfLine();
1545 /// ParseCppHashLineFilenameComment as this:
1546 /// ::= # number "filename"
1547 /// or just as a full line comment if it doesn't have a number and a string.
1548 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1549 Lex(); // Eat the hash token.
1551 if (getLexer().isNot(AsmToken::Integer)) {
1552 // Consume the line since in cases it is not a well-formed line directive,
1553 // as if were simply a full line comment.
1558 int64_t LineNumber = getTok().getIntVal();
1561 if (getLexer().isNot(AsmToken::String)) {
1566 StringRef Filename = getTok().getString();
1567 // Get rid of the enclosing quotes.
1568 Filename = Filename.substr(1, Filename.size()-2);
1570 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1572 CppHashFilename = Filename;
1573 CppHashLineNumber = LineNumber;
1574 CppHashBuf = CurBuffer;
1576 // Ignore any trailing characters, they're just comment.
1581 /// DiagHandler - will use the last parsed cpp hash line filename comment
1582 /// for the Filename and LineNo if any in the diagnostic.
1583 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1584 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1585 raw_ostream &OS = errs();
1587 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1588 const SMLoc &DiagLoc = Diag.getLoc();
1589 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1590 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1592 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1593 // before printing the message.
1594 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1595 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1596 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1597 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1600 // If we have not parsed a cpp hash line filename comment or the source
1601 // manager changed or buffer changed (like in a nested include) then just
1602 // print the normal diagnostic using its Filename and LineNo.
1603 if (!Parser->CppHashLineNumber ||
1604 &DiagSrcMgr != &Parser->SrcMgr ||
1605 DiagBuf != CppHashBuf) {
1606 if (Parser->SavedDiagHandler)
1607 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1613 // Use the CppHashFilename and calculate a line number based on the
1614 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1616 const std::string Filename = Parser->CppHashFilename;
1618 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1619 int CppHashLocLineNo =
1620 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1621 int LineNo = Parser->CppHashLineNumber - 1 +
1622 (DiagLocLineNo - CppHashLocLineNo);
1624 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1625 Filename, LineNo, Diag.getColumnNo(),
1626 Diag.getKind(), Diag.getMessage(),
1627 Diag.getLineContents(), Diag.getRanges());
1629 if (Parser->SavedDiagHandler)
1630 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1632 NewDiag.print(0, OS);
1635 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1636 // difference being that that function accepts '@' as part of identifiers and
1637 // we can't do that. AsmLexer.cpp should probably be changed to handle
1638 // '@' as a special case when needed.
1639 static bool isIdentifierChar(char c) {
1640 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1644 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1645 const MCAsmMacroParameters &Parameters,
1646 const MCAsmMacroArguments &A,
1648 unsigned NParameters = Parameters.size();
1649 if (NParameters != 0 && NParameters != A.size())
1650 return Error(L, "Wrong number of arguments");
1652 // A macro without parameters is handled differently on Darwin:
1653 // gas accepts no arguments and does no substitutions
1654 while (!Body.empty()) {
1655 // Scan for the next substitution.
1656 std::size_t End = Body.size(), Pos = 0;
1657 for (; Pos != End; ++Pos) {
1658 // Check for a substitution or escape.
1660 // This macro has no parameters, look for $0, $1, etc.
1661 if (Body[Pos] != '$' || Pos + 1 == End)
1664 char Next = Body[Pos + 1];
1665 if (Next == '$' || Next == 'n' ||
1666 isdigit(static_cast<unsigned char>(Next)))
1669 // This macro has parameters, look for \foo, \bar, etc.
1670 if (Body[Pos] == '\\' && Pos + 1 != End)
1676 OS << Body.slice(0, Pos);
1678 // Check if we reached the end.
1683 switch (Body[Pos+1]) {
1689 // $n => number of arguments
1694 // $[0-9] => argument
1696 // Missing arguments are ignored.
1697 unsigned Index = Body[Pos+1] - '0';
1698 if (Index >= A.size())
1701 // Otherwise substitute with the token values, with spaces eliminated.
1702 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1703 ie = A[Index].end(); it != ie; ++it)
1704 OS << it->getString();
1710 unsigned I = Pos + 1;
1711 while (isIdentifierChar(Body[I]) && I + 1 != End)
1714 const char *Begin = Body.data() + Pos +1;
1715 StringRef Argument(Begin, I - (Pos +1));
1717 for (; Index < NParameters; ++Index)
1718 if (Parameters[Index].first == Argument)
1721 if (Index == NParameters) {
1722 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1725 OS << '\\' << Argument;
1729 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1730 ie = A[Index].end(); it != ie; ++it)
1731 if (it->getKind() == AsmToken::String)
1732 OS << it->getStringContents();
1734 OS << it->getString();
1736 Pos += 1 + Argument.size();
1739 // Update the scan point.
1740 Body = Body.substr(Pos);
1746 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1749 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1754 static bool IsOperator(AsmToken::TokenKind kind)
1760 case AsmToken::Plus:
1761 case AsmToken::Minus:
1762 case AsmToken::Tilde:
1763 case AsmToken::Slash:
1764 case AsmToken::Star:
1766 case AsmToken::Equal:
1767 case AsmToken::EqualEqual:
1768 case AsmToken::Pipe:
1769 case AsmToken::PipePipe:
1770 case AsmToken::Caret:
1772 case AsmToken::AmpAmp:
1773 case AsmToken::Exclaim:
1774 case AsmToken::ExclaimEqual:
1775 case AsmToken::Percent:
1776 case AsmToken::Less:
1777 case AsmToken::LessEqual:
1778 case AsmToken::LessLess:
1779 case AsmToken::LessGreater:
1780 case AsmToken::Greater:
1781 case AsmToken::GreaterEqual:
1782 case AsmToken::GreaterGreater:
1787 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1788 AsmToken::TokenKind &ArgumentDelimiter) {
1789 unsigned ParenLevel = 0;
1790 unsigned AddTokens = 0;
1792 // gas accepts arguments separated by whitespace, except on Darwin
1794 Lexer.setSkipSpace(false);
1797 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1798 Lexer.setSkipSpace(true);
1799 return TokError("unexpected token in macro instantiation");
1802 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1803 // Spaces and commas cannot be mixed to delimit parameters
1804 if (ArgumentDelimiter == AsmToken::Eof)
1805 ArgumentDelimiter = AsmToken::Comma;
1806 else if (ArgumentDelimiter != AsmToken::Comma) {
1807 Lexer.setSkipSpace(true);
1808 return TokError("expected ' ' for macro argument separator");
1813 if (Lexer.is(AsmToken::Space)) {
1814 Lex(); // Eat spaces
1816 // Spaces can delimit parameters, but could also be part an expression.
1817 // If the token after a space is an operator, add the token and the next
1818 // one into this argument
1819 if (ArgumentDelimiter == AsmToken::Space ||
1820 ArgumentDelimiter == AsmToken::Eof) {
1821 if (IsOperator(Lexer.getKind())) {
1822 // Check to see whether the token is used as an operator,
1823 // or part of an identifier
1824 const char *NextChar = getTok().getEndLoc().getPointer();
1825 if (*NextChar == ' ')
1829 if (!AddTokens && ParenLevel == 0) {
1830 if (ArgumentDelimiter == AsmToken::Eof &&
1831 !IsOperator(Lexer.getKind()))
1832 ArgumentDelimiter = AsmToken::Space;
1838 // HandleMacroEntry relies on not advancing the lexer here
1839 // to be able to fill in the remaining default parameter values
1840 if (Lexer.is(AsmToken::EndOfStatement))
1843 // Adjust the current parentheses level.
1844 if (Lexer.is(AsmToken::LParen))
1846 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1849 // Append the token to the current argument list.
1850 MA.push_back(getTok());
1856 Lexer.setSkipSpace(true);
1857 if (ParenLevel != 0)
1858 return TokError("unbalanced parentheses in macro argument");
1862 // Parse the macro instantiation arguments.
1863 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1864 const unsigned NParameters = M ? M->Parameters.size() : 0;
1865 // Argument delimiter is initially unknown. It will be set by
1866 // ParseMacroArgument()
1867 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1869 // Parse two kinds of macro invocations:
1870 // - macros defined without any parameters accept an arbitrary number of them
1871 // - macros defined with parameters accept at most that many of them
1872 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1874 MCAsmMacroArgument MA;
1876 if (ParseMacroArgument(MA, ArgumentDelimiter))
1879 if (!MA.empty() || !NParameters)
1881 else if (NParameters) {
1882 if (!M->Parameters[Parameter].second.empty())
1883 A.push_back(M->Parameters[Parameter].second);
1886 // At the end of the statement, fill in remaining arguments that have
1887 // default values. If there aren't any, then the next argument is
1888 // required but missing
1889 if (Lexer.is(AsmToken::EndOfStatement)) {
1890 if (NParameters && Parameter < NParameters - 1) {
1891 if (M->Parameters[Parameter + 1].second.empty())
1892 return TokError("macro argument '" +
1893 Twine(M->Parameters[Parameter + 1].first) +
1901 if (Lexer.is(AsmToken::Comma))
1904 return TokError("Too many arguments");
1907 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1908 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1909 return (I == MacroMap.end()) ? NULL : I->getValue();
1912 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1913 MacroMap[Name] = new MCAsmMacro(Macro);
1916 void AsmParser::UndefineMacro(StringRef Name) {
1917 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1918 if (I != MacroMap.end()) {
1919 delete I->getValue();
1924 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1925 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1926 // this, although we should protect against infinite loops.
1927 if (ActiveMacros.size() == 20)
1928 return TokError("macros cannot be nested more than 20 levels deep");
1930 MCAsmMacroArguments A;
1931 if (ParseMacroArguments(M, A))
1934 // Remove any trailing empty arguments. Do this after-the-fact as we have
1935 // to keep empty arguments in the middle of the list or positionality
1936 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1937 while (!A.empty() && A.back().empty())
1940 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1941 // to hold the macro body with substitutions.
1942 SmallString<256> Buf;
1943 StringRef Body = M->Body;
1944 raw_svector_ostream OS(Buf);
1946 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1949 // We include the .endmacro in the buffer as our cue to exit the macro
1951 OS << ".endmacro\n";
1953 MemoryBuffer *Instantiation =
1954 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1956 // Create the macro instantiation object and add to the current macro
1957 // instantiation stack.
1958 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1962 ActiveMacros.push_back(MI);
1964 // Jump to the macro instantiation and prime the lexer.
1965 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1966 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1972 void AsmParser::HandleMacroExit() {
1973 // Jump to the EndOfStatement we should return to, and consume it.
1974 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1977 // Pop the instantiation entry.
1978 delete ActiveMacros.back();
1979 ActiveMacros.pop_back();
1982 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1983 switch (Value->getKind()) {
1984 case MCExpr::Binary: {
1985 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1986 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1988 case MCExpr::Target:
1989 case MCExpr::Constant:
1991 case MCExpr::SymbolRef: {
1992 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1994 return IsUsedIn(Sym, S.getVariableValue());
1998 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
2001 llvm_unreachable("Unknown expr kind!");
2004 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2006 // FIXME: Use better location, we should use proper tokens.
2007 SMLoc EqualLoc = Lexer.getLoc();
2009 const MCExpr *Value;
2010 if (parseExpression(Value))
2013 // Note: we don't count b as used in "a = b". This is to allow
2017 if (Lexer.isNot(AsmToken::EndOfStatement))
2018 return TokError("unexpected token in assignment");
2020 // Error on assignment to '.'.
2022 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2023 "(use '.space' or '.org').)"));
2026 // Eat the end of statement marker.
2029 // Validate that the LHS is allowed to be a variable (either it has not been
2030 // used as a symbol, or it is an absolute symbol).
2031 MCSymbol *Sym = getContext().LookupSymbol(Name);
2033 // Diagnose assignment to a label.
2035 // FIXME: Diagnostics. Note the location of the definition as a label.
2036 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2037 if (IsUsedIn(Sym, Value))
2038 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2039 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2040 ; // Allow redefinitions of undefined symbols only used in directives.
2041 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2042 ; // Allow redefinitions of variables that haven't yet been used.
2043 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2044 return Error(EqualLoc, "redefinition of '" + Name + "'");
2045 else if (!Sym->isVariable())
2046 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2047 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2048 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2051 // Don't count these checks as uses.
2052 Sym->setUsed(false);
2054 Sym = getContext().GetOrCreateSymbol(Name);
2056 // FIXME: Handle '.'.
2058 // Do the assignment.
2059 Out.EmitAssignment(Sym, Value);
2061 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2067 /// parseIdentifier:
2070 bool AsmParser::parseIdentifier(StringRef &Res) {
2071 // The assembler has relaxed rules for accepting identifiers, in particular we
2072 // allow things like '.globl $foo', which would normally be separate
2073 // tokens. At this level, we have already lexed so we cannot (currently)
2074 // handle this as a context dependent token, instead we detect adjacent tokens
2075 // and return the combined identifier.
2076 if (Lexer.is(AsmToken::Dollar)) {
2077 SMLoc DollarLoc = getLexer().getLoc();
2079 // Consume the dollar sign, and check for a following identifier.
2081 if (Lexer.isNot(AsmToken::Identifier))
2084 // We have a '$' followed by an identifier, make sure they are adjacent.
2085 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2088 // Construct the joined identifier and consume the token.
2089 Res = StringRef(DollarLoc.getPointer(),
2090 getTok().getIdentifier().size() + 1);
2095 if (Lexer.isNot(AsmToken::Identifier) &&
2096 Lexer.isNot(AsmToken::String))
2099 Res = getTok().getIdentifier();
2101 Lex(); // Consume the identifier token.
2106 /// ParseDirectiveSet:
2107 /// ::= .equ identifier ',' expression
2108 /// ::= .equiv identifier ',' expression
2109 /// ::= .set identifier ',' expression
2110 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2113 if (parseIdentifier(Name))
2114 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2116 if (getLexer().isNot(AsmToken::Comma))
2117 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2120 return ParseAssignment(Name, allow_redef, true);
2123 bool AsmParser::parseEscapedString(std::string &Data) {
2124 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2127 StringRef Str = getTok().getStringContents();
2128 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2129 if (Str[i] != '\\') {
2134 // Recognize escaped characters. Note that this escape semantics currently
2135 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2138 return TokError("unexpected backslash at end of string");
2140 // Recognize octal sequences.
2141 if ((unsigned) (Str[i] - '0') <= 7) {
2142 // Consume up to three octal characters.
2143 unsigned Value = Str[i] - '0';
2145 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2147 Value = Value * 8 + (Str[i] - '0');
2149 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2151 Value = Value * 8 + (Str[i] - '0');
2156 return TokError("invalid octal escape sequence (out of range)");
2158 Data += (unsigned char) Value;
2162 // Otherwise recognize individual escapes.
2165 // Just reject invalid escape sequences for now.
2166 return TokError("invalid escape sequence (unrecognized character)");
2168 case 'b': Data += '\b'; break;
2169 case 'f': Data += '\f'; break;
2170 case 'n': Data += '\n'; break;
2171 case 'r': Data += '\r'; break;
2172 case 't': Data += '\t'; break;
2173 case '"': Data += '"'; break;
2174 case '\\': Data += '\\'; break;
2181 /// ParseDirectiveAscii:
2182 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2183 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2184 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2185 checkForValidSection();
2188 if (getLexer().isNot(AsmToken::String))
2189 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2192 if (parseEscapedString(Data))
2195 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2197 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2201 if (getLexer().is(AsmToken::EndOfStatement))
2204 if (getLexer().isNot(AsmToken::Comma))
2205 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2214 /// ParseDirectiveValue
2215 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2216 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2217 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2218 checkForValidSection();
2221 const MCExpr *Value;
2222 SMLoc ExprLoc = getLexer().getLoc();
2223 if (parseExpression(Value))
2226 // Special case constant expressions to match code generator.
2227 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2228 assert(Size <= 8 && "Invalid size");
2229 uint64_t IntValue = MCE->getValue();
2230 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2231 return Error(ExprLoc, "literal value out of range for directive");
2232 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2234 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2236 if (getLexer().is(AsmToken::EndOfStatement))
2239 // FIXME: Improve diagnostic.
2240 if (getLexer().isNot(AsmToken::Comma))
2241 return TokError("unexpected token in directive");
2250 /// ParseDirectiveRealValue
2251 /// ::= (.single | .double) [ expression (, expression)* ]
2252 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2253 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2254 checkForValidSection();
2257 // We don't truly support arithmetic on floating point expressions, so we
2258 // have to manually parse unary prefixes.
2260 if (getLexer().is(AsmToken::Minus)) {
2263 } else if (getLexer().is(AsmToken::Plus))
2266 if (getLexer().isNot(AsmToken::Integer) &&
2267 getLexer().isNot(AsmToken::Real) &&
2268 getLexer().isNot(AsmToken::Identifier))
2269 return TokError("unexpected token in directive");
2271 // Convert to an APFloat.
2272 APFloat Value(Semantics);
2273 StringRef IDVal = getTok().getString();
2274 if (getLexer().is(AsmToken::Identifier)) {
2275 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2276 Value = APFloat::getInf(Semantics);
2277 else if (!IDVal.compare_lower("nan"))
2278 Value = APFloat::getNaN(Semantics, false, ~0);
2280 return TokError("invalid floating point literal");
2281 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2282 APFloat::opInvalidOp)
2283 return TokError("invalid floating point literal");
2287 // Consume the numeric token.
2290 // Emit the value as an integer.
2291 APInt AsInt = Value.bitcastToAPInt();
2292 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2293 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2295 if (getLexer().is(AsmToken::EndOfStatement))
2298 if (getLexer().isNot(AsmToken::Comma))
2299 return TokError("unexpected token in directive");
2308 /// ParseDirectiveZero
2309 /// ::= .zero expression
2310 bool AsmParser::ParseDirectiveZero() {
2311 checkForValidSection();
2314 if (parseAbsoluteExpression(NumBytes))
2318 if (getLexer().is(AsmToken::Comma)) {
2320 if (parseAbsoluteExpression(Val))
2324 if (getLexer().isNot(AsmToken::EndOfStatement))
2325 return TokError("unexpected token in '.zero' directive");
2329 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2334 /// ParseDirectiveFill
2335 /// ::= .fill expression , expression , expression
2336 bool AsmParser::ParseDirectiveFill() {
2337 checkForValidSection();
2340 if (parseAbsoluteExpression(NumValues))
2343 if (getLexer().isNot(AsmToken::Comma))
2344 return TokError("unexpected token in '.fill' directive");
2348 if (parseAbsoluteExpression(FillSize))
2351 if (getLexer().isNot(AsmToken::Comma))
2352 return TokError("unexpected token in '.fill' directive");
2356 if (parseAbsoluteExpression(FillExpr))
2359 if (getLexer().isNot(AsmToken::EndOfStatement))
2360 return TokError("unexpected token in '.fill' directive");
2364 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2365 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2367 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2368 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2373 /// ParseDirectiveOrg
2374 /// ::= .org expression [ , expression ]
2375 bool AsmParser::ParseDirectiveOrg() {
2376 checkForValidSection();
2378 const MCExpr *Offset;
2379 SMLoc Loc = getTok().getLoc();
2380 if (parseExpression(Offset))
2383 // Parse optional fill expression.
2384 int64_t FillExpr = 0;
2385 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2386 if (getLexer().isNot(AsmToken::Comma))
2387 return TokError("unexpected token in '.org' directive");
2390 if (parseAbsoluteExpression(FillExpr))
2393 if (getLexer().isNot(AsmToken::EndOfStatement))
2394 return TokError("unexpected token in '.org' directive");
2399 // Only limited forms of relocatable expressions are accepted here, it
2400 // has to be relative to the current section. The streamer will return
2401 // 'true' if the expression wasn't evaluatable.
2402 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2403 return Error(Loc, "expected assembly-time absolute expression");
2408 /// ParseDirectiveAlign
2409 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2410 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2411 checkForValidSection();
2413 SMLoc AlignmentLoc = getLexer().getLoc();
2415 if (parseAbsoluteExpression(Alignment))
2419 bool HasFillExpr = false;
2420 int64_t FillExpr = 0;
2421 int64_t MaxBytesToFill = 0;
2422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2423 if (getLexer().isNot(AsmToken::Comma))
2424 return TokError("unexpected token in directive");
2427 // The fill expression can be omitted while specifying a maximum number of
2428 // alignment bytes, e.g:
2430 if (getLexer().isNot(AsmToken::Comma)) {
2432 if (parseAbsoluteExpression(FillExpr))
2436 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2437 if (getLexer().isNot(AsmToken::Comma))
2438 return TokError("unexpected token in directive");
2441 MaxBytesLoc = getLexer().getLoc();
2442 if (parseAbsoluteExpression(MaxBytesToFill))
2445 if (getLexer().isNot(AsmToken::EndOfStatement))
2446 return TokError("unexpected token in directive");
2455 // Compute alignment in bytes.
2457 // FIXME: Diagnose overflow.
2458 if (Alignment >= 32) {
2459 Error(AlignmentLoc, "invalid alignment value");
2463 Alignment = 1ULL << Alignment;
2465 // Reject alignments that aren't a power of two, for gas compatibility.
2466 if (!isPowerOf2_64(Alignment))
2467 Error(AlignmentLoc, "alignment must be a power of 2");
2470 // Diagnose non-sensical max bytes to align.
2471 if (MaxBytesLoc.isValid()) {
2472 if (MaxBytesToFill < 1) {
2473 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2474 "many bytes, ignoring maximum bytes expression");
2478 if (MaxBytesToFill >= Alignment) {
2479 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2485 // Check whether we should use optimal code alignment for this .align
2487 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2488 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2489 ValueSize == 1 && UseCodeAlign) {
2490 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2492 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2493 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2500 /// ParseDirectiveFile
2501 /// ::= .file [number] filename
2502 /// ::= .file number directory filename
2503 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2504 // FIXME: I'm not sure what this is.
2505 int64_t FileNumber = -1;
2506 SMLoc FileNumberLoc = getLexer().getLoc();
2507 if (getLexer().is(AsmToken::Integer)) {
2508 FileNumber = getTok().getIntVal();
2512 return TokError("file number less than one");
2515 if (getLexer().isNot(AsmToken::String))
2516 return TokError("unexpected token in '.file' directive");
2518 // Usually the directory and filename together, otherwise just the directory.
2519 StringRef Path = getTok().getString();
2520 Path = Path.substr(1, Path.size()-2);
2523 StringRef Directory;
2525 if (getLexer().is(AsmToken::String)) {
2526 if (FileNumber == -1)
2527 return TokError("explicit path specified, but no file number");
2528 Filename = getTok().getString();
2529 Filename = Filename.substr(1, Filename.size()-2);
2536 if (getLexer().isNot(AsmToken::EndOfStatement))
2537 return TokError("unexpected token in '.file' directive");
2539 if (FileNumber == -1)
2540 getStreamer().EmitFileDirective(Filename);
2542 if (getContext().getGenDwarfForAssembly() == true)
2543 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2544 "used to generate dwarf debug info for assembly code");
2546 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2547 Error(FileNumberLoc, "file number already allocated");
2553 /// ParseDirectiveLine
2554 /// ::= .line [number]
2555 bool AsmParser::ParseDirectiveLine() {
2556 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2557 if (getLexer().isNot(AsmToken::Integer))
2558 return TokError("unexpected token in '.line' directive");
2560 int64_t LineNumber = getTok().getIntVal();
2564 // FIXME: Do something with the .line.
2567 if (getLexer().isNot(AsmToken::EndOfStatement))
2568 return TokError("unexpected token in '.line' directive");
2573 /// ParseDirectiveLoc
2574 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2575 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2576 /// The first number is a file number, must have been previously assigned with
2577 /// a .file directive, the second number is the line number and optionally the
2578 /// third number is a column position (zero if not specified). The remaining
2579 /// optional items are .loc sub-directives.
2580 bool AsmParser::ParseDirectiveLoc() {
2581 if (getLexer().isNot(AsmToken::Integer))
2582 return TokError("unexpected token in '.loc' directive");
2583 int64_t FileNumber = getTok().getIntVal();
2585 return TokError("file number less than one in '.loc' directive");
2586 if (!getContext().isValidDwarfFileNumber(FileNumber))
2587 return TokError("unassigned file number in '.loc' directive");
2590 int64_t LineNumber = 0;
2591 if (getLexer().is(AsmToken::Integer)) {
2592 LineNumber = getTok().getIntVal();
2594 return TokError("line number less than one in '.loc' directive");
2598 int64_t ColumnPos = 0;
2599 if (getLexer().is(AsmToken::Integer)) {
2600 ColumnPos = getTok().getIntVal();
2602 return TokError("column position less than zero in '.loc' directive");
2606 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2608 int64_t Discriminator = 0;
2609 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2611 if (getLexer().is(AsmToken::EndOfStatement))
2615 SMLoc Loc = getTok().getLoc();
2616 if (parseIdentifier(Name))
2617 return TokError("unexpected token in '.loc' directive");
2619 if (Name == "basic_block")
2620 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2621 else if (Name == "prologue_end")
2622 Flags |= DWARF2_FLAG_PROLOGUE_END;
2623 else if (Name == "epilogue_begin")
2624 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2625 else if (Name == "is_stmt") {
2626 Loc = getTok().getLoc();
2627 const MCExpr *Value;
2628 if (parseExpression(Value))
2630 // The expression must be the constant 0 or 1.
2631 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2632 int Value = MCE->getValue();
2634 Flags &= ~DWARF2_FLAG_IS_STMT;
2635 else if (Value == 1)
2636 Flags |= DWARF2_FLAG_IS_STMT;
2638 return Error(Loc, "is_stmt value not 0 or 1");
2640 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2642 } else if (Name == "isa") {
2643 Loc = getTok().getLoc();
2644 const MCExpr *Value;
2645 if (parseExpression(Value))
2647 // The expression must be a constant greater or equal to 0.
2648 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2649 int Value = MCE->getValue();
2651 return Error(Loc, "isa number less than zero");
2654 return Error(Loc, "isa number not a constant value");
2656 } else if (Name == "discriminator") {
2657 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();
3630 if (parseAbsoluteExpression(ExprValue))
3633 if (getLexer().isNot(AsmToken::EndOfStatement))
3634 return TokError("unexpected token in '.elseif' directive");
3637 TheCondState.CondMet = ExprValue;
3638 TheCondState.Ignore = !TheCondState.CondMet;
3644 /// ParseDirectiveElse
3646 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3647 if (getLexer().isNot(AsmToken::EndOfStatement))
3648 return TokError("unexpected token in '.else' directive");
3652 if (TheCondState.TheCond != AsmCond::IfCond &&
3653 TheCondState.TheCond != AsmCond::ElseIfCond)
3654 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3656 TheCondState.TheCond = AsmCond::ElseCond;
3657 bool LastIgnoreState = false;
3658 if (!TheCondStack.empty())
3659 LastIgnoreState = TheCondStack.back().Ignore;
3660 if (LastIgnoreState || TheCondState.CondMet)
3661 TheCondState.Ignore = true;
3663 TheCondState.Ignore = false;
3668 /// ParseDirectiveEndIf
3670 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3671 if (getLexer().isNot(AsmToken::EndOfStatement))
3672 return TokError("unexpected token in '.endif' directive");
3676 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3677 TheCondStack.empty())
3678 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3680 if (!TheCondStack.empty()) {
3681 TheCondState = TheCondStack.back();
3682 TheCondStack.pop_back();
3688 void AsmParser::initializeDirectiveKindMap() {
3689 DirectiveKindMap[".set"] = DK_SET;
3690 DirectiveKindMap[".equ"] = DK_EQU;
3691 DirectiveKindMap[".equiv"] = DK_EQUIV;
3692 DirectiveKindMap[".ascii"] = DK_ASCII;
3693 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3694 DirectiveKindMap[".string"] = DK_STRING;
3695 DirectiveKindMap[".byte"] = DK_BYTE;
3696 DirectiveKindMap[".short"] = DK_SHORT;
3697 DirectiveKindMap[".value"] = DK_VALUE;
3698 DirectiveKindMap[".2byte"] = DK_2BYTE;
3699 DirectiveKindMap[".long"] = DK_LONG;
3700 DirectiveKindMap[".int"] = DK_INT;
3701 DirectiveKindMap[".4byte"] = DK_4BYTE;
3702 DirectiveKindMap[".quad"] = DK_QUAD;
3703 DirectiveKindMap[".8byte"] = DK_8BYTE;
3704 DirectiveKindMap[".single"] = DK_SINGLE;
3705 DirectiveKindMap[".float"] = DK_FLOAT;
3706 DirectiveKindMap[".double"] = DK_DOUBLE;
3707 DirectiveKindMap[".align"] = DK_ALIGN;
3708 DirectiveKindMap[".align32"] = DK_ALIGN32;
3709 DirectiveKindMap[".balign"] = DK_BALIGN;
3710 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3711 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3712 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3713 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3714 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3715 DirectiveKindMap[".org"] = DK_ORG;
3716 DirectiveKindMap[".fill"] = DK_FILL;
3717 DirectiveKindMap[".zero"] = DK_ZERO;
3718 DirectiveKindMap[".extern"] = DK_EXTERN;
3719 DirectiveKindMap[".globl"] = DK_GLOBL;
3720 DirectiveKindMap[".global"] = DK_GLOBAL;
3721 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3722 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3723 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3724 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3725 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3726 DirectiveKindMap[".reference"] = DK_REFERENCE;
3727 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3728 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3729 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3730 DirectiveKindMap[".comm"] = DK_COMM;
3731 DirectiveKindMap[".common"] = DK_COMMON;
3732 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3733 DirectiveKindMap[".abort"] = DK_ABORT;
3734 DirectiveKindMap[".include"] = DK_INCLUDE;
3735 DirectiveKindMap[".incbin"] = DK_INCBIN;
3736 DirectiveKindMap[".code16"] = DK_CODE16;
3737 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3738 DirectiveKindMap[".rept"] = DK_REPT;
3739 DirectiveKindMap[".irp"] = DK_IRP;
3740 DirectiveKindMap[".irpc"] = DK_IRPC;
3741 DirectiveKindMap[".endr"] = DK_ENDR;
3742 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3743 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3744 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3745 DirectiveKindMap[".if"] = DK_IF;
3746 DirectiveKindMap[".ifb"] = DK_IFB;
3747 DirectiveKindMap[".ifnb"] = DK_IFNB;
3748 DirectiveKindMap[".ifc"] = DK_IFC;
3749 DirectiveKindMap[".ifnc"] = DK_IFNC;
3750 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3751 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3752 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3753 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3754 DirectiveKindMap[".else"] = DK_ELSE;
3755 DirectiveKindMap[".endif"] = DK_ENDIF;
3756 DirectiveKindMap[".skip"] = DK_SKIP;
3757 DirectiveKindMap[".space"] = DK_SPACE;
3758 DirectiveKindMap[".file"] = DK_FILE;
3759 DirectiveKindMap[".line"] = DK_LINE;
3760 DirectiveKindMap[".loc"] = DK_LOC;
3761 DirectiveKindMap[".stabs"] = DK_STABS;
3762 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3763 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3764 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3765 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3766 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3767 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3768 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3769 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3770 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3771 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3772 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3773 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3774 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3775 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3776 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3777 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3778 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3779 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3780 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3781 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3782 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3783 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3784 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3785 DirectiveKindMap[".macro"] = DK_MACRO;
3786 DirectiveKindMap[".endm"] = DK_ENDM;
3787 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3788 DirectiveKindMap[".purgem"] = DK_PURGEM;
3792 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3793 AsmToken EndToken, StartToken = getTok();
3795 unsigned NestLevel = 0;
3797 // Check whether we have reached the end of the file.
3798 if (getLexer().is(AsmToken::Eof)) {
3799 Error(DirectiveLoc, "no matching '.endr' in definition");
3803 if (Lexer.is(AsmToken::Identifier) &&
3804 (getTok().getIdentifier() == ".rept")) {
3808 // Otherwise, check whether we have reached the .endr.
3809 if (Lexer.is(AsmToken::Identifier) &&
3810 getTok().getIdentifier() == ".endr") {
3811 if (NestLevel == 0) {
3812 EndToken = getTok();
3814 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3815 TokError("unexpected token in '.endr' directive");
3823 // Otherwise, scan till the end of the statement.
3824 eatToEndOfStatement();
3827 const char *BodyStart = StartToken.getLoc().getPointer();
3828 const char *BodyEnd = EndToken.getLoc().getPointer();
3829 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3831 // We Are Anonymous.
3833 MCAsmMacroParameters Parameters;
3834 return new MCAsmMacro(Name, Body, Parameters);
3837 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3838 raw_svector_ostream &OS) {
3841 MemoryBuffer *Instantiation =
3842 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3844 // Create the macro instantiation object and add to the current macro
3845 // instantiation stack.
3846 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3850 ActiveMacros.push_back(MI);
3852 // Jump to the macro instantiation and prime the lexer.
3853 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3854 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3858 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3860 if (parseAbsoluteExpression(Count))
3861 return TokError("unexpected token in '.rept' directive");
3864 return TokError("Count is negative");
3866 if (Lexer.isNot(AsmToken::EndOfStatement))
3867 return TokError("unexpected token in '.rept' directive");
3869 // Eat the end of statement.
3872 // Lex the rept definition.
3873 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3877 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3878 // to hold the macro body with substitutions.
3879 SmallString<256> Buf;
3880 MCAsmMacroParameters Parameters;
3881 MCAsmMacroArguments A;
3882 raw_svector_ostream OS(Buf);
3884 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3887 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3892 /// ParseDirectiveIrp
3893 /// ::= .irp symbol,values
3894 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3895 MCAsmMacroParameters Parameters;
3896 MCAsmMacroParameter Parameter;
3898 if (parseIdentifier(Parameter.first))
3899 return TokError("expected identifier in '.irp' directive");
3901 Parameters.push_back(Parameter);
3903 if (Lexer.isNot(AsmToken::Comma))
3904 return TokError("expected comma in '.irp' directive");
3908 MCAsmMacroArguments A;
3909 if (ParseMacroArguments(0, A))
3912 // Eat the end of statement.
3915 // Lex the irp definition.
3916 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3920 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3921 // to hold the macro body with substitutions.
3922 SmallString<256> Buf;
3923 raw_svector_ostream OS(Buf);
3925 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3926 MCAsmMacroArguments Args;
3929 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3933 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3938 /// ParseDirectiveIrpc
3939 /// ::= .irpc symbol,values
3940 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3941 MCAsmMacroParameters Parameters;
3942 MCAsmMacroParameter Parameter;
3944 if (parseIdentifier(Parameter.first))
3945 return TokError("expected identifier in '.irpc' directive");
3947 Parameters.push_back(Parameter);
3949 if (Lexer.isNot(AsmToken::Comma))
3950 return TokError("expected comma in '.irpc' directive");
3954 MCAsmMacroArguments A;
3955 if (ParseMacroArguments(0, A))
3958 if (A.size() != 1 || A.front().size() != 1)
3959 return TokError("unexpected token in '.irpc' directive");
3961 // Eat the end of statement.
3964 // Lex the irpc definition.
3965 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3969 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3970 // to hold the macro body with substitutions.
3971 SmallString<256> Buf;
3972 raw_svector_ostream OS(Buf);
3974 StringRef Values = A.front().front().getString();
3975 std::size_t I, End = Values.size();
3976 for (I = 0; I < End; ++I) {
3977 MCAsmMacroArgument Arg;
3978 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3980 MCAsmMacroArguments Args;
3981 Args.push_back(Arg);
3983 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3987 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3992 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3993 if (ActiveMacros.empty())
3994 return TokError("unmatched '.endr' directive");
3996 // The only .repl that should get here are the ones created by
3997 // InstantiateMacroLikeBody.
3998 assert(getLexer().is(AsmToken::EndOfStatement));
4004 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4006 const MCExpr *Value;
4007 SMLoc ExprLoc = getLexer().getLoc();
4008 if (parseExpression(Value))
4010 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4012 return Error(ExprLoc, "unexpected expression in _emit");
4013 uint64_t IntValue = MCE->getValue();
4014 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4015 return Error(ExprLoc, "literal value out of range for directive");
4017 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4021 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4022 const MCExpr *Value;
4023 SMLoc ExprLoc = getLexer().getLoc();
4024 if (parseExpression(Value))
4026 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4028 return Error(ExprLoc, "unexpected expression in align");
4029 uint64_t IntValue = MCE->getValue();
4030 if (!isPowerOf2_64(IntValue))
4031 return Error(ExprLoc, "literal value not a power of two greater then zero");
4033 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4034 Log2_64(IntValue)));
4038 // We are comparing pointers, but the pointers are relative to a single string.
4039 // Thus, this should always be deterministic.
4040 static int RewritesSort(const void *A, const void *B) {
4041 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4042 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
4043 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4045 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4048 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4049 // rewrite to the same location. Make sure the SizeDirective rewrite is
4050 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4051 // ensures the sort algorithm is stable.
4052 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4053 AsmRewritePrecedence [AsmRewriteB->Kind])
4056 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4057 AsmRewritePrecedence [AsmRewriteB->Kind])
4059 llvm_unreachable ("Unstable rewrite sort.");
4063 AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4064 unsigned &NumOutputs, unsigned &NumInputs,
4065 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4066 SmallVectorImpl<std::string> &Constraints,
4067 SmallVectorImpl<std::string> &Clobbers,
4068 const MCInstrInfo *MII,
4069 const MCInstPrinter *IP,
4070 MCAsmParserSemaCallback &SI) {
4071 SmallVector<void *, 4> InputDecls;
4072 SmallVector<void *, 4> OutputDecls;
4073 SmallVector<bool, 4> InputDeclsAddressOf;
4074 SmallVector<bool, 4> OutputDeclsAddressOf;
4075 SmallVector<std::string, 4> InputConstraints;
4076 SmallVector<std::string, 4> OutputConstraints;
4077 SmallVector<unsigned, 4> ClobberRegs;
4079 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4084 // While we have input, parse each statement.
4085 unsigned InputIdx = 0;
4086 unsigned OutputIdx = 0;
4087 while (getLexer().isNot(AsmToken::Eof)) {
4088 ParseStatementInfo Info(&AsmStrRewrites);
4089 if (ParseStatement(Info))
4092 if (Info.ParseError)
4095 if (Info.Opcode == ~0U)
4098 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4100 // Build the list of clobbers, outputs and inputs.
4101 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4102 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4105 if (Operand->isImm())
4108 // Register operand.
4109 if (Operand->isReg() && !Operand->needAddressOf()) {
4110 unsigned NumDefs = Desc.getNumDefs();
4112 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4113 ClobberRegs.push_back(Operand->getReg());
4117 // Expr/Input or Output.
4118 StringRef SymName = Operand->getSymName();
4119 if (SymName.empty())
4122 void *OpDecl = Operand->getOpDecl();
4126 bool isOutput = (i == 1) && Desc.mayStore();
4127 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4130 OutputDecls.push_back(OpDecl);
4131 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4132 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4133 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4135 InputDecls.push_back(OpDecl);
4136 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4137 InputConstraints.push_back(Operand->getConstraint().str());
4138 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4143 // Set the number of Outputs and Inputs.
4144 NumOutputs = OutputDecls.size();
4145 NumInputs = InputDecls.size();
4147 // Set the unique clobbers.
4148 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4149 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4151 Clobbers.assign(ClobberRegs.size(), std::string());
4152 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4153 raw_string_ostream OS(Clobbers[I]);
4154 IP->printRegName(OS, ClobberRegs[I]);
4157 // Merge the various outputs and inputs. Output are expected first.
4158 if (NumOutputs || NumInputs) {
4159 unsigned NumExprs = NumOutputs + NumInputs;
4160 OpDecls.resize(NumExprs);
4161 Constraints.resize(NumExprs);
4162 for (unsigned i = 0; i < NumOutputs; ++i) {
4163 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4164 Constraints[i] = OutputConstraints[i];
4166 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4167 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4168 Constraints[j] = InputConstraints[i];
4172 // Build the IR assembly string.
4173 std::string AsmStringIR;
4174 raw_string_ostream OS(AsmStringIR);
4175 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4176 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4177 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4178 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4179 E = AsmStrRewrites.end();
4181 AsmRewriteKind Kind = (*I).Kind;
4182 if (Kind == AOK_Delete)
4185 const char *Loc = (*I).Loc.getPointer();
4186 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4188 // Emit everything up to the immediate/expression.
4189 unsigned Len = Loc - AsmStart;
4191 OS << StringRef(AsmStart, Len);
4193 // Skip the original expression.
4194 if (Kind == AOK_Skip) {
4195 AsmStart = Loc + (*I).Len;
4199 unsigned AdditionalSkip = 0;
4200 // Rewrite expressions in $N notation.
4204 OS << "$$" << (*I).Val;
4210 OS << '$' << InputIdx++;
4213 OS << '$' << OutputIdx++;
4215 case AOK_SizeDirective:
4218 case 8: OS << "byte ptr "; break;
4219 case 16: OS << "word ptr "; break;
4220 case 32: OS << "dword ptr "; break;
4221 case 64: OS << "qword ptr "; break;
4222 case 80: OS << "xword ptr "; break;
4223 case 128: OS << "xmmword ptr "; break;
4224 case 256: OS << "ymmword ptr "; break;
4231 unsigned Val = (*I).Val;
4232 OS << ".align " << Val;
4234 // Skip the original immediate.
4235 assert(Val < 10 && "Expected alignment less then 2^10.");
4236 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4239 case AOK_DotOperator:
4244 // Skip the original expression.
4245 AsmStart = Loc + (*I).Len + AdditionalSkip;
4248 // Emit the remainder of the asm string.
4249 if (AsmStart != AsmEnd)
4250 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4252 AsmString = OS.str();
4256 /// \brief Create an MCAsmParser instance.
4257 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4258 MCContext &C, MCStreamer &Out,
4259 const MCAsmInfo &MAI) {
4260 return new AsmParser(SM, C, Out, MAI);