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/StringMap.h"
17 #include "llvm/ADT/StringSwitch.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/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
152 const AsmToken &Lex();
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
162 void CheckForValidSection();
164 bool ParseStatement();
165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
173 void HandleMacroExit();
175 void PrintMacroInstantiations();
176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
185 /// \brief Reset the current lexer position to that given by \arg Loc. The
186 /// current token is not set; clients should ensure Lex() is called
188 void JumpToLoc(SMLoc Loc);
190 void EatToEndOfStatement();
192 /// \brief Parse up to the end of statement and a return the contents from the
193 /// current token until the end of the statement; the current token on exit
194 /// will be either the EndOfStatement or EOF.
195 StringRef ParseStringToEndOfStatement();
197 bool ParseAssignment(StringRef Name, bool allow_redef);
199 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
200 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
201 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
202 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
204 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
205 /// and set \arg Res to the identifier contents.
206 bool ParseIdentifier(StringRef &Res);
208 // Directive Parsing.
210 // ".ascii", ".asciiz", ".string"
211 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
212 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
213 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
214 bool ParseDirectiveFill(); // ".fill"
215 bool ParseDirectiveSpace(); // ".space"
216 bool ParseDirectiveZero(); // ".zero"
217 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
218 bool ParseDirectiveOrg(); // ".org"
219 // ".align{,32}", ".p2align{,w,l}"
220 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
222 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
223 /// accepts a single symbol (which should be a label or an external).
224 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
226 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
228 bool ParseDirectiveAbort(); // ".abort"
229 bool ParseDirectiveInclude(); // ".include"
231 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
232 // ".ifdef" or ".ifndef", depending on expect_defined
233 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
234 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
235 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
236 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
238 /// ParseEscapedString - Parse the current token as a string which may include
239 /// escaped characters and return the string contents.
240 bool ParseEscapedString(std::string &Data);
242 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
243 MCSymbolRefExpr::VariantKind Variant);
246 /// \brief Generic implementations of directive handling, etc. which is shared
247 /// (or the default, at least) for all assembler parser.
248 class GenericAsmParser : public MCAsmParserExtension {
249 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
250 void AddDirectiveHandler(StringRef Directive) {
251 getParser().AddDirectiveHandler(this, Directive,
252 HandleDirective<GenericAsmParser, Handler>);
255 GenericAsmParser() {}
257 AsmParser &getParser() {
258 return (AsmParser&) this->MCAsmParserExtension::getParser();
261 virtual void Initialize(MCAsmParser &Parser) {
262 // Call the base implementation.
263 this->MCAsmParserExtension::Initialize(Parser);
265 // Debugging directives.
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
281 ".cfi_def_cfa_offset");
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
283 ".cfi_adjust_cfa_offset");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
285 ".cfi_def_cfa_register");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
291 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
293 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
295 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
297 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
299 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
314 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
316 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveLEB128(StringRef, SMLoc);
345 extern MCAsmParserExtension *createDarwinAsmParser();
346 extern MCAsmParserExtension *createELFAsmParser();
347 extern MCAsmParserExtension *createCOFFAsmParser();
351 enum { DEFAULT_ADDRSPACE = 0 };
353 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
354 MCStreamer &_Out, const MCAsmInfo &_MAI)
355 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
356 GenericParser(new GenericAsmParser), PlatformParser(0),
357 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
358 // Save the old handler.
359 SavedDiagHandler = SrcMgr.getDiagHandler();
360 SavedDiagContext = SrcMgr.getDiagContext();
361 // Set our own handler which calls the saved handler.
362 SrcMgr.setDiagHandler(DiagHandler, this);
363 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
365 // Initialize the generic parser.
366 GenericParser->Initialize(*this);
368 // Initialize the platform / file format parser.
370 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
372 if (_MAI.hasMicrosoftFastStdCallMangling()) {
373 PlatformParser = createCOFFAsmParser();
374 PlatformParser->Initialize(*this);
375 } else if (_MAI.hasSubsectionsViaSymbols()) {
376 PlatformParser = createDarwinAsmParser();
377 PlatformParser->Initialize(*this);
379 PlatformParser = createELFAsmParser();
380 PlatformParser->Initialize(*this);
384 AsmParser::~AsmParser() {
385 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
387 // Destroy any macros.
388 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
389 ie = MacroMap.end(); it != ie; ++it)
390 delete it->getValue();
392 delete PlatformParser;
393 delete GenericParser;
396 void AsmParser::PrintMacroInstantiations() {
397 // Print the active macro instantiation stack.
398 for (std::vector<MacroInstantiation*>::const_reverse_iterator
399 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
400 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
401 "while in macro instantiation");
404 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
405 if (FatalAssemblerWarnings)
406 return Error(L, Msg, Ranges);
407 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
408 PrintMacroInstantiations();
412 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
414 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
415 PrintMacroInstantiations();
419 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
420 std::string IncludedFile;
421 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
427 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
432 void AsmParser::JumpToLoc(SMLoc Loc) {
433 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
434 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
437 const AsmToken &AsmParser::Lex() {
438 const AsmToken *tok = &Lexer.Lex();
440 if (tok->is(AsmToken::Eof)) {
441 // If this is the end of an included file, pop the parent file off the
443 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
444 if (ParentIncludeLoc != SMLoc()) {
445 JumpToLoc(ParentIncludeLoc);
450 if (tok->is(AsmToken::Error))
451 Error(Lexer.getErrLoc(), Lexer.getErr());
456 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
457 // Create the initial section, if requested.
458 if (!NoInitialTextSection)
465 AsmCond StartingCondState = TheCondState;
467 // If we are generating dwarf for assembly source files save the initial text
468 // section and generate a .file directive.
469 if (getContext().getGenDwarfForAssembly()) {
470 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
471 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
472 getStreamer().EmitLabel(SectionStartSym);
473 getContext().setGenDwarfSectionStartSym(SectionStartSym);
474 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
475 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
478 // While we have input, parse each statement.
479 while (Lexer.isNot(AsmToken::Eof)) {
480 if (!ParseStatement()) continue;
482 // We had an error, validate that one was emitted and recover by skipping to
484 assert(HadError && "Parse statement returned an error, but none emitted!");
485 EatToEndOfStatement();
488 if (TheCondState.TheCond != StartingCondState.TheCond ||
489 TheCondState.Ignore != StartingCondState.Ignore)
490 return TokError("unmatched .ifs or .elses");
492 // Check to see there are no empty DwarfFile slots.
493 const std::vector<MCDwarfFile *> &MCDwarfFiles =
494 getContext().getMCDwarfFiles();
495 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
496 if (!MCDwarfFiles[i])
497 TokError("unassigned file number: " + Twine(i) + " for .file directives");
500 // Check to see that all assembler local symbols were actually defined.
501 // Targets that don't do subsections via symbols may not want this, though,
502 // so conservatively exclude them. Only do this if we're finalizing, though,
503 // as otherwise we won't necessarilly have seen everything yet.
504 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
505 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
506 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
509 MCSymbol *Sym = i->getValue();
510 // Variable symbols may not be marked as defined, so check those
511 // explicitly. If we know it's a variable, we have a definition for
512 // the purposes of this check.
513 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
514 // FIXME: We would really like to refer back to where the symbol was
515 // first referenced for a source location. We need to add something
516 // to track that. Currently, we just point to the end of the file.
517 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
518 "assembler local symbol '" + Sym->getName() +
524 // Finalize the output stream if there are no errors and if the client wants
526 if (!HadError && !NoFinalize)
532 void AsmParser::CheckForValidSection() {
533 if (!getStreamer().getCurrentSection()) {
534 TokError("expected section directive before assembly directive");
535 Out.SwitchSection(Ctx.getMachOSection(
537 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
538 0, SectionKind::getText()));
542 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
543 void AsmParser::EatToEndOfStatement() {
544 while (Lexer.isNot(AsmToken::EndOfStatement) &&
545 Lexer.isNot(AsmToken::Eof))
549 if (Lexer.is(AsmToken::EndOfStatement))
553 StringRef AsmParser::ParseStringToEndOfStatement() {
554 const char *Start = getTok().getLoc().getPointer();
556 while (Lexer.isNot(AsmToken::EndOfStatement) &&
557 Lexer.isNot(AsmToken::Eof))
560 const char *End = getTok().getLoc().getPointer();
561 return StringRef(Start, End - Start);
564 /// ParseParenExpr - Parse a paren expression and return it.
565 /// NOTE: This assumes the leading '(' has already been consumed.
567 /// parenexpr ::= expr)
569 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
570 if (ParseExpression(Res)) return true;
571 if (Lexer.isNot(AsmToken::RParen))
572 return TokError("expected ')' in parentheses expression");
573 EndLoc = Lexer.getLoc();
578 /// ParseBracketExpr - Parse a bracket expression and return it.
579 /// NOTE: This assumes the leading '[' has already been consumed.
581 /// bracketexpr ::= expr]
583 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
584 if (ParseExpression(Res)) return true;
585 if (Lexer.isNot(AsmToken::RBrac))
586 return TokError("expected ']' in brackets expression");
587 EndLoc = Lexer.getLoc();
592 /// ParsePrimaryExpr - Parse a primary expression and return it.
593 /// primaryexpr ::= (parenexpr
594 /// primaryexpr ::= symbol
595 /// primaryexpr ::= number
596 /// primaryexpr ::= '.'
597 /// primaryexpr ::= ~,+,- primaryexpr
598 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
599 switch (Lexer.getKind()) {
601 return TokError("unknown token in expression");
602 // If we have an error assume that we've already handled it.
603 case AsmToken::Error:
605 case AsmToken::Exclaim:
606 Lex(); // Eat the operator.
607 if (ParsePrimaryExpr(Res, EndLoc))
609 Res = MCUnaryExpr::CreateLNot(Res, getContext());
611 case AsmToken::Dollar:
612 case AsmToken::String:
613 case AsmToken::Identifier: {
614 EndLoc = Lexer.getLoc();
616 StringRef Identifier;
617 if (ParseIdentifier(Identifier))
620 // This is a symbol reference.
621 std::pair<StringRef, StringRef> Split = Identifier.split('@');
622 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
624 // Lookup the symbol variant if used.
625 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
626 if (Split.first.size() != Identifier.size()) {
627 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
628 if (Variant == MCSymbolRefExpr::VK_Invalid) {
629 Variant = MCSymbolRefExpr::VK_None;
630 return TokError("invalid variant '" + Split.second + "'");
634 // If this is an absolute variable reference, substitute it now to preserve
635 // semantics in the face of reassignment.
636 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
638 return Error(EndLoc, "unexpected modifier on variable reference");
640 Res = Sym->getVariableValue();
644 // Otherwise create a symbol ref.
645 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
648 case AsmToken::Integer: {
649 SMLoc Loc = getTok().getLoc();
650 int64_t IntVal = getTok().getIntVal();
651 Res = MCConstantExpr::Create(IntVal, getContext());
652 EndLoc = Lexer.getLoc();
654 // Look for 'b' or 'f' following an Integer as a directional label
655 if (Lexer.getKind() == AsmToken::Identifier) {
656 StringRef IDVal = getTok().getString();
657 if (IDVal == "f" || IDVal == "b"){
658 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
659 IDVal == "f" ? 1 : 0);
660 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
662 if(IDVal == "b" && Sym->isUndefined())
663 return Error(Loc, "invalid reference to undefined symbol");
664 EndLoc = Lexer.getLoc();
665 Lex(); // Eat identifier.
670 case AsmToken::Real: {
671 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
672 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
673 Res = MCConstantExpr::Create(IntVal, getContext());
677 case AsmToken::Dot: {
678 // This is a '.' reference, which references the current PC. Emit a
679 // temporary label to the streamer and refer to it.
680 MCSymbol *Sym = Ctx.CreateTempSymbol();
682 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
683 EndLoc = Lexer.getLoc();
684 Lex(); // Eat identifier.
687 case AsmToken::LParen:
688 Lex(); // Eat the '('.
689 return ParseParenExpr(Res, EndLoc);
690 case AsmToken::LBrac:
691 if (!PlatformParser->HasBracketExpressions())
692 return TokError("brackets expression not supported on this target");
693 Lex(); // Eat the '['.
694 return ParseBracketExpr(Res, EndLoc);
695 case AsmToken::Minus:
696 Lex(); // Eat the operator.
697 if (ParsePrimaryExpr(Res, EndLoc))
699 Res = MCUnaryExpr::CreateMinus(Res, getContext());
702 Lex(); // Eat the operator.
703 if (ParsePrimaryExpr(Res, EndLoc))
705 Res = MCUnaryExpr::CreatePlus(Res, getContext());
707 case AsmToken::Tilde:
708 Lex(); // Eat the operator.
709 if (ParsePrimaryExpr(Res, EndLoc))
711 Res = MCUnaryExpr::CreateNot(Res, getContext());
716 bool AsmParser::ParseExpression(const MCExpr *&Res) {
718 return ParseExpression(Res, EndLoc);
722 AsmParser::ApplyModifierToExpr(const MCExpr *E,
723 MCSymbolRefExpr::VariantKind Variant) {
724 // Recurse over the given expression, rebuilding it to apply the given variant
725 // if there is exactly one symbol.
726 switch (E->getKind()) {
728 case MCExpr::Constant:
731 case MCExpr::SymbolRef: {
732 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
734 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
735 TokError("invalid variant on expression '" +
736 getTok().getIdentifier() + "' (already modified)");
740 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
743 case MCExpr::Unary: {
744 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
745 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
748 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
751 case MCExpr::Binary: {
752 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
753 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
754 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
759 if (!LHS) LHS = BE->getLHS();
760 if (!RHS) RHS = BE->getRHS();
762 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
766 assert(0 && "Invalid expression kind!");
770 /// ParseExpression - Parse an expression and return it.
772 /// expr ::= expr &&,|| expr -> lowest.
773 /// expr ::= expr |,^,&,! expr
774 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
775 /// expr ::= expr <<,>> expr
776 /// expr ::= expr +,- expr
777 /// expr ::= expr *,/,% expr -> highest.
778 /// expr ::= primaryexpr
780 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
781 // Parse the expression.
783 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
786 // As a special case, we support 'a op b @ modifier' by rewriting the
787 // expression to include the modifier. This is inefficient, but in general we
788 // expect users to use 'a@modifier op b'.
789 if (Lexer.getKind() == AsmToken::At) {
792 if (Lexer.isNot(AsmToken::Identifier))
793 return TokError("unexpected symbol modifier following '@'");
795 MCSymbolRefExpr::VariantKind Variant =
796 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
797 if (Variant == MCSymbolRefExpr::VK_Invalid)
798 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
800 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
802 return TokError("invalid modifier '" + getTok().getIdentifier() +
803 "' (no symbols present)");
811 // Try to constant fold it up front, if possible.
813 if (Res->EvaluateAsAbsolute(Value))
814 Res = MCConstantExpr::Create(Value, getContext());
819 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
821 return ParseParenExpr(Res, EndLoc) ||
822 ParseBinOpRHS(1, Res, EndLoc);
825 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
828 SMLoc StartLoc = Lexer.getLoc();
829 if (ParseExpression(Expr))
832 if (!Expr->EvaluateAsAbsolute(Res))
833 return Error(StartLoc, "expected absolute expression");
838 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
839 MCBinaryExpr::Opcode &Kind) {
842 return 0; // not a binop.
844 // Lowest Precedence: &&, ||
845 case AsmToken::AmpAmp:
846 Kind = MCBinaryExpr::LAnd;
848 case AsmToken::PipePipe:
849 Kind = MCBinaryExpr::LOr;
853 // Low Precedence: |, &, ^
855 // FIXME: gas seems to support '!' as an infix operator?
857 Kind = MCBinaryExpr::Or;
859 case AsmToken::Caret:
860 Kind = MCBinaryExpr::Xor;
863 Kind = MCBinaryExpr::And;
866 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
867 case AsmToken::EqualEqual:
868 Kind = MCBinaryExpr::EQ;
870 case AsmToken::ExclaimEqual:
871 case AsmToken::LessGreater:
872 Kind = MCBinaryExpr::NE;
875 Kind = MCBinaryExpr::LT;
877 case AsmToken::LessEqual:
878 Kind = MCBinaryExpr::LTE;
880 case AsmToken::Greater:
881 Kind = MCBinaryExpr::GT;
883 case AsmToken::GreaterEqual:
884 Kind = MCBinaryExpr::GTE;
887 // Intermediate Precedence: <<, >>
888 case AsmToken::LessLess:
889 Kind = MCBinaryExpr::Shl;
891 case AsmToken::GreaterGreater:
892 Kind = MCBinaryExpr::Shr;
895 // High Intermediate Precedence: +, -
897 Kind = MCBinaryExpr::Add;
899 case AsmToken::Minus:
900 Kind = MCBinaryExpr::Sub;
903 // Highest Precedence: *, /, %
905 Kind = MCBinaryExpr::Mul;
907 case AsmToken::Slash:
908 Kind = MCBinaryExpr::Div;
910 case AsmToken::Percent:
911 Kind = MCBinaryExpr::Mod;
917 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
918 /// Res contains the LHS of the expression on input.
919 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
922 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
923 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
925 // If the next token is lower precedence than we are allowed to eat, return
926 // successfully with what we ate already.
927 if (TokPrec < Precedence)
932 // Eat the next primary expression.
934 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
936 // If BinOp binds less tightly with RHS than the operator after RHS, let
937 // the pending operator take RHS as its LHS.
938 MCBinaryExpr::Opcode Dummy;
939 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
940 if (TokPrec < NextTokPrec) {
941 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
944 // Merge LHS and RHS according to operator.
945 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
953 /// ::= EndOfStatement
954 /// ::= Label* Directive ...Operands... EndOfStatement
955 /// ::= Label* Identifier OperandList* EndOfStatement
956 bool AsmParser::ParseStatement() {
957 if (Lexer.is(AsmToken::EndOfStatement)) {
963 // Statements always start with an identifier or are a full line comment.
964 AsmToken ID = getTok();
965 SMLoc IDLoc = ID.getLoc();
967 int64_t LocalLabelVal = -1;
968 // A full line comment is a '#' as the first token.
969 if (Lexer.is(AsmToken::Hash))
970 return ParseCppHashLineFilenameComment(IDLoc);
972 // Allow an integer followed by a ':' as a directional local label.
973 if (Lexer.is(AsmToken::Integer)) {
974 LocalLabelVal = getTok().getIntVal();
975 if (LocalLabelVal < 0) {
976 if (!TheCondState.Ignore)
977 return TokError("unexpected token at start of statement");
981 IDVal = getTok().getString();
982 Lex(); // Consume the integer token to be used as an identifier token.
983 if (Lexer.getKind() != AsmToken::Colon) {
984 if (!TheCondState.Ignore)
985 return TokError("unexpected token at start of statement");
989 } else if (Lexer.is(AsmToken::Dot)) {
990 // Treat '.' as a valid identifier in this context.
994 } else if (ParseIdentifier(IDVal)) {
995 if (!TheCondState.Ignore)
996 return TokError("unexpected token at start of statement");
1001 // Handle conditional assembly here before checking for skipping. We
1002 // have to do this so that .endif isn't skipped in a ".if 0" block for
1005 return ParseDirectiveIf(IDLoc);
1006 if (IDVal == ".ifdef")
1007 return ParseDirectiveIfdef(IDLoc, true);
1008 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1009 return ParseDirectiveIfdef(IDLoc, false);
1010 if (IDVal == ".elseif")
1011 return ParseDirectiveElseIf(IDLoc);
1012 if (IDVal == ".else")
1013 return ParseDirectiveElse(IDLoc);
1014 if (IDVal == ".endif")
1015 return ParseDirectiveEndIf(IDLoc);
1017 // If we are in a ".if 0" block, ignore this statement.
1018 if (TheCondState.Ignore) {
1019 EatToEndOfStatement();
1023 // FIXME: Recurse on local labels?
1025 // See what kind of statement we have.
1026 switch (Lexer.getKind()) {
1027 case AsmToken::Colon: {
1028 CheckForValidSection();
1030 // identifier ':' -> Label.
1033 // Diagnose attempt to use '.' as a label.
1035 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1037 // Diagnose attempt to use a variable as a label.
1039 // FIXME: Diagnostics. Note the location of the definition as a label.
1040 // FIXME: This doesn't diagnose assignment to a symbol which has been
1041 // implicitly marked as external.
1043 if (LocalLabelVal == -1)
1044 Sym = getContext().GetOrCreateSymbol(IDVal);
1046 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1047 if (!Sym->isUndefined() || Sym->isVariable())
1048 return Error(IDLoc, "invalid symbol redefinition");
1053 // If we are generating dwarf for assembly source files then gather the
1054 // info to make a dwarf subprogram entry for this label if needed.
1055 if (getContext().getGenDwarfForAssembly())
1056 MCGenDwarfSubprogramEntry::Make(Sym, &getStreamer(), getSourceManager(),
1059 // Consume any end of statement token, if present, to avoid spurious
1060 // AddBlankLine calls().
1061 if (Lexer.is(AsmToken::EndOfStatement)) {
1063 if (Lexer.is(AsmToken::Eof))
1067 return ParseStatement();
1070 case AsmToken::Equal:
1071 // identifier '=' ... -> assignment statement
1074 return ParseAssignment(IDVal, true);
1076 default: // Normal instruction or directive.
1080 // If macros are enabled, check to see if this is a macro instantiation.
1082 if (const Macro *M = MacroMap.lookup(IDVal))
1083 return HandleMacroEntry(IDVal, IDLoc, M);
1085 // Otherwise, we have a normal instruction or directive.
1086 if (IDVal[0] == '.' && IDVal != ".") {
1087 // Assembler features
1088 if (IDVal == ".set" || IDVal == ".equ")
1089 return ParseDirectiveSet(IDVal, true);
1090 if (IDVal == ".equiv")
1091 return ParseDirectiveSet(IDVal, false);
1095 if (IDVal == ".ascii")
1096 return ParseDirectiveAscii(IDVal, false);
1097 if (IDVal == ".asciz" || IDVal == ".string")
1098 return ParseDirectiveAscii(IDVal, true);
1100 if (IDVal == ".byte")
1101 return ParseDirectiveValue(1);
1102 if (IDVal == ".short")
1103 return ParseDirectiveValue(2);
1104 if (IDVal == ".value")
1105 return ParseDirectiveValue(2);
1106 if (IDVal == ".2byte")
1107 return ParseDirectiveValue(2);
1108 if (IDVal == ".long")
1109 return ParseDirectiveValue(4);
1110 if (IDVal == ".int")
1111 return ParseDirectiveValue(4);
1112 if (IDVal == ".4byte")
1113 return ParseDirectiveValue(4);
1114 if (IDVal == ".quad")
1115 return ParseDirectiveValue(8);
1116 if (IDVal == ".8byte")
1117 return ParseDirectiveValue(8);
1118 if (IDVal == ".single" || IDVal == ".float")
1119 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1120 if (IDVal == ".double")
1121 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1123 if (IDVal == ".align") {
1124 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1125 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1127 if (IDVal == ".align32") {
1128 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1129 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1131 if (IDVal == ".balign")
1132 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1133 if (IDVal == ".balignw")
1134 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1135 if (IDVal == ".balignl")
1136 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1137 if (IDVal == ".p2align")
1138 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1139 if (IDVal == ".p2alignw")
1140 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1141 if (IDVal == ".p2alignl")
1142 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1144 if (IDVal == ".org")
1145 return ParseDirectiveOrg();
1147 if (IDVal == ".fill")
1148 return ParseDirectiveFill();
1149 if (IDVal == ".space" || IDVal == ".skip")
1150 return ParseDirectiveSpace();
1151 if (IDVal == ".zero")
1152 return ParseDirectiveZero();
1154 // Symbol attribute directives
1156 if (IDVal == ".globl" || IDVal == ".global")
1157 return ParseDirectiveSymbolAttribute(MCSA_Global);
1158 if (IDVal == ".indirect_symbol")
1159 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1160 if (IDVal == ".lazy_reference")
1161 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1162 if (IDVal == ".no_dead_strip")
1163 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1164 if (IDVal == ".symbol_resolver")
1165 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1166 if (IDVal == ".private_extern")
1167 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1168 if (IDVal == ".reference")
1169 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1170 if (IDVal == ".weak_definition")
1171 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1172 if (IDVal == ".weak_reference")
1173 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1174 if (IDVal == ".weak_def_can_be_hidden")
1175 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1177 if (IDVal == ".comm" || IDVal == ".common")
1178 return ParseDirectiveComm(/*IsLocal=*/false);
1179 if (IDVal == ".lcomm")
1180 return ParseDirectiveComm(/*IsLocal=*/true);
1182 if (IDVal == ".abort")
1183 return ParseDirectiveAbort();
1184 if (IDVal == ".include")
1185 return ParseDirectiveInclude();
1187 if (IDVal == ".code16")
1188 return TokError(Twine(IDVal) + " not supported yet");
1190 // Look up the handler in the handler table.
1191 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1192 DirectiveMap.lookup(IDVal);
1194 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1196 // Target hook for parsing target specific directives.
1197 if (!getTargetParser().ParseDirective(ID))
1200 bool retval = Warning(IDLoc, "ignoring directive for now");
1201 EatToEndOfStatement();
1205 CheckForValidSection();
1207 // Canonicalize the opcode to lower case.
1208 SmallString<128> Opcode;
1209 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1210 Opcode.push_back(tolower(IDVal[i]));
1212 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1213 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1216 // Dump the parsed representation, if requested.
1217 if (getShowParsedOperands()) {
1218 SmallString<256> Str;
1219 raw_svector_ostream OS(Str);
1220 OS << "parsed instruction: [";
1221 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1224 ParsedOperands[i]->print(OS);
1228 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1231 // If we are generating dwarf for assembly source files and the current
1232 // section is the initial text section then generate a .loc directive for
1234 if (!HadError && getContext().getGenDwarfForAssembly() &&
1235 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1236 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1237 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1238 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1239 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1243 // If parsing succeeded, match the instruction.
1245 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1248 // Free any parsed operands.
1249 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1250 delete ParsedOperands[i];
1252 // Don't skip the rest of the line, the instruction parser is responsible for
1257 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1258 /// since they may not be able to be tokenized to get to the end of line token.
1259 void AsmParser::EatToEndOfLine() {
1260 if (!Lexer.is(AsmToken::EndOfStatement))
1261 Lexer.LexUntilEndOfLine();
1266 /// ParseCppHashLineFilenameComment as this:
1267 /// ::= # number "filename"
1268 /// or just as a full line comment if it doesn't have a number and a string.
1269 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1270 Lex(); // Eat the hash token.
1272 if (getLexer().isNot(AsmToken::Integer)) {
1273 // Consume the line since in cases it is not a well-formed line directive,
1274 // as if were simply a full line comment.
1279 int64_t LineNumber = getTok().getIntVal();
1282 if (getLexer().isNot(AsmToken::String)) {
1287 StringRef Filename = getTok().getString();
1288 // Get rid of the enclosing quotes.
1289 Filename = Filename.substr(1, Filename.size()-2);
1291 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1293 CppHashFilename = Filename;
1294 CppHashLineNumber = LineNumber;
1296 // Ignore any trailing characters, they're just comment.
1301 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1302 /// for the Filename and LineNo if any in the diagnostic.
1303 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1304 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1305 raw_ostream &OS = errs();
1307 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1308 const SMLoc &DiagLoc = Diag.getLoc();
1309 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1310 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1312 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1313 // before printing the message.
1314 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1315 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1316 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1317 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1320 // If we have not parsed a cpp hash line filename comment or the source
1321 // manager changed or buffer changed (like in a nested include) then just
1322 // print the normal diagnostic using its Filename and LineNo.
1323 if (!Parser->CppHashLineNumber ||
1324 &DiagSrcMgr != &Parser->SrcMgr ||
1325 DiagBuf != CppHashBuf) {
1326 if (Parser->SavedDiagHandler)
1327 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1333 // Use the CppHashFilename and calculate a line number based on the
1334 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1336 const std::string Filename = Parser->CppHashFilename;
1338 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1339 int CppHashLocLineNo =
1340 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1341 int LineNo = Parser->CppHashLineNumber - 1 +
1342 (DiagLocLineNo - CppHashLocLineNo);
1344 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1345 Filename, LineNo, Diag.getColumnNo(),
1346 Diag.getKind(), Diag.getMessage(),
1347 Diag.getLineContents(), Diag.getRanges());
1349 if (Parser->SavedDiagHandler)
1350 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1352 NewDiag.print(0, OS);
1355 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1356 const std::vector<StringRef> &Parameters,
1357 const std::vector<std::vector<AsmToken> > &A,
1359 raw_svector_ostream OS(Buf);
1360 unsigned NParameters = Parameters.size();
1361 if (NParameters != 0 && NParameters != A.size())
1362 return Error(L, "Wrong number of arguments");
1364 while (!Body.empty()) {
1365 // Scan for the next substitution.
1366 std::size_t End = Body.size(), Pos = 0;
1367 for (; Pos != End; ++Pos) {
1368 // Check for a substitution or escape.
1370 // This macro has no parameters, look for $0, $1, etc.
1371 if (Body[Pos] != '$' || Pos + 1 == End)
1374 char Next = Body[Pos + 1];
1375 if (Next == '$' || Next == 'n' || isdigit(Next))
1378 // This macro has parameters, look for \foo, \bar, etc.
1379 if (Body[Pos] == '\\' && Pos + 1 != End)
1385 OS << Body.slice(0, Pos);
1387 // Check if we reached the end.
1392 switch (Body[Pos+1]) {
1398 // $n => number of arguments
1403 // $[0-9] => argument
1405 // Missing arguments are ignored.
1406 unsigned Index = Body[Pos+1] - '0';
1407 if (Index >= A.size())
1410 // Otherwise substitute with the token values, with spaces eliminated.
1411 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1412 ie = A[Index].end(); it != ie; ++it)
1413 OS << it->getString();
1419 unsigned I = Pos + 1;
1420 while (isalnum(Body[I]) && I + 1 != End)
1423 const char *Begin = Body.data() + Pos +1;
1424 StringRef Argument(Begin, I - (Pos +1));
1426 for (; Index < NParameters; ++Index)
1427 if (Parameters[Index] == Argument)
1430 // FIXME: We should error at the macro definition.
1431 if (Index == NParameters)
1432 return Error(L, "Parameter not found");
1434 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1435 ie = A[Index].end(); it != ie; ++it)
1436 OS << it->getString();
1438 Pos += 1 + Argument.size();
1440 // Update the scan point.
1441 Body = Body.substr(Pos);
1444 // We include the .endmacro in the buffer as our queue to exit the macro
1446 OS << ".endmacro\n";
1450 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1452 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1456 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1458 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1459 // this, although we should protect against infinite loops.
1460 if (ActiveMacros.size() == 20)
1461 return TokError("macros cannot be nested more than 20 levels deep");
1463 // Parse the macro instantiation arguments.
1464 std::vector<std::vector<AsmToken> > MacroArguments;
1465 MacroArguments.push_back(std::vector<AsmToken>());
1466 unsigned ParenLevel = 0;
1468 if (Lexer.is(AsmToken::Eof))
1469 return TokError("unexpected token in macro instantiation");
1470 if (Lexer.is(AsmToken::EndOfStatement))
1473 // If we aren't inside parentheses and this is a comma, start a new token
1475 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1476 MacroArguments.push_back(std::vector<AsmToken>());
1478 // Adjust the current parentheses level.
1479 if (Lexer.is(AsmToken::LParen))
1481 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1484 // Append the token to the current argument list.
1485 MacroArguments.back().push_back(getTok());
1490 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1491 // to hold the macro body with substitutions.
1492 SmallString<256> Buf;
1493 StringRef Body = M->Body;
1495 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1498 MemoryBuffer *Instantiation =
1499 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1501 // Create the macro instantiation object and add to the current macro
1502 // instantiation stack.
1503 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1506 ActiveMacros.push_back(MI);
1508 // Jump to the macro instantiation and prime the lexer.
1509 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1510 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1516 void AsmParser::HandleMacroExit() {
1517 // Jump to the EndOfStatement we should return to, and consume it.
1518 JumpToLoc(ActiveMacros.back()->ExitLoc);
1521 // Pop the instantiation entry.
1522 delete ActiveMacros.back();
1523 ActiveMacros.pop_back();
1526 static void MarkUsed(const MCExpr *Value) {
1527 switch (Value->getKind()) {
1528 case MCExpr::Binary:
1529 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1530 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1532 case MCExpr::Target:
1533 case MCExpr::Constant:
1535 case MCExpr::SymbolRef: {
1536 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1540 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1545 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1546 // FIXME: Use better location, we should use proper tokens.
1547 SMLoc EqualLoc = Lexer.getLoc();
1549 const MCExpr *Value;
1550 if (ParseExpression(Value))
1555 if (Lexer.isNot(AsmToken::EndOfStatement))
1556 return TokError("unexpected token in assignment");
1558 // Error on assignment to '.'.
1560 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1561 "(use '.space' or '.org').)"));
1564 // Eat the end of statement marker.
1567 // Validate that the LHS is allowed to be a variable (either it has not been
1568 // used as a symbol, or it is an absolute symbol).
1569 MCSymbol *Sym = getContext().LookupSymbol(Name);
1571 // Diagnose assignment to a label.
1573 // FIXME: Diagnostics. Note the location of the definition as a label.
1574 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1575 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1576 ; // Allow redefinitions of undefined symbols only used in directives.
1577 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1578 return Error(EqualLoc, "redefinition of '" + Name + "'");
1579 else if (!Sym->isVariable())
1580 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1581 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1582 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1585 // Don't count these checks as uses.
1586 Sym->setUsed(false);
1588 Sym = getContext().GetOrCreateSymbol(Name);
1590 // FIXME: Handle '.'.
1592 // Do the assignment.
1593 Out.EmitAssignment(Sym, Value);
1598 /// ParseIdentifier:
1601 bool AsmParser::ParseIdentifier(StringRef &Res) {
1602 // The assembler has relaxed rules for accepting identifiers, in particular we
1603 // allow things like '.globl $foo', which would normally be separate
1604 // tokens. At this level, we have already lexed so we cannot (currently)
1605 // handle this as a context dependent token, instead we detect adjacent tokens
1606 // and return the combined identifier.
1607 if (Lexer.is(AsmToken::Dollar)) {
1608 SMLoc DollarLoc = getLexer().getLoc();
1610 // Consume the dollar sign, and check for a following identifier.
1612 if (Lexer.isNot(AsmToken::Identifier))
1615 // We have a '$' followed by an identifier, make sure they are adjacent.
1616 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1619 // Construct the joined identifier and consume the token.
1620 Res = StringRef(DollarLoc.getPointer(),
1621 getTok().getIdentifier().size() + 1);
1626 if (Lexer.isNot(AsmToken::Identifier) &&
1627 Lexer.isNot(AsmToken::String))
1630 Res = getTok().getIdentifier();
1632 Lex(); // Consume the identifier token.
1637 /// ParseDirectiveSet:
1638 /// ::= .equ identifier ',' expression
1639 /// ::= .equiv identifier ',' expression
1640 /// ::= .set identifier ',' expression
1641 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1644 if (ParseIdentifier(Name))
1645 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1647 if (getLexer().isNot(AsmToken::Comma))
1648 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1651 return ParseAssignment(Name, allow_redef);
1654 bool AsmParser::ParseEscapedString(std::string &Data) {
1655 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1658 StringRef Str = getTok().getStringContents();
1659 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1660 if (Str[i] != '\\') {
1665 // Recognize escaped characters. Note that this escape semantics currently
1666 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1669 return TokError("unexpected backslash at end of string");
1671 // Recognize octal sequences.
1672 if ((unsigned) (Str[i] - '0') <= 7) {
1673 // Consume up to three octal characters.
1674 unsigned Value = Str[i] - '0';
1676 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1678 Value = Value * 8 + (Str[i] - '0');
1680 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1682 Value = Value * 8 + (Str[i] - '0');
1687 return TokError("invalid octal escape sequence (out of range)");
1689 Data += (unsigned char) Value;
1693 // Otherwise recognize individual escapes.
1696 // Just reject invalid escape sequences for now.
1697 return TokError("invalid escape sequence (unrecognized character)");
1699 case 'b': Data += '\b'; break;
1700 case 'f': Data += '\f'; break;
1701 case 'n': Data += '\n'; break;
1702 case 'r': Data += '\r'; break;
1703 case 't': Data += '\t'; break;
1704 case '"': Data += '"'; break;
1705 case '\\': Data += '\\'; break;
1712 /// ParseDirectiveAscii:
1713 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1714 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1715 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1716 CheckForValidSection();
1719 if (getLexer().isNot(AsmToken::String))
1720 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1723 if (ParseEscapedString(Data))
1726 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1728 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1732 if (getLexer().is(AsmToken::EndOfStatement))
1735 if (getLexer().isNot(AsmToken::Comma))
1736 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1745 /// ParseDirectiveValue
1746 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1747 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1748 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1749 CheckForValidSection();
1752 const MCExpr *Value;
1753 SMLoc ExprLoc = getLexer().getLoc();
1754 if (ParseExpression(Value))
1757 // Special case constant expressions to match code generator.
1758 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1759 assert(Size <= 8 && "Invalid size");
1760 uint64_t IntValue = MCE->getValue();
1761 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1762 return Error(ExprLoc, "literal value out of range for directive");
1763 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1765 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1767 if (getLexer().is(AsmToken::EndOfStatement))
1770 // FIXME: Improve diagnostic.
1771 if (getLexer().isNot(AsmToken::Comma))
1772 return TokError("unexpected token in directive");
1781 /// ParseDirectiveRealValue
1782 /// ::= (.single | .double) [ expression (, expression)* ]
1783 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1784 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1785 CheckForValidSection();
1788 // We don't truly support arithmetic on floating point expressions, so we
1789 // have to manually parse unary prefixes.
1791 if (getLexer().is(AsmToken::Minus)) {
1794 } else if (getLexer().is(AsmToken::Plus))
1797 if (getLexer().isNot(AsmToken::Integer) &&
1798 getLexer().isNot(AsmToken::Real) &&
1799 getLexer().isNot(AsmToken::Identifier))
1800 return TokError("unexpected token in directive");
1802 // Convert to an APFloat.
1803 APFloat Value(Semantics);
1804 StringRef IDVal = getTok().getString();
1805 if (getLexer().is(AsmToken::Identifier)) {
1806 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1807 Value = APFloat::getInf(Semantics);
1808 else if (!IDVal.compare_lower("nan"))
1809 Value = APFloat::getNaN(Semantics, false, ~0);
1811 return TokError("invalid floating point literal");
1812 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1813 APFloat::opInvalidOp)
1814 return TokError("invalid floating point literal");
1818 // Consume the numeric token.
1821 // Emit the value as an integer.
1822 APInt AsInt = Value.bitcastToAPInt();
1823 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1824 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1826 if (getLexer().is(AsmToken::EndOfStatement))
1829 if (getLexer().isNot(AsmToken::Comma))
1830 return TokError("unexpected token in directive");
1839 /// ParseDirectiveSpace
1840 /// ::= .space expression [ , expression ]
1841 bool AsmParser::ParseDirectiveSpace() {
1842 CheckForValidSection();
1845 if (ParseAbsoluteExpression(NumBytes))
1848 int64_t FillExpr = 0;
1849 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1850 if (getLexer().isNot(AsmToken::Comma))
1851 return TokError("unexpected token in '.space' directive");
1854 if (ParseAbsoluteExpression(FillExpr))
1857 if (getLexer().isNot(AsmToken::EndOfStatement))
1858 return TokError("unexpected token in '.space' directive");
1864 return TokError("invalid number of bytes in '.space' directive");
1866 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1867 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1872 /// ParseDirectiveZero
1873 /// ::= .zero expression
1874 bool AsmParser::ParseDirectiveZero() {
1875 CheckForValidSection();
1878 if (ParseAbsoluteExpression(NumBytes))
1882 if (getLexer().is(AsmToken::Comma)) {
1884 if (ParseAbsoluteExpression(Val))
1888 if (getLexer().isNot(AsmToken::EndOfStatement))
1889 return TokError("unexpected token in '.zero' directive");
1893 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1898 /// ParseDirectiveFill
1899 /// ::= .fill expression , expression , expression
1900 bool AsmParser::ParseDirectiveFill() {
1901 CheckForValidSection();
1904 if (ParseAbsoluteExpression(NumValues))
1907 if (getLexer().isNot(AsmToken::Comma))
1908 return TokError("unexpected token in '.fill' directive");
1912 if (ParseAbsoluteExpression(FillSize))
1915 if (getLexer().isNot(AsmToken::Comma))
1916 return TokError("unexpected token in '.fill' directive");
1920 if (ParseAbsoluteExpression(FillExpr))
1923 if (getLexer().isNot(AsmToken::EndOfStatement))
1924 return TokError("unexpected token in '.fill' directive");
1928 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1929 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1931 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1932 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1937 /// ParseDirectiveOrg
1938 /// ::= .org expression [ , expression ]
1939 bool AsmParser::ParseDirectiveOrg() {
1940 CheckForValidSection();
1942 const MCExpr *Offset;
1943 if (ParseExpression(Offset))
1946 // Parse optional fill expression.
1947 int64_t FillExpr = 0;
1948 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1949 if (getLexer().isNot(AsmToken::Comma))
1950 return TokError("unexpected token in '.org' directive");
1953 if (ParseAbsoluteExpression(FillExpr))
1956 if (getLexer().isNot(AsmToken::EndOfStatement))
1957 return TokError("unexpected token in '.org' directive");
1962 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1963 // has to be relative to the current section.
1964 getStreamer().EmitValueToOffset(Offset, FillExpr);
1969 /// ParseDirectiveAlign
1970 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1971 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1972 CheckForValidSection();
1974 SMLoc AlignmentLoc = getLexer().getLoc();
1976 if (ParseAbsoluteExpression(Alignment))
1980 bool HasFillExpr = false;
1981 int64_t FillExpr = 0;
1982 int64_t MaxBytesToFill = 0;
1983 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1984 if (getLexer().isNot(AsmToken::Comma))
1985 return TokError("unexpected token in directive");
1988 // The fill expression can be omitted while specifying a maximum number of
1989 // alignment bytes, e.g:
1991 if (getLexer().isNot(AsmToken::Comma)) {
1993 if (ParseAbsoluteExpression(FillExpr))
1997 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1998 if (getLexer().isNot(AsmToken::Comma))
1999 return TokError("unexpected token in directive");
2002 MaxBytesLoc = getLexer().getLoc();
2003 if (ParseAbsoluteExpression(MaxBytesToFill))
2006 if (getLexer().isNot(AsmToken::EndOfStatement))
2007 return TokError("unexpected token in directive");
2016 // Compute alignment in bytes.
2018 // FIXME: Diagnose overflow.
2019 if (Alignment >= 32) {
2020 Error(AlignmentLoc, "invalid alignment value");
2024 Alignment = 1ULL << Alignment;
2027 // Diagnose non-sensical max bytes to align.
2028 if (MaxBytesLoc.isValid()) {
2029 if (MaxBytesToFill < 1) {
2030 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2031 "many bytes, ignoring maximum bytes expression");
2035 if (MaxBytesToFill >= Alignment) {
2036 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2042 // Check whether we should use optimal code alignment for this .align
2044 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2045 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2046 ValueSize == 1 && UseCodeAlign) {
2047 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2049 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2050 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2057 /// ParseDirectiveSymbolAttribute
2058 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2059 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2060 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2063 SMLoc Loc = getTok().getLoc();
2065 if (ParseIdentifier(Name))
2066 return Error(Loc, "expected identifier in directive");
2068 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2070 // Assembler local symbols don't make any sense here. Complain loudly.
2071 if (Sym->isTemporary())
2072 return Error(Loc, "non-local symbol required in directive");
2074 getStreamer().EmitSymbolAttribute(Sym, Attr);
2076 if (getLexer().is(AsmToken::EndOfStatement))
2079 if (getLexer().isNot(AsmToken::Comma))
2080 return TokError("unexpected token in directive");
2089 /// ParseDirectiveComm
2090 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2091 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2092 CheckForValidSection();
2094 SMLoc IDLoc = getLexer().getLoc();
2096 if (ParseIdentifier(Name))
2097 return TokError("expected identifier in directive");
2099 // Handle the identifier as the key symbol.
2100 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2102 if (getLexer().isNot(AsmToken::Comma))
2103 return TokError("unexpected token in directive");
2107 SMLoc SizeLoc = getLexer().getLoc();
2108 if (ParseAbsoluteExpression(Size))
2111 int64_t Pow2Alignment = 0;
2112 SMLoc Pow2AlignmentLoc;
2113 if (getLexer().is(AsmToken::Comma)) {
2115 Pow2AlignmentLoc = getLexer().getLoc();
2116 if (ParseAbsoluteExpression(Pow2Alignment))
2119 // If this target takes alignments in bytes (not log) validate and convert.
2120 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2121 if (!isPowerOf2_64(Pow2Alignment))
2122 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2123 Pow2Alignment = Log2_64(Pow2Alignment);
2127 if (getLexer().isNot(AsmToken::EndOfStatement))
2128 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2132 // NOTE: a size of zero for a .comm should create a undefined symbol
2133 // but a size of .lcomm creates a bss symbol of size zero.
2135 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2136 "be less than zero");
2138 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2139 // may internally end up wanting an alignment in bytes.
2140 // FIXME: Diagnose overflow.
2141 if (Pow2Alignment < 0)
2142 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2143 "alignment, can't be less than zero");
2145 if (!Sym->isUndefined())
2146 return Error(IDLoc, "invalid symbol redefinition");
2148 // '.lcomm' is equivalent to '.zerofill'.
2149 // Create the Symbol as a common or local common with Size and Pow2Alignment
2151 getStreamer().EmitZerofill(Ctx.getMachOSection(
2152 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2153 0, SectionKind::getBSS()),
2154 Sym, Size, 1 << Pow2Alignment);
2158 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2162 /// ParseDirectiveAbort
2163 /// ::= .abort [... message ...]
2164 bool AsmParser::ParseDirectiveAbort() {
2165 // FIXME: Use loc from directive.
2166 SMLoc Loc = getLexer().getLoc();
2168 StringRef Str = ParseStringToEndOfStatement();
2169 if (getLexer().isNot(AsmToken::EndOfStatement))
2170 return TokError("unexpected token in '.abort' directive");
2175 Error(Loc, ".abort detected. Assembly stopping.");
2177 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2178 // FIXME: Actually abort assembly here.
2183 /// ParseDirectiveInclude
2184 /// ::= .include "filename"
2185 bool AsmParser::ParseDirectiveInclude() {
2186 if (getLexer().isNot(AsmToken::String))
2187 return TokError("expected string in '.include' directive");
2189 std::string Filename = getTok().getString();
2190 SMLoc IncludeLoc = getLexer().getLoc();
2193 if (getLexer().isNot(AsmToken::EndOfStatement))
2194 return TokError("unexpected token in '.include' directive");
2196 // Strip the quotes.
2197 Filename = Filename.substr(1, Filename.size()-2);
2199 // Attempt to switch the lexer to the included file before consuming the end
2200 // of statement to avoid losing it when we switch.
2201 if (EnterIncludeFile(Filename)) {
2202 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2209 /// ParseDirectiveIf
2210 /// ::= .if expression
2211 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2212 TheCondStack.push_back(TheCondState);
2213 TheCondState.TheCond = AsmCond::IfCond;
2214 if(TheCondState.Ignore) {
2215 EatToEndOfStatement();
2219 if (ParseAbsoluteExpression(ExprValue))
2222 if (getLexer().isNot(AsmToken::EndOfStatement))
2223 return TokError("unexpected token in '.if' directive");
2227 TheCondState.CondMet = ExprValue;
2228 TheCondState.Ignore = !TheCondState.CondMet;
2234 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2236 TheCondStack.push_back(TheCondState);
2237 TheCondState.TheCond = AsmCond::IfCond;
2239 if (TheCondState.Ignore) {
2240 EatToEndOfStatement();
2242 if (ParseIdentifier(Name))
2243 return TokError("expected identifier after '.ifdef'");
2247 MCSymbol *Sym = getContext().LookupSymbol(Name);
2250 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2252 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2253 TheCondState.Ignore = !TheCondState.CondMet;
2259 /// ParseDirectiveElseIf
2260 /// ::= .elseif expression
2261 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2262 if (TheCondState.TheCond != AsmCond::IfCond &&
2263 TheCondState.TheCond != AsmCond::ElseIfCond)
2264 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2266 TheCondState.TheCond = AsmCond::ElseIfCond;
2268 bool LastIgnoreState = false;
2269 if (!TheCondStack.empty())
2270 LastIgnoreState = TheCondStack.back().Ignore;
2271 if (LastIgnoreState || TheCondState.CondMet) {
2272 TheCondState.Ignore = true;
2273 EatToEndOfStatement();
2277 if (ParseAbsoluteExpression(ExprValue))
2280 if (getLexer().isNot(AsmToken::EndOfStatement))
2281 return TokError("unexpected token in '.elseif' directive");
2284 TheCondState.CondMet = ExprValue;
2285 TheCondState.Ignore = !TheCondState.CondMet;
2291 /// ParseDirectiveElse
2293 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2294 if (getLexer().isNot(AsmToken::EndOfStatement))
2295 return TokError("unexpected token in '.else' directive");
2299 if (TheCondState.TheCond != AsmCond::IfCond &&
2300 TheCondState.TheCond != AsmCond::ElseIfCond)
2301 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2303 TheCondState.TheCond = AsmCond::ElseCond;
2304 bool LastIgnoreState = false;
2305 if (!TheCondStack.empty())
2306 LastIgnoreState = TheCondStack.back().Ignore;
2307 if (LastIgnoreState || TheCondState.CondMet)
2308 TheCondState.Ignore = true;
2310 TheCondState.Ignore = false;
2315 /// ParseDirectiveEndIf
2317 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2318 if (getLexer().isNot(AsmToken::EndOfStatement))
2319 return TokError("unexpected token in '.endif' directive");
2323 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2324 TheCondStack.empty())
2325 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2327 if (!TheCondStack.empty()) {
2328 TheCondState = TheCondStack.back();
2329 TheCondStack.pop_back();
2335 /// ParseDirectiveFile
2336 /// ::= .file [number] filename
2337 /// ::= .file number directory filename
2338 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2339 // FIXME: I'm not sure what this is.
2340 int64_t FileNumber = -1;
2341 SMLoc FileNumberLoc = getLexer().getLoc();
2342 if (getLexer().is(AsmToken::Integer)) {
2343 FileNumber = getTok().getIntVal();
2347 return TokError("file number less than one");
2350 if (getLexer().isNot(AsmToken::String))
2351 return TokError("unexpected token in '.file' directive");
2353 // Usually the directory and filename together, otherwise just the directory.
2354 StringRef Path = getTok().getString();
2355 Path = Path.substr(1, Path.size()-2);
2358 StringRef Directory;
2360 if (getLexer().is(AsmToken::String)) {
2361 if (FileNumber == -1)
2362 return TokError("explicit path specified, but no file number");
2363 Filename = getTok().getString();
2364 Filename = Filename.substr(1, Filename.size()-2);
2371 if (getLexer().isNot(AsmToken::EndOfStatement))
2372 return TokError("unexpected token in '.file' directive");
2374 if (getContext().getGenDwarfForAssembly() == true)
2375 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2376 "used to generate dwarf debug info for assembly code");
2378 if (FileNumber == -1)
2379 getStreamer().EmitFileDirective(Filename);
2381 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2382 Error(FileNumberLoc, "file number already allocated");
2388 /// ParseDirectiveLine
2389 /// ::= .line [number]
2390 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2391 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2392 if (getLexer().isNot(AsmToken::Integer))
2393 return TokError("unexpected token in '.line' directive");
2395 int64_t LineNumber = getTok().getIntVal();
2399 // FIXME: Do something with the .line.
2402 if (getLexer().isNot(AsmToken::EndOfStatement))
2403 return TokError("unexpected token in '.line' directive");
2409 /// ParseDirectiveLoc
2410 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2411 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2412 /// The first number is a file number, must have been previously assigned with
2413 /// a .file directive, the second number is the line number and optionally the
2414 /// third number is a column position (zero if not specified). The remaining
2415 /// optional items are .loc sub-directives.
2416 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2418 if (getLexer().isNot(AsmToken::Integer))
2419 return TokError("unexpected token in '.loc' directive");
2420 int64_t FileNumber = getTok().getIntVal();
2422 return TokError("file number less than one in '.loc' directive");
2423 if (!getContext().isValidDwarfFileNumber(FileNumber))
2424 return TokError("unassigned file number in '.loc' directive");
2427 int64_t LineNumber = 0;
2428 if (getLexer().is(AsmToken::Integer)) {
2429 LineNumber = getTok().getIntVal();
2431 return TokError("line number less than one in '.loc' directive");
2435 int64_t ColumnPos = 0;
2436 if (getLexer().is(AsmToken::Integer)) {
2437 ColumnPos = getTok().getIntVal();
2439 return TokError("column position less than zero in '.loc' directive");
2443 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2445 int64_t Discriminator = 0;
2446 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2448 if (getLexer().is(AsmToken::EndOfStatement))
2452 SMLoc Loc = getTok().getLoc();
2453 if (getParser().ParseIdentifier(Name))
2454 return TokError("unexpected token in '.loc' directive");
2456 if (Name == "basic_block")
2457 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2458 else if (Name == "prologue_end")
2459 Flags |= DWARF2_FLAG_PROLOGUE_END;
2460 else if (Name == "epilogue_begin")
2461 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2462 else if (Name == "is_stmt") {
2463 SMLoc Loc = getTok().getLoc();
2464 const MCExpr *Value;
2465 if (getParser().ParseExpression(Value))
2467 // The expression must be the constant 0 or 1.
2468 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2469 int Value = MCE->getValue();
2471 Flags &= ~DWARF2_FLAG_IS_STMT;
2472 else if (Value == 1)
2473 Flags |= DWARF2_FLAG_IS_STMT;
2475 return Error(Loc, "is_stmt value not 0 or 1");
2478 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2481 else if (Name == "isa") {
2482 SMLoc Loc = getTok().getLoc();
2483 const MCExpr *Value;
2484 if (getParser().ParseExpression(Value))
2486 // The expression must be a constant greater or equal to 0.
2487 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2488 int Value = MCE->getValue();
2490 return Error(Loc, "isa number less than zero");
2494 return Error(Loc, "isa number not a constant value");
2497 else if (Name == "discriminator") {
2498 if (getParser().ParseAbsoluteExpression(Discriminator))
2502 return Error(Loc, "unknown sub-directive in '.loc' directive");
2505 if (getLexer().is(AsmToken::EndOfStatement))
2510 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2511 Isa, Discriminator, StringRef());
2516 /// ParseDirectiveStabs
2517 /// ::= .stabs string, number, number, number
2518 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2519 SMLoc DirectiveLoc) {
2520 return TokError("unsupported directive '" + Directive + "'");
2523 /// ParseDirectiveCFISections
2524 /// ::= .cfi_sections section [, section]
2525 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2526 SMLoc DirectiveLoc) {
2531 if (getParser().ParseIdentifier(Name))
2532 return TokError("Expected an identifier");
2534 if (Name == ".eh_frame")
2536 else if (Name == ".debug_frame")
2539 if (getLexer().is(AsmToken::Comma)) {
2542 if (getParser().ParseIdentifier(Name))
2543 return TokError("Expected an identifier");
2545 if (Name == ".eh_frame")
2547 else if (Name == ".debug_frame")
2551 getStreamer().EmitCFISections(EH, Debug);
2556 /// ParseDirectiveCFIStartProc
2557 /// ::= .cfi_startproc
2558 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2559 SMLoc DirectiveLoc) {
2560 getStreamer().EmitCFIStartProc();
2564 /// ParseDirectiveCFIEndProc
2565 /// ::= .cfi_endproc
2566 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2567 getStreamer().EmitCFIEndProc();
2571 /// ParseRegisterOrRegisterNumber - parse register name or number.
2572 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2573 SMLoc DirectiveLoc) {
2576 if (getLexer().isNot(AsmToken::Integer)) {
2577 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2580 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2582 return getParser().ParseAbsoluteExpression(Register);
2587 /// ParseDirectiveCFIDefCfa
2588 /// ::= .cfi_def_cfa register, offset
2589 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2590 SMLoc DirectiveLoc) {
2591 int64_t Register = 0;
2592 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2595 if (getLexer().isNot(AsmToken::Comma))
2596 return TokError("unexpected token in directive");
2600 if (getParser().ParseAbsoluteExpression(Offset))
2603 getStreamer().EmitCFIDefCfa(Register, Offset);
2607 /// ParseDirectiveCFIDefCfaOffset
2608 /// ::= .cfi_def_cfa_offset offset
2609 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2610 SMLoc DirectiveLoc) {
2612 if (getParser().ParseAbsoluteExpression(Offset))
2615 getStreamer().EmitCFIDefCfaOffset(Offset);
2619 /// ParseDirectiveCFIAdjustCfaOffset
2620 /// ::= .cfi_adjust_cfa_offset adjustment
2621 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2622 SMLoc DirectiveLoc) {
2623 int64_t Adjustment = 0;
2624 if (getParser().ParseAbsoluteExpression(Adjustment))
2627 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2631 /// ParseDirectiveCFIDefCfaRegister
2632 /// ::= .cfi_def_cfa_register register
2633 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2634 SMLoc DirectiveLoc) {
2635 int64_t Register = 0;
2636 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2639 getStreamer().EmitCFIDefCfaRegister(Register);
2643 /// ParseDirectiveCFIOffset
2644 /// ::= .cfi_offset register, offset
2645 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2646 int64_t Register = 0;
2649 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2652 if (getLexer().isNot(AsmToken::Comma))
2653 return TokError("unexpected token in directive");
2656 if (getParser().ParseAbsoluteExpression(Offset))
2659 getStreamer().EmitCFIOffset(Register, Offset);
2663 /// ParseDirectiveCFIRelOffset
2664 /// ::= .cfi_rel_offset register, offset
2665 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2666 SMLoc DirectiveLoc) {
2667 int64_t Register = 0;
2669 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2672 if (getLexer().isNot(AsmToken::Comma))
2673 return TokError("unexpected token in directive");
2677 if (getParser().ParseAbsoluteExpression(Offset))
2680 getStreamer().EmitCFIRelOffset(Register, Offset);
2684 static bool isValidEncoding(int64_t Encoding) {
2685 if (Encoding & ~0xff)
2688 if (Encoding == dwarf::DW_EH_PE_omit)
2691 const unsigned Format = Encoding & 0xf;
2692 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2693 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2694 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2695 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2698 const unsigned Application = Encoding & 0x70;
2699 if (Application != dwarf::DW_EH_PE_absptr &&
2700 Application != dwarf::DW_EH_PE_pcrel)
2706 /// ParseDirectiveCFIPersonalityOrLsda
2707 /// ::= .cfi_personality encoding, [symbol_name]
2708 /// ::= .cfi_lsda encoding, [symbol_name]
2709 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2710 SMLoc DirectiveLoc) {
2711 int64_t Encoding = 0;
2712 if (getParser().ParseAbsoluteExpression(Encoding))
2714 if (Encoding == dwarf::DW_EH_PE_omit)
2717 if (!isValidEncoding(Encoding))
2718 return TokError("unsupported encoding.");
2720 if (getLexer().isNot(AsmToken::Comma))
2721 return TokError("unexpected token in directive");
2725 if (getParser().ParseIdentifier(Name))
2726 return TokError("expected identifier in directive");
2728 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2730 if (IDVal == ".cfi_personality")
2731 getStreamer().EmitCFIPersonality(Sym, Encoding);
2733 assert(IDVal == ".cfi_lsda");
2734 getStreamer().EmitCFILsda(Sym, Encoding);
2739 /// ParseDirectiveCFIRememberState
2740 /// ::= .cfi_remember_state
2741 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2742 SMLoc DirectiveLoc) {
2743 getStreamer().EmitCFIRememberState();
2747 /// ParseDirectiveCFIRestoreState
2748 /// ::= .cfi_remember_state
2749 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2750 SMLoc DirectiveLoc) {
2751 getStreamer().EmitCFIRestoreState();
2755 /// ParseDirectiveCFISameValue
2756 /// ::= .cfi_same_value register
2757 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2758 SMLoc DirectiveLoc) {
2759 int64_t Register = 0;
2761 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2764 getStreamer().EmitCFISameValue(Register);
2769 /// ParseDirectiveMacrosOnOff
2772 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2773 SMLoc DirectiveLoc) {
2774 if (getLexer().isNot(AsmToken::EndOfStatement))
2775 return Error(getLexer().getLoc(),
2776 "unexpected token in '" + Directive + "' directive");
2778 getParser().MacrosEnabled = Directive == ".macros_on";
2783 /// ParseDirectiveMacro
2784 /// ::= .macro name [parameters]
2785 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2786 SMLoc DirectiveLoc) {
2788 if (getParser().ParseIdentifier(Name))
2789 return TokError("expected identifier in directive");
2791 std::vector<StringRef> Parameters;
2792 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2794 StringRef Parameter;
2795 if (getParser().ParseIdentifier(Parameter))
2796 return TokError("expected identifier in directive");
2797 Parameters.push_back(Parameter);
2799 if (getLexer().isNot(AsmToken::Comma))
2805 if (getLexer().isNot(AsmToken::EndOfStatement))
2806 return TokError("unexpected token in '.macro' directive");
2808 // Eat the end of statement.
2811 AsmToken EndToken, StartToken = getTok();
2813 // Lex the macro definition.
2815 // Check whether we have reached the end of the file.
2816 if (getLexer().is(AsmToken::Eof))
2817 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2819 // Otherwise, check whether we have reach the .endmacro.
2820 if (getLexer().is(AsmToken::Identifier) &&
2821 (getTok().getIdentifier() == ".endm" ||
2822 getTok().getIdentifier() == ".endmacro")) {
2823 EndToken = getTok();
2825 if (getLexer().isNot(AsmToken::EndOfStatement))
2826 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2831 // Otherwise, scan til the end of the statement.
2832 getParser().EatToEndOfStatement();
2835 if (getParser().MacroMap.lookup(Name)) {
2836 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2839 const char *BodyStart = StartToken.getLoc().getPointer();
2840 const char *BodyEnd = EndToken.getLoc().getPointer();
2841 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2842 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2846 /// ParseDirectiveEndMacro
2849 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2850 SMLoc DirectiveLoc) {
2851 if (getLexer().isNot(AsmToken::EndOfStatement))
2852 return TokError("unexpected token in '" + Directive + "' directive");
2854 // If we are inside a macro instantiation, terminate the current
2856 if (!getParser().ActiveMacros.empty()) {
2857 getParser().HandleMacroExit();
2861 // Otherwise, this .endmacro is a stray entry in the file; well formed
2862 // .endmacro directives are handled during the macro definition parsing.
2863 return TokError("unexpected '" + Directive + "' in file, "
2864 "no current macro definition");
2867 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2868 getParser().CheckForValidSection();
2870 const MCExpr *Value;
2872 if (getParser().ParseExpression(Value))
2875 if (getLexer().isNot(AsmToken::EndOfStatement))
2876 return TokError("unexpected token in directive");
2878 if (DirName[1] == 's')
2879 getStreamer().EmitSLEB128Value(Value);
2881 getStreamer().EmitULEB128Value(Value);
2887 /// \brief Create an MCAsmParser instance.
2888 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2889 MCContext &C, MCStreamer &Out,
2890 const MCAsmInfo &MAI) {
2891 return new AsmParser(SM, C, Out, MAI);