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/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
39 /// \brief Helper class for tracking macro definitions.
45 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 /// \brief The concrete assembly parser instance.
49 class AsmParser : public MCAsmParser {
50 friend class GenericAsmParser;
52 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
53 void operator=(const AsmParser &); // DO NOT IMPLEMENT
59 MCAsmParserExtension *GenericParser;
60 MCAsmParserExtension *PlatformParser;
62 /// This is the current buffer index we're lexing from as managed by the
67 std::vector<AsmCond> TheCondStack;
69 /// DirectiveMap - This is a table handlers for directives. Each handler is
70 /// invoked after the directive identifier is read and is responsible for
71 /// parsing and validating the rest of the directive. The handler is passed
72 /// in the directive name and the location of the directive keyword.
73 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
75 /// MacroMap - Map of currently defined macros.
76 StringMap<Macro*> MacroMap;
78 /// Boolean tracking whether macro substitution is enabled.
79 unsigned MacrosEnabled : 1;
82 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
83 const MCAsmInfo &MAI);
86 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
88 void AddDirectiveHandler(MCAsmParserExtension *Object,
90 DirectiveHandler Handler) {
91 DirectiveMap[Directive] = std::make_pair(Object, Handler);
95 /// @name MCAsmParser Interface
98 virtual SourceMgr &getSourceManager() { return SrcMgr; }
99 virtual MCAsmLexer &getLexer() { return Lexer; }
100 virtual MCContext &getContext() { return Ctx; }
101 virtual MCStreamer &getStreamer() { return Out; }
103 virtual void Warning(SMLoc L, const Twine &Meg);
104 virtual bool Error(SMLoc L, const Twine &Msg);
106 const AsmToken &Lex();
108 bool ParseExpression(const MCExpr *&Res);
109 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
110 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
111 virtual bool ParseAbsoluteExpression(int64_t &Res);
116 bool ParseStatement();
118 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
120 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
121 bool EnterIncludeFile(const std::string &Filename);
123 void EatToEndOfStatement();
125 bool ParseAssignment(StringRef Name);
127 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
128 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
129 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
131 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
132 /// and set \arg Res to the identifier contents.
133 bool ParseIdentifier(StringRef &Res);
135 // Directive Parsing.
136 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
137 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
138 bool ParseDirectiveFill(); // ".fill"
139 bool ParseDirectiveSpace(); // ".space"
140 bool ParseDirectiveSet(); // ".set"
141 bool ParseDirectiveOrg(); // ".org"
142 // ".align{,32}", ".p2align{,w,l}"
143 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
145 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
146 /// accepts a single symbol (which should be a label or an external).
147 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
148 bool ParseDirectiveELFType(); // ELF specific ".type"
150 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
152 bool ParseDirectiveAbort(); // ".abort"
153 bool ParseDirectiveInclude(); // ".include"
155 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
156 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
157 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
158 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
160 /// ParseEscapedString - Parse the current token as a string which may include
161 /// escaped characters and return the string contents.
162 bool ParseEscapedString(std::string &Data);
165 /// \brief Generic implementations of directive handling, etc. which is shared
166 /// (or the default, at least) for all assembler parser.
167 class GenericAsmParser : public MCAsmParserExtension {
169 GenericAsmParser() {}
171 AsmParser &getParser() {
172 return (AsmParser&) this->MCAsmParserExtension::getParser();
175 virtual void Initialize(MCAsmParser &Parser) {
176 // Call the base implementation.
177 this->MCAsmParserExtension::Initialize(Parser);
179 // Debugging directives.
180 Parser.AddDirectiveHandler(this, ".file", MCAsmParser::DirectiveHandler(
181 &GenericAsmParser::ParseDirectiveFile));
182 Parser.AddDirectiveHandler(this, ".line", MCAsmParser::DirectiveHandler(
183 &GenericAsmParser::ParseDirectiveLine));
184 Parser.AddDirectiveHandler(this, ".loc", MCAsmParser::DirectiveHandler(
185 &GenericAsmParser::ParseDirectiveLoc));
188 Parser.AddDirectiveHandler(this, ".macros_on",
189 MCAsmParser::DirectiveHandler(
190 &GenericAsmParser::ParseDirectiveMacrosOnOff));
191 Parser.AddDirectiveHandler(this, ".macros_off",
192 MCAsmParser::DirectiveHandler(
193 &GenericAsmParser::ParseDirectiveMacrosOnOff));
194 Parser.AddDirectiveHandler(this, ".macro", MCAsmParser::DirectiveHandler(
195 &GenericAsmParser::ParseDirectiveMacro));
196 Parser.AddDirectiveHandler(this, ".endm", MCAsmParser::DirectiveHandler(
197 &GenericAsmParser::ParseDirectiveEndMacro));
198 Parser.AddDirectiveHandler(this, ".endmacro", MCAsmParser::DirectiveHandler(
199 &GenericAsmParser::ParseDirectiveEndMacro));
202 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
203 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
204 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
206 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
207 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
208 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
215 extern MCAsmParserExtension *createDarwinAsmParser();
216 extern MCAsmParserExtension *createELFAsmParser();
220 enum { DEFAULT_ADDRSPACE = 0 };
222 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
223 MCStreamer &_Out, const MCAsmInfo &_MAI)
224 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
225 GenericParser(new GenericAsmParser), PlatformParser(0),
226 CurBuffer(0), MacrosEnabled(true) {
227 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
229 // Initialize the generic parser.
230 GenericParser->Initialize(*this);
232 // Initialize the platform / file format parser.
234 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
236 if (_MAI.hasSubsectionsViaSymbols()) {
237 PlatformParser = createDarwinAsmParser();
238 PlatformParser->Initialize(*this);
240 PlatformParser = createELFAsmParser();
241 PlatformParser->Initialize(*this);
245 AsmParser::~AsmParser() {
246 delete PlatformParser;
247 delete GenericParser;
250 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
251 PrintMessage(L, Msg.str(), "warning");
254 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
255 PrintMessage(L, Msg.str(), "error");
259 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
260 const char *Type) const {
261 SrcMgr.PrintMessage(Loc, Msg, Type);
264 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
265 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
271 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
276 const AsmToken &AsmParser::Lex() {
277 const AsmToken *tok = &Lexer.Lex();
279 if (tok->is(AsmToken::Eof)) {
280 // If this is the end of an included file, pop the parent file off the
282 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
283 if (ParentIncludeLoc != SMLoc()) {
284 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
285 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
286 ParentIncludeLoc.getPointer());
291 if (tok->is(AsmToken::Error))
292 Error(Lexer.getErrLoc(), Lexer.getErr());
297 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
298 // Create the initial section, if requested.
300 // FIXME: Target hook & command line option for initial section.
301 if (!NoInitialTextSection)
302 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
303 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
304 0, SectionKind::getText()));
309 bool HadError = false;
311 AsmCond StartingCondState = TheCondState;
313 // While we have input, parse each statement.
314 while (Lexer.isNot(AsmToken::Eof)) {
315 if (!ParseStatement()) continue;
317 // We had an error, remember it and recover by skipping to the next line.
319 EatToEndOfStatement();
322 if (TheCondState.TheCond != StartingCondState.TheCond ||
323 TheCondState.Ignore != StartingCondState.Ignore)
324 return TokError("unmatched .ifs or .elses");
326 // Finalize the output stream if there are no errors and if the client wants
328 if (!HadError && !NoFinalize)
334 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
335 void AsmParser::EatToEndOfStatement() {
336 while (Lexer.isNot(AsmToken::EndOfStatement) &&
337 Lexer.isNot(AsmToken::Eof))
341 if (Lexer.is(AsmToken::EndOfStatement))
346 /// ParseParenExpr - Parse a paren expression and return it.
347 /// NOTE: This assumes the leading '(' has already been consumed.
349 /// parenexpr ::= expr)
351 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
352 if (ParseExpression(Res)) return true;
353 if (Lexer.isNot(AsmToken::RParen))
354 return TokError("expected ')' in parentheses expression");
355 EndLoc = Lexer.getLoc();
360 /// ParsePrimaryExpr - Parse a primary expression and return it.
361 /// primaryexpr ::= (parenexpr
362 /// primaryexpr ::= symbol
363 /// primaryexpr ::= number
364 /// primaryexpr ::= '.'
365 /// primaryexpr ::= ~,+,- primaryexpr
366 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
367 switch (Lexer.getKind()) {
369 return TokError("unknown token in expression");
370 case AsmToken::Exclaim:
371 Lex(); // Eat the operator.
372 if (ParsePrimaryExpr(Res, EndLoc))
374 Res = MCUnaryExpr::CreateLNot(Res, getContext());
376 case AsmToken::String:
377 case AsmToken::Identifier: {
378 // This is a symbol reference.
379 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
380 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
382 // Mark the symbol as used in an expression.
383 Sym->setUsedInExpr(true);
385 // Lookup the symbol variant if used.
386 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
387 if (Split.first.size() != getTok().getIdentifier().size())
388 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
390 EndLoc = Lexer.getLoc();
391 Lex(); // Eat identifier.
393 // If this is an absolute variable reference, substitute it now to preserve
394 // semantics in the face of reassignment.
395 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
397 return Error(EndLoc, "unexpected modified on variable reference");
399 Res = Sym->getVariableValue();
403 // Otherwise create a symbol ref.
404 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
407 case AsmToken::Integer: {
408 SMLoc Loc = getTok().getLoc();
409 int64_t IntVal = getTok().getIntVal();
410 Res = MCConstantExpr::Create(IntVal, getContext());
411 EndLoc = Lexer.getLoc();
413 // Look for 'b' or 'f' following an Integer as a directional label
414 if (Lexer.getKind() == AsmToken::Identifier) {
415 StringRef IDVal = getTok().getString();
416 if (IDVal == "f" || IDVal == "b"){
417 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
418 IDVal == "f" ? 1 : 0);
419 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
421 if(IDVal == "b" && Sym->isUndefined())
422 return Error(Loc, "invalid reference to undefined symbol");
423 EndLoc = Lexer.getLoc();
424 Lex(); // Eat identifier.
429 case AsmToken::Dot: {
430 // This is a '.' reference, which references the current PC. Emit a
431 // temporary label to the streamer and refer to it.
432 MCSymbol *Sym = Ctx.CreateTempSymbol();
434 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
435 EndLoc = Lexer.getLoc();
436 Lex(); // Eat identifier.
440 case AsmToken::LParen:
441 Lex(); // Eat the '('.
442 return ParseParenExpr(Res, EndLoc);
443 case AsmToken::Minus:
444 Lex(); // Eat the operator.
445 if (ParsePrimaryExpr(Res, EndLoc))
447 Res = MCUnaryExpr::CreateMinus(Res, getContext());
450 Lex(); // Eat the operator.
451 if (ParsePrimaryExpr(Res, EndLoc))
453 Res = MCUnaryExpr::CreatePlus(Res, getContext());
455 case AsmToken::Tilde:
456 Lex(); // Eat the operator.
457 if (ParsePrimaryExpr(Res, EndLoc))
459 Res = MCUnaryExpr::CreateNot(Res, getContext());
464 bool AsmParser::ParseExpression(const MCExpr *&Res) {
466 return ParseExpression(Res, EndLoc);
469 /// ParseExpression - Parse an expression and return it.
471 /// expr ::= expr +,- expr -> lowest.
472 /// expr ::= expr |,^,&,! expr -> middle.
473 /// expr ::= expr *,/,%,<<,>> expr -> highest.
474 /// expr ::= primaryexpr
476 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
477 // Parse the expression.
479 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
482 // Try to constant fold it up front, if possible.
484 if (Res->EvaluateAsAbsolute(Value))
485 Res = MCConstantExpr::Create(Value, getContext());
490 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
492 return ParseParenExpr(Res, EndLoc) ||
493 ParseBinOpRHS(1, Res, EndLoc);
496 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
499 SMLoc StartLoc = Lexer.getLoc();
500 if (ParseExpression(Expr))
503 if (!Expr->EvaluateAsAbsolute(Res))
504 return Error(StartLoc, "expected absolute expression");
509 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
510 MCBinaryExpr::Opcode &Kind) {
513 return 0; // not a binop.
515 // Lowest Precedence: &&, ||
516 case AsmToken::AmpAmp:
517 Kind = MCBinaryExpr::LAnd;
519 case AsmToken::PipePipe:
520 Kind = MCBinaryExpr::LOr;
523 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
525 Kind = MCBinaryExpr::Add;
527 case AsmToken::Minus:
528 Kind = MCBinaryExpr::Sub;
530 case AsmToken::EqualEqual:
531 Kind = MCBinaryExpr::EQ;
533 case AsmToken::ExclaimEqual:
534 case AsmToken::LessGreater:
535 Kind = MCBinaryExpr::NE;
538 Kind = MCBinaryExpr::LT;
540 case AsmToken::LessEqual:
541 Kind = MCBinaryExpr::LTE;
543 case AsmToken::Greater:
544 Kind = MCBinaryExpr::GT;
546 case AsmToken::GreaterEqual:
547 Kind = MCBinaryExpr::GTE;
550 // Intermediate Precedence: |, &, ^
552 // FIXME: gas seems to support '!' as an infix operator?
554 Kind = MCBinaryExpr::Or;
556 case AsmToken::Caret:
557 Kind = MCBinaryExpr::Xor;
560 Kind = MCBinaryExpr::And;
563 // Highest Precedence: *, /, %, <<, >>
565 Kind = MCBinaryExpr::Mul;
567 case AsmToken::Slash:
568 Kind = MCBinaryExpr::Div;
570 case AsmToken::Percent:
571 Kind = MCBinaryExpr::Mod;
573 case AsmToken::LessLess:
574 Kind = MCBinaryExpr::Shl;
576 case AsmToken::GreaterGreater:
577 Kind = MCBinaryExpr::Shr;
583 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
584 /// Res contains the LHS of the expression on input.
585 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
588 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
589 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
591 // If the next token is lower precedence than we are allowed to eat, return
592 // successfully with what we ate already.
593 if (TokPrec < Precedence)
598 // Eat the next primary expression.
600 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
602 // If BinOp binds less tightly with RHS than the operator after RHS, let
603 // the pending operator take RHS as its LHS.
604 MCBinaryExpr::Opcode Dummy;
605 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
606 if (TokPrec < NextTokPrec) {
607 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
610 // Merge LHS and RHS according to operator.
611 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
619 /// ::= EndOfStatement
620 /// ::= Label* Directive ...Operands... EndOfStatement
621 /// ::= Label* Identifier OperandList* EndOfStatement
622 bool AsmParser::ParseStatement() {
623 if (Lexer.is(AsmToken::EndOfStatement)) {
629 // Statements always start with an identifier.
630 AsmToken ID = getTok();
631 SMLoc IDLoc = ID.getLoc();
633 int64_t LocalLabelVal = -1;
634 // GUESS allow an integer followed by a ':' as a directional local label
635 if (Lexer.is(AsmToken::Integer)) {
636 LocalLabelVal = getTok().getIntVal();
637 if (LocalLabelVal < 0) {
638 if (!TheCondState.Ignore)
639 return TokError("unexpected token at start of statement");
643 IDVal = getTok().getString();
644 Lex(); // Consume the integer token to be used as an identifier token.
645 if (Lexer.getKind() != AsmToken::Colon) {
646 if (!TheCondState.Ignore)
647 return TokError("unexpected token at start of statement");
651 else if (ParseIdentifier(IDVal)) {
652 if (!TheCondState.Ignore)
653 return TokError("unexpected token at start of statement");
657 // Handle conditional assembly here before checking for skipping. We
658 // have to do this so that .endif isn't skipped in a ".if 0" block for
661 return ParseDirectiveIf(IDLoc);
662 if (IDVal == ".elseif")
663 return ParseDirectiveElseIf(IDLoc);
664 if (IDVal == ".else")
665 return ParseDirectiveElse(IDLoc);
666 if (IDVal == ".endif")
667 return ParseDirectiveEndIf(IDLoc);
669 // If we are in a ".if 0" block, ignore this statement.
670 if (TheCondState.Ignore) {
671 EatToEndOfStatement();
675 // FIXME: Recurse on local labels?
677 // See what kind of statement we have.
678 switch (Lexer.getKind()) {
679 case AsmToken::Colon: {
680 // identifier ':' -> Label.
683 // Diagnose attempt to use a variable as a label.
685 // FIXME: Diagnostics. Note the location of the definition as a label.
686 // FIXME: This doesn't diagnose assignment to a symbol which has been
687 // implicitly marked as external.
689 if (LocalLabelVal == -1)
690 Sym = getContext().GetOrCreateSymbol(IDVal);
692 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
693 if (!Sym->isUndefined() || Sym->isVariable())
694 return Error(IDLoc, "invalid symbol redefinition");
699 // Consume any end of statement token, if present, to avoid spurious
700 // AddBlankLine calls().
701 if (Lexer.is(AsmToken::EndOfStatement)) {
703 if (Lexer.is(AsmToken::Eof))
707 return ParseStatement();
710 case AsmToken::Equal:
711 // identifier '=' ... -> assignment statement
714 return ParseAssignment(IDVal);
716 default: // Normal instruction or directive.
720 // Otherwise, we have a normal instruction or directive.
721 if (IDVal[0] == '.') {
722 // Assembler features
724 return ParseDirectiveSet();
728 if (IDVal == ".ascii")
729 return ParseDirectiveAscii(false);
730 if (IDVal == ".asciz")
731 return ParseDirectiveAscii(true);
733 if (IDVal == ".byte")
734 return ParseDirectiveValue(1);
735 if (IDVal == ".short")
736 return ParseDirectiveValue(2);
737 if (IDVal == ".long")
738 return ParseDirectiveValue(4);
739 if (IDVal == ".quad")
740 return ParseDirectiveValue(8);
742 // FIXME: Target hooks for IsPow2.
743 if (IDVal == ".align")
744 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
745 if (IDVal == ".align32")
746 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
747 if (IDVal == ".balign")
748 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
749 if (IDVal == ".balignw")
750 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
751 if (IDVal == ".balignl")
752 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
753 if (IDVal == ".p2align")
754 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
755 if (IDVal == ".p2alignw")
756 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
757 if (IDVal == ".p2alignl")
758 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
761 return ParseDirectiveOrg();
763 if (IDVal == ".fill")
764 return ParseDirectiveFill();
765 if (IDVal == ".space")
766 return ParseDirectiveSpace();
768 // Symbol attribute directives
770 if (IDVal == ".globl" || IDVal == ".global")
771 return ParseDirectiveSymbolAttribute(MCSA_Global);
772 if (IDVal == ".hidden")
773 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
774 if (IDVal == ".indirect_symbol")
775 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
776 if (IDVal == ".internal")
777 return ParseDirectiveSymbolAttribute(MCSA_Internal);
778 if (IDVal == ".lazy_reference")
779 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
780 if (IDVal == ".no_dead_strip")
781 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
782 if (IDVal == ".private_extern")
783 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
784 if (IDVal == ".protected")
785 return ParseDirectiveSymbolAttribute(MCSA_Protected);
786 if (IDVal == ".reference")
787 return ParseDirectiveSymbolAttribute(MCSA_Reference);
788 if (IDVal == ".type")
789 return ParseDirectiveELFType();
790 if (IDVal == ".weak")
791 return ParseDirectiveSymbolAttribute(MCSA_Weak);
792 if (IDVal == ".weak_definition")
793 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
794 if (IDVal == ".weak_reference")
795 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
796 if (IDVal == ".weak_def_can_be_hidden")
797 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
799 if (IDVal == ".comm")
800 return ParseDirectiveComm(/*IsLocal=*/false);
801 if (IDVal == ".lcomm")
802 return ParseDirectiveComm(/*IsLocal=*/true);
804 if (IDVal == ".abort")
805 return ParseDirectiveAbort();
806 if (IDVal == ".include")
807 return ParseDirectiveInclude();
809 // If macros are enabled, check to see if this is a macro instantiation.
811 if (const Macro *M = MacroMap.lookup(IDVal)) {
814 Error(IDLoc, "macros are not yet supported");
815 EatToEndOfStatement();
820 // Look up the handler in the handler table.
821 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
822 DirectiveMap.lookup(IDVal);
824 return (Handler.first->*Handler.second)(IDVal, IDLoc);
826 // Target hook for parsing target specific directives.
827 if (!getTargetParser().ParseDirective(ID))
830 Warning(IDLoc, "ignoring directive for now");
831 EatToEndOfStatement();
835 // Canonicalize the opcode to lower case.
836 SmallString<128> Opcode;
837 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
838 Opcode.push_back(tolower(IDVal[i]));
840 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
841 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
843 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
844 HadError = TokError("unexpected token in argument list");
846 // If parsing succeeded, match the instruction.
849 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
850 // Emit the instruction on success.
851 Out.EmitInstruction(Inst);
853 // Otherwise emit a diagnostic about the match failure and set the error
856 // FIXME: We should give nicer diagnostics about the exact failure.
857 Error(IDLoc, "unrecognized instruction");
862 // If there was no error, consume the end-of-statement token. Otherwise this
863 // will be done by our caller.
867 // Free any parsed operands.
868 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
869 delete ParsedOperands[i];
874 bool AsmParser::ParseAssignment(StringRef Name) {
875 // FIXME: Use better location, we should use proper tokens.
876 SMLoc EqualLoc = Lexer.getLoc();
879 if (ParseExpression(Value))
882 if (Lexer.isNot(AsmToken::EndOfStatement))
883 return TokError("unexpected token in assignment");
885 // Eat the end of statement marker.
888 // Validate that the LHS is allowed to be a variable (either it has not been
889 // used as a symbol, or it is an absolute symbol).
890 MCSymbol *Sym = getContext().LookupSymbol(Name);
892 // Diagnose assignment to a label.
894 // FIXME: Diagnostics. Note the location of the definition as a label.
895 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
896 if (Sym->isUndefined() && !Sym->isUsedInExpr())
897 ; // Allow redefinitions of undefined symbols only used in directives.
898 else if (!Sym->isUndefined() && !Sym->isAbsolute())
899 return Error(EqualLoc, "redefinition of '" + Name + "'");
900 else if (!Sym->isVariable())
901 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
902 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
903 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
906 Sym = getContext().GetOrCreateSymbol(Name);
908 // FIXME: Handle '.'.
910 Sym->setUsedInExpr(true);
912 // Do the assignment.
913 Out.EmitAssignment(Sym, Value);
921 bool AsmParser::ParseIdentifier(StringRef &Res) {
922 if (Lexer.isNot(AsmToken::Identifier) &&
923 Lexer.isNot(AsmToken::String))
926 Res = getTok().getIdentifier();
928 Lex(); // Consume the identifier token.
933 /// ParseDirectiveSet:
934 /// ::= .set identifier ',' expression
935 bool AsmParser::ParseDirectiveSet() {
938 if (ParseIdentifier(Name))
939 return TokError("expected identifier after '.set' directive");
941 if (getLexer().isNot(AsmToken::Comma))
942 return TokError("unexpected token in '.set'");
945 return ParseAssignment(Name);
948 bool AsmParser::ParseEscapedString(std::string &Data) {
949 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
952 StringRef Str = getTok().getStringContents();
953 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
954 if (Str[i] != '\\') {
959 // Recognize escaped characters. Note that this escape semantics currently
960 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
963 return TokError("unexpected backslash at end of string");
965 // Recognize octal sequences.
966 if ((unsigned) (Str[i] - '0') <= 7) {
967 // Consume up to three octal characters.
968 unsigned Value = Str[i] - '0';
970 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
972 Value = Value * 8 + (Str[i] - '0');
974 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
976 Value = Value * 8 + (Str[i] - '0');
981 return TokError("invalid octal escape sequence (out of range)");
983 Data += (unsigned char) Value;
987 // Otherwise recognize individual escapes.
990 // Just reject invalid escape sequences for now.
991 return TokError("invalid escape sequence (unrecognized character)");
993 case 'b': Data += '\b'; break;
994 case 'f': Data += '\f'; break;
995 case 'n': Data += '\n'; break;
996 case 'r': Data += '\r'; break;
997 case 't': Data += '\t'; break;
998 case '"': Data += '"'; break;
999 case '\\': Data += '\\'; break;
1006 /// ParseDirectiveAscii:
1007 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1008 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1009 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1011 if (getLexer().isNot(AsmToken::String))
1012 return TokError("expected string in '.ascii' or '.asciz' directive");
1015 if (ParseEscapedString(Data))
1018 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1020 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1024 if (getLexer().is(AsmToken::EndOfStatement))
1027 if (getLexer().isNot(AsmToken::Comma))
1028 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1037 /// ParseDirectiveValue
1038 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1039 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1040 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1042 const MCExpr *Value;
1043 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1044 if (ParseExpression(Value))
1047 // Special case constant expressions to match code generator.
1048 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1049 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1051 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1053 if (getLexer().is(AsmToken::EndOfStatement))
1056 // FIXME: Improve diagnostic.
1057 if (getLexer().isNot(AsmToken::Comma))
1058 return TokError("unexpected token in directive");
1067 /// ParseDirectiveSpace
1068 /// ::= .space expression [ , expression ]
1069 bool AsmParser::ParseDirectiveSpace() {
1071 if (ParseAbsoluteExpression(NumBytes))
1074 int64_t FillExpr = 0;
1075 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1076 if (getLexer().isNot(AsmToken::Comma))
1077 return TokError("unexpected token in '.space' directive");
1080 if (ParseAbsoluteExpression(FillExpr))
1083 if (getLexer().isNot(AsmToken::EndOfStatement))
1084 return TokError("unexpected token in '.space' directive");
1090 return TokError("invalid number of bytes in '.space' directive");
1092 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1093 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1098 /// ParseDirectiveFill
1099 /// ::= .fill expression , expression , expression
1100 bool AsmParser::ParseDirectiveFill() {
1102 if (ParseAbsoluteExpression(NumValues))
1105 if (getLexer().isNot(AsmToken::Comma))
1106 return TokError("unexpected token in '.fill' directive");
1110 if (ParseAbsoluteExpression(FillSize))
1113 if (getLexer().isNot(AsmToken::Comma))
1114 return TokError("unexpected token in '.fill' directive");
1118 if (ParseAbsoluteExpression(FillExpr))
1121 if (getLexer().isNot(AsmToken::EndOfStatement))
1122 return TokError("unexpected token in '.fill' directive");
1126 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1127 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1129 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1130 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1135 /// ParseDirectiveOrg
1136 /// ::= .org expression [ , expression ]
1137 bool AsmParser::ParseDirectiveOrg() {
1138 const MCExpr *Offset;
1139 if (ParseExpression(Offset))
1142 // Parse optional fill expression.
1143 int64_t FillExpr = 0;
1144 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1145 if (getLexer().isNot(AsmToken::Comma))
1146 return TokError("unexpected token in '.org' directive");
1149 if (ParseAbsoluteExpression(FillExpr))
1152 if (getLexer().isNot(AsmToken::EndOfStatement))
1153 return TokError("unexpected token in '.org' directive");
1158 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1159 // has to be relative to the current section.
1160 getStreamer().EmitValueToOffset(Offset, FillExpr);
1165 /// ParseDirectiveAlign
1166 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1167 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1168 SMLoc AlignmentLoc = getLexer().getLoc();
1170 if (ParseAbsoluteExpression(Alignment))
1174 bool HasFillExpr = false;
1175 int64_t FillExpr = 0;
1176 int64_t MaxBytesToFill = 0;
1177 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1178 if (getLexer().isNot(AsmToken::Comma))
1179 return TokError("unexpected token in directive");
1182 // The fill expression can be omitted while specifying a maximum number of
1183 // alignment bytes, e.g:
1185 if (getLexer().isNot(AsmToken::Comma)) {
1187 if (ParseAbsoluteExpression(FillExpr))
1191 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1192 if (getLexer().isNot(AsmToken::Comma))
1193 return TokError("unexpected token in directive");
1196 MaxBytesLoc = getLexer().getLoc();
1197 if (ParseAbsoluteExpression(MaxBytesToFill))
1200 if (getLexer().isNot(AsmToken::EndOfStatement))
1201 return TokError("unexpected token in directive");
1210 // Compute alignment in bytes.
1212 // FIXME: Diagnose overflow.
1213 if (Alignment >= 32) {
1214 Error(AlignmentLoc, "invalid alignment value");
1218 Alignment = 1ULL << Alignment;
1221 // Diagnose non-sensical max bytes to align.
1222 if (MaxBytesLoc.isValid()) {
1223 if (MaxBytesToFill < 1) {
1224 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1225 "many bytes, ignoring maximum bytes expression");
1229 if (MaxBytesToFill >= Alignment) {
1230 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1236 // Check whether we should use optimal code alignment for this .align
1239 // FIXME: This should be using a target hook.
1240 bool UseCodeAlign = false;
1241 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1242 getStreamer().getCurrentSection()))
1243 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1244 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1245 ValueSize == 1 && UseCodeAlign) {
1246 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1248 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1249 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1256 /// ParseDirectiveSymbolAttribute
1257 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1258 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1259 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1263 if (ParseIdentifier(Name))
1264 return TokError("expected identifier in directive");
1266 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1268 getStreamer().EmitSymbolAttribute(Sym, Attr);
1270 if (getLexer().is(AsmToken::EndOfStatement))
1273 if (getLexer().isNot(AsmToken::Comma))
1274 return TokError("unexpected token in directive");
1283 /// ParseDirectiveELFType
1284 /// ::= .type identifier , @attribute
1285 bool AsmParser::ParseDirectiveELFType() {
1287 if (ParseIdentifier(Name))
1288 return TokError("expected identifier in directive");
1290 // Handle the identifier as the key symbol.
1291 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1293 if (getLexer().isNot(AsmToken::Comma))
1294 return TokError("unexpected token in '.type' directive");
1297 if (getLexer().isNot(AsmToken::At))
1298 return TokError("expected '@' before type");
1304 TypeLoc = getLexer().getLoc();
1305 if (ParseIdentifier(Type))
1306 return TokError("expected symbol type in directive");
1308 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1309 .Case("function", MCSA_ELF_TypeFunction)
1310 .Case("object", MCSA_ELF_TypeObject)
1311 .Case("tls_object", MCSA_ELF_TypeTLS)
1312 .Case("common", MCSA_ELF_TypeCommon)
1313 .Case("notype", MCSA_ELF_TypeNoType)
1314 .Default(MCSA_Invalid);
1316 if (Attr == MCSA_Invalid)
1317 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1319 if (getLexer().isNot(AsmToken::EndOfStatement))
1320 return TokError("unexpected token in '.type' directive");
1324 getStreamer().EmitSymbolAttribute(Sym, Attr);
1329 /// ParseDirectiveComm
1330 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1331 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1332 SMLoc IDLoc = getLexer().getLoc();
1334 if (ParseIdentifier(Name))
1335 return TokError("expected identifier in directive");
1337 // Handle the identifier as the key symbol.
1338 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1340 if (getLexer().isNot(AsmToken::Comma))
1341 return TokError("unexpected token in directive");
1345 SMLoc SizeLoc = getLexer().getLoc();
1346 if (ParseAbsoluteExpression(Size))
1349 int64_t Pow2Alignment = 0;
1350 SMLoc Pow2AlignmentLoc;
1351 if (getLexer().is(AsmToken::Comma)) {
1353 Pow2AlignmentLoc = getLexer().getLoc();
1354 if (ParseAbsoluteExpression(Pow2Alignment))
1357 // If this target takes alignments in bytes (not log) validate and convert.
1358 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1359 if (!isPowerOf2_64(Pow2Alignment))
1360 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1361 Pow2Alignment = Log2_64(Pow2Alignment);
1365 if (getLexer().isNot(AsmToken::EndOfStatement))
1366 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1370 // NOTE: a size of zero for a .comm should create a undefined symbol
1371 // but a size of .lcomm creates a bss symbol of size zero.
1373 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1374 "be less than zero");
1376 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1377 // may internally end up wanting an alignment in bytes.
1378 // FIXME: Diagnose overflow.
1379 if (Pow2Alignment < 0)
1380 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1381 "alignment, can't be less than zero");
1383 if (!Sym->isUndefined())
1384 return Error(IDLoc, "invalid symbol redefinition");
1386 // '.lcomm' is equivalent to '.zerofill'.
1387 // Create the Symbol as a common or local common with Size and Pow2Alignment
1389 getStreamer().EmitZerofill(Ctx.getMachOSection(
1390 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1391 0, SectionKind::getBSS()),
1392 Sym, Size, 1 << Pow2Alignment);
1396 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1400 /// ParseDirectiveAbort
1401 /// ::= .abort [ "abort_string" ]
1402 bool AsmParser::ParseDirectiveAbort() {
1403 // FIXME: Use loc from directive.
1404 SMLoc Loc = getLexer().getLoc();
1407 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1408 if (getLexer().isNot(AsmToken::String))
1409 return TokError("expected string in '.abort' directive");
1411 Str = getTok().getString();
1416 if (getLexer().isNot(AsmToken::EndOfStatement))
1417 return TokError("unexpected token in '.abort' directive");
1421 // FIXME: Handle here.
1423 Error(Loc, ".abort detected. Assembly stopping.");
1425 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1430 /// ParseDirectiveInclude
1431 /// ::= .include "filename"
1432 bool AsmParser::ParseDirectiveInclude() {
1433 if (getLexer().isNot(AsmToken::String))
1434 return TokError("expected string in '.include' directive");
1436 std::string Filename = getTok().getString();
1437 SMLoc IncludeLoc = getLexer().getLoc();
1440 if (getLexer().isNot(AsmToken::EndOfStatement))
1441 return TokError("unexpected token in '.include' directive");
1443 // Strip the quotes.
1444 Filename = Filename.substr(1, Filename.size()-2);
1446 // Attempt to switch the lexer to the included file before consuming the end
1447 // of statement to avoid losing it when we switch.
1448 if (EnterIncludeFile(Filename)) {
1449 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1456 /// ParseDirectiveIf
1457 /// ::= .if expression
1458 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1459 TheCondStack.push_back(TheCondState);
1460 TheCondState.TheCond = AsmCond::IfCond;
1461 if(TheCondState.Ignore) {
1462 EatToEndOfStatement();
1466 if (ParseAbsoluteExpression(ExprValue))
1469 if (getLexer().isNot(AsmToken::EndOfStatement))
1470 return TokError("unexpected token in '.if' directive");
1474 TheCondState.CondMet = ExprValue;
1475 TheCondState.Ignore = !TheCondState.CondMet;
1481 /// ParseDirectiveElseIf
1482 /// ::= .elseif expression
1483 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1484 if (TheCondState.TheCond != AsmCond::IfCond &&
1485 TheCondState.TheCond != AsmCond::ElseIfCond)
1486 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1488 TheCondState.TheCond = AsmCond::ElseIfCond;
1490 bool LastIgnoreState = false;
1491 if (!TheCondStack.empty())
1492 LastIgnoreState = TheCondStack.back().Ignore;
1493 if (LastIgnoreState || TheCondState.CondMet) {
1494 TheCondState.Ignore = true;
1495 EatToEndOfStatement();
1499 if (ParseAbsoluteExpression(ExprValue))
1502 if (getLexer().isNot(AsmToken::EndOfStatement))
1503 return TokError("unexpected token in '.elseif' directive");
1506 TheCondState.CondMet = ExprValue;
1507 TheCondState.Ignore = !TheCondState.CondMet;
1513 /// ParseDirectiveElse
1515 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1516 if (getLexer().isNot(AsmToken::EndOfStatement))
1517 return TokError("unexpected token in '.else' directive");
1521 if (TheCondState.TheCond != AsmCond::IfCond &&
1522 TheCondState.TheCond != AsmCond::ElseIfCond)
1523 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1525 TheCondState.TheCond = AsmCond::ElseCond;
1526 bool LastIgnoreState = false;
1527 if (!TheCondStack.empty())
1528 LastIgnoreState = TheCondStack.back().Ignore;
1529 if (LastIgnoreState || TheCondState.CondMet)
1530 TheCondState.Ignore = true;
1532 TheCondState.Ignore = false;
1537 /// ParseDirectiveEndIf
1539 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1540 if (getLexer().isNot(AsmToken::EndOfStatement))
1541 return TokError("unexpected token in '.endif' directive");
1545 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1546 TheCondStack.empty())
1547 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1549 if (!TheCondStack.empty()) {
1550 TheCondState = TheCondStack.back();
1551 TheCondStack.pop_back();
1557 /// ParseDirectiveFile
1558 /// ::= .file [number] string
1559 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1560 // FIXME: I'm not sure what this is.
1561 int64_t FileNumber = -1;
1562 if (getLexer().is(AsmToken::Integer)) {
1563 FileNumber = getTok().getIntVal();
1567 return TokError("file number less than one");
1570 if (getLexer().isNot(AsmToken::String))
1571 return TokError("unexpected token in '.file' directive");
1573 StringRef Filename = getTok().getString();
1574 Filename = Filename.substr(1, Filename.size()-2);
1577 if (getLexer().isNot(AsmToken::EndOfStatement))
1578 return TokError("unexpected token in '.file' directive");
1580 if (FileNumber == -1)
1581 getStreamer().EmitFileDirective(Filename);
1583 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1588 /// ParseDirectiveLine
1589 /// ::= .line [number]
1590 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1591 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1592 if (getLexer().isNot(AsmToken::Integer))
1593 return TokError("unexpected token in '.line' directive");
1595 int64_t LineNumber = getTok().getIntVal();
1599 // FIXME: Do something with the .line.
1602 if (getLexer().isNot(AsmToken::EndOfStatement))
1603 return TokError("unexpected token in '.line' directive");
1609 /// ParseDirectiveLoc
1610 /// ::= .loc number [number [number]]
1611 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1612 if (getLexer().isNot(AsmToken::Integer))
1613 return TokError("unexpected token in '.loc' directive");
1615 // FIXME: What are these fields?
1616 int64_t FileNumber = getTok().getIntVal();
1618 // FIXME: Validate file.
1621 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1622 if (getLexer().isNot(AsmToken::Integer))
1623 return TokError("unexpected token in '.loc' directive");
1625 int64_t Param2 = getTok().getIntVal();
1629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1630 if (getLexer().isNot(AsmToken::Integer))
1631 return TokError("unexpected token in '.loc' directive");
1633 int64_t Param3 = getTok().getIntVal();
1637 // FIXME: Do something with the .loc.
1641 if (getLexer().isNot(AsmToken::EndOfStatement))
1642 return TokError("unexpected token in '.file' directive");
1647 /// ParseDirectiveMacrosOnOff
1650 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1651 SMLoc DirectiveLoc) {
1652 if (getLexer().isNot(AsmToken::EndOfStatement))
1653 return Error(getLexer().getLoc(),
1654 "unexpected token in '" + Directive + "' directive");
1656 getParser().MacrosEnabled = Directive == ".macros_on";
1661 /// ParseDirectiveMacro
1663 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1664 SMLoc DirectiveLoc) {
1666 if (getParser().ParseIdentifier(Name))
1667 return TokError("expected identifier in directive");
1669 if (getLexer().isNot(AsmToken::EndOfStatement))
1670 return TokError("unexpected token in '.macro' directive");
1672 // Eat the end of statement.
1675 AsmToken EndToken, StartToken = getTok();
1677 // Lex the macro definition.
1679 // Check whether we have reached the end of the file.
1680 if (getLexer().is(AsmToken::Eof))
1681 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1683 // Otherwise, check whether we have reach the .endmacro.
1684 if (getLexer().is(AsmToken::Identifier) &&
1685 (getTok().getIdentifier() == ".endm" ||
1686 getTok().getIdentifier() == ".endmacro")) {
1687 EndToken = getTok();
1689 if (getLexer().isNot(AsmToken::EndOfStatement))
1690 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1695 // Otherwise, scan til the end of the statement.
1696 getParser().EatToEndOfStatement();
1699 if (getParser().MacroMap.lookup(Name)) {
1700 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1703 const char *BodyStart = StartToken.getLoc().getPointer();
1704 const char *BodyEnd = EndToken.getLoc().getPointer();
1705 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1706 getParser().MacroMap[Name] = new Macro(Name, Body);
1710 /// ParseDirectiveEndMacro
1713 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1714 SMLoc DirectiveLoc) {
1715 if (getLexer().isNot(AsmToken::EndOfStatement))
1716 return TokError("unexpected token in '" + Directive + "' directive");
1718 // If we see a .endmacro directly, it is a stray entry in the file; well
1719 // formed .endmacro directives are handled during the macro definition
1721 return TokError("unexpected '" + Directive + "' in file, "
1722 "no current macro definition");
1725 /// \brief Create an MCAsmParser instance.
1726 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1727 MCContext &C, MCStreamer &Out,
1728 const MCAsmInfo &MAI) {
1729 return new AsmParser(T, SM, C, Out, MAI);