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 Helper class for storing information about an active macro
50 struct MacroInstantiation {
51 /// The macro being instantiated.
52 const Macro *TheMacro;
54 /// The macro instantiation with substitutions.
55 MemoryBuffer *Instantiation;
57 /// The location of the instantiation.
58 SMLoc InstantiationLoc;
60 /// The location where parsing should resume upon instantiation completion.
64 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
65 const std::vector<std::vector<AsmToken> > &A);
68 /// \brief The concrete assembly parser instance.
69 class AsmParser : public MCAsmParser {
70 friend class GenericAsmParser;
72 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
73 void operator=(const AsmParser &); // DO NOT IMPLEMENT
79 MCAsmParserExtension *GenericParser;
80 MCAsmParserExtension *PlatformParser;
82 /// This is the current buffer index we're lexing from as managed by the
87 std::vector<AsmCond> TheCondStack;
89 /// DirectiveMap - This is a table handlers for directives. Each handler is
90 /// invoked after the directive identifier is read and is responsible for
91 /// parsing and validating the rest of the directive. The handler is passed
92 /// in the directive name and the location of the directive keyword.
93 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95 /// MacroMap - Map of currently defined macros.
96 StringMap<Macro*> MacroMap;
98 /// ActiveMacros - Stack of active macro instantiations.
99 std::vector<MacroInstantiation*> ActiveMacros;
101 /// Boolean tracking whether macro substitution is enabled.
102 unsigned MacrosEnabled : 1;
105 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
106 const MCAsmInfo &MAI);
109 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
111 void AddDirectiveHandler(MCAsmParserExtension *Object,
113 DirectiveHandler Handler) {
114 DirectiveMap[Directive] = std::make_pair(Object, Handler);
118 /// @name MCAsmParser Interface
121 virtual SourceMgr &getSourceManager() { return SrcMgr; }
122 virtual MCAsmLexer &getLexer() { return Lexer; }
123 virtual MCContext &getContext() { return Ctx; }
124 virtual MCStreamer &getStreamer() { return Out; }
126 virtual void Warning(SMLoc L, const Twine &Meg);
127 virtual bool Error(SMLoc L, const Twine &Msg);
129 const AsmToken &Lex();
131 bool ParseExpression(const MCExpr *&Res);
132 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
133 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
134 virtual bool ParseAbsoluteExpression(int64_t &Res);
139 bool ParseStatement();
141 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
142 void HandleMacroExit();
144 void PrintMacroInstantiations();
145 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
147 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
148 bool EnterIncludeFile(const std::string &Filename);
150 /// \brief Reset the current lexer position to that given by \arg Loc. The
151 /// current token is not set; clients should ensure Lex() is called
153 void JumpToLoc(SMLoc Loc);
155 void EatToEndOfStatement();
157 /// \brief Parse up to the end of statement and a return the contents from the
158 /// current token until the end of the statement; the current token on exit
159 /// will be either the EndOfStatement or EOF.
160 StringRef ParseStringToEndOfStatement();
162 bool ParseAssignment(StringRef Name);
164 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
165 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
166 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
168 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
169 /// and set \arg Res to the identifier contents.
170 bool ParseIdentifier(StringRef &Res);
172 // Directive Parsing.
173 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
174 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
175 bool ParseDirectiveFill(); // ".fill"
176 bool ParseDirectiveSpace(); // ".space"
177 bool ParseDirectiveSet(); // ".set"
178 bool ParseDirectiveOrg(); // ".org"
179 // ".align{,32}", ".p2align{,w,l}"
180 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
182 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
183 /// accepts a single symbol (which should be a label or an external).
184 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
185 bool ParseDirectiveELFType(); // ELF specific ".type"
187 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
189 bool ParseDirectiveAbort(); // ".abort"
190 bool ParseDirectiveInclude(); // ".include"
192 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
193 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
194 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
195 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
197 /// ParseEscapedString - Parse the current token as a string which may include
198 /// escaped characters and return the string contents.
199 bool ParseEscapedString(std::string &Data);
202 /// \brief Generic implementations of directive handling, etc. which is shared
203 /// (or the default, at least) for all assembler parser.
204 class GenericAsmParser : public MCAsmParserExtension {
206 GenericAsmParser() {}
208 AsmParser &getParser() {
209 return (AsmParser&) this->MCAsmParserExtension::getParser();
212 virtual void Initialize(MCAsmParser &Parser) {
213 // Call the base implementation.
214 this->MCAsmParserExtension::Initialize(Parser);
216 // Debugging directives.
217 Parser.AddDirectiveHandler(this, ".file", MCAsmParser::DirectiveHandler(
218 &GenericAsmParser::ParseDirectiveFile));
219 Parser.AddDirectiveHandler(this, ".line", MCAsmParser::DirectiveHandler(
220 &GenericAsmParser::ParseDirectiveLine));
221 Parser.AddDirectiveHandler(this, ".loc", MCAsmParser::DirectiveHandler(
222 &GenericAsmParser::ParseDirectiveLoc));
225 Parser.AddDirectiveHandler(this, ".macros_on",
226 MCAsmParser::DirectiveHandler(
227 &GenericAsmParser::ParseDirectiveMacrosOnOff));
228 Parser.AddDirectiveHandler(this, ".macros_off",
229 MCAsmParser::DirectiveHandler(
230 &GenericAsmParser::ParseDirectiveMacrosOnOff));
231 Parser.AddDirectiveHandler(this, ".macro", MCAsmParser::DirectiveHandler(
232 &GenericAsmParser::ParseDirectiveMacro));
233 Parser.AddDirectiveHandler(this, ".endm", MCAsmParser::DirectiveHandler(
234 &GenericAsmParser::ParseDirectiveEndMacro));
235 Parser.AddDirectiveHandler(this, ".endmacro", MCAsmParser::DirectiveHandler(
236 &GenericAsmParser::ParseDirectiveEndMacro));
239 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
240 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
241 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
243 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
244 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
245 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
252 extern MCAsmParserExtension *createDarwinAsmParser();
253 extern MCAsmParserExtension *createELFAsmParser();
257 enum { DEFAULT_ADDRSPACE = 0 };
259 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
260 MCStreamer &_Out, const MCAsmInfo &_MAI)
261 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
262 GenericParser(new GenericAsmParser), PlatformParser(0),
263 CurBuffer(0), MacrosEnabled(true) {
264 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
266 // Initialize the generic parser.
267 GenericParser->Initialize(*this);
269 // Initialize the platform / file format parser.
271 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
273 if (_MAI.hasSubsectionsViaSymbols()) {
274 PlatformParser = createDarwinAsmParser();
275 PlatformParser->Initialize(*this);
277 PlatformParser = createELFAsmParser();
278 PlatformParser->Initialize(*this);
282 AsmParser::~AsmParser() {
283 delete PlatformParser;
284 delete GenericParser;
287 void AsmParser::PrintMacroInstantiations() {
288 // Print the active macro instantiation stack.
289 for (std::vector<MacroInstantiation*>::const_reverse_iterator
290 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
291 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
295 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
296 PrintMessage(L, Msg.str(), "warning");
297 PrintMacroInstantiations();
300 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
301 PrintMessage(L, Msg.str(), "error");
302 PrintMacroInstantiations();
306 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
307 const char *Type) const {
308 SrcMgr.PrintMessage(Loc, Msg, Type);
311 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
312 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
318 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
323 void AsmParser::JumpToLoc(SMLoc Loc) {
324 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
325 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
328 const AsmToken &AsmParser::Lex() {
329 const AsmToken *tok = &Lexer.Lex();
331 if (tok->is(AsmToken::Eof)) {
332 // If this is the end of an included file, pop the parent file off the
334 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
335 if (ParentIncludeLoc != SMLoc()) {
336 JumpToLoc(ParentIncludeLoc);
341 if (tok->is(AsmToken::Error))
342 Error(Lexer.getErrLoc(), Lexer.getErr());
347 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
348 // Create the initial section, if requested.
350 // FIXME: Target hook & command line option for initial section.
351 if (!NoInitialTextSection)
352 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
353 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
354 0, SectionKind::getText()));
359 bool HadError = false;
361 AsmCond StartingCondState = TheCondState;
363 // While we have input, parse each statement.
364 while (Lexer.isNot(AsmToken::Eof)) {
365 if (!ParseStatement()) continue;
367 // We had an error, remember it and recover by skipping to the next line.
369 EatToEndOfStatement();
372 if (TheCondState.TheCond != StartingCondState.TheCond ||
373 TheCondState.Ignore != StartingCondState.Ignore)
374 return TokError("unmatched .ifs or .elses");
376 // Finalize the output stream if there are no errors and if the client wants
378 if (!HadError && !NoFinalize)
384 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
385 void AsmParser::EatToEndOfStatement() {
386 while (Lexer.isNot(AsmToken::EndOfStatement) &&
387 Lexer.isNot(AsmToken::Eof))
391 if (Lexer.is(AsmToken::EndOfStatement))
395 StringRef AsmParser::ParseStringToEndOfStatement() {
396 const char *Start = getTok().getLoc().getPointer();
398 while (Lexer.isNot(AsmToken::EndOfStatement) &&
399 Lexer.isNot(AsmToken::Eof))
402 const char *End = getTok().getLoc().getPointer();
403 return StringRef(Start, End - Start);
406 /// ParseParenExpr - Parse a paren expression and return it.
407 /// NOTE: This assumes the leading '(' has already been consumed.
409 /// parenexpr ::= expr)
411 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
412 if (ParseExpression(Res)) return true;
413 if (Lexer.isNot(AsmToken::RParen))
414 return TokError("expected ')' in parentheses expression");
415 EndLoc = Lexer.getLoc();
420 /// ParsePrimaryExpr - Parse a primary expression and return it.
421 /// primaryexpr ::= (parenexpr
422 /// primaryexpr ::= symbol
423 /// primaryexpr ::= number
424 /// primaryexpr ::= '.'
425 /// primaryexpr ::= ~,+,- primaryexpr
426 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
427 switch (Lexer.getKind()) {
429 return TokError("unknown token in expression");
430 case AsmToken::Exclaim:
431 Lex(); // Eat the operator.
432 if (ParsePrimaryExpr(Res, EndLoc))
434 Res = MCUnaryExpr::CreateLNot(Res, getContext());
436 case AsmToken::String:
437 case AsmToken::Identifier: {
438 // This is a symbol reference.
439 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
440 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
442 // Mark the symbol as used in an expression.
443 Sym->setUsedInExpr(true);
445 // Lookup the symbol variant if used.
446 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
447 if (Split.first.size() != getTok().getIdentifier().size())
448 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
450 EndLoc = Lexer.getLoc();
451 Lex(); // Eat identifier.
453 // If this is an absolute variable reference, substitute it now to preserve
454 // semantics in the face of reassignment.
455 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
457 return Error(EndLoc, "unexpected modified on variable reference");
459 Res = Sym->getVariableValue();
463 // Otherwise create a symbol ref.
464 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
467 case AsmToken::Integer: {
468 SMLoc Loc = getTok().getLoc();
469 int64_t IntVal = getTok().getIntVal();
470 Res = MCConstantExpr::Create(IntVal, getContext());
471 EndLoc = Lexer.getLoc();
473 // Look for 'b' or 'f' following an Integer as a directional label
474 if (Lexer.getKind() == AsmToken::Identifier) {
475 StringRef IDVal = getTok().getString();
476 if (IDVal == "f" || IDVal == "b"){
477 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
478 IDVal == "f" ? 1 : 0);
479 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
481 if(IDVal == "b" && Sym->isUndefined())
482 return Error(Loc, "invalid reference to undefined symbol");
483 EndLoc = Lexer.getLoc();
484 Lex(); // Eat identifier.
489 case AsmToken::Dot: {
490 // This is a '.' reference, which references the current PC. Emit a
491 // temporary label to the streamer and refer to it.
492 MCSymbol *Sym = Ctx.CreateTempSymbol();
494 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
495 EndLoc = Lexer.getLoc();
496 Lex(); // Eat identifier.
500 case AsmToken::LParen:
501 Lex(); // Eat the '('.
502 return ParseParenExpr(Res, EndLoc);
503 case AsmToken::Minus:
504 Lex(); // Eat the operator.
505 if (ParsePrimaryExpr(Res, EndLoc))
507 Res = MCUnaryExpr::CreateMinus(Res, getContext());
510 Lex(); // Eat the operator.
511 if (ParsePrimaryExpr(Res, EndLoc))
513 Res = MCUnaryExpr::CreatePlus(Res, getContext());
515 case AsmToken::Tilde:
516 Lex(); // Eat the operator.
517 if (ParsePrimaryExpr(Res, EndLoc))
519 Res = MCUnaryExpr::CreateNot(Res, getContext());
524 bool AsmParser::ParseExpression(const MCExpr *&Res) {
526 return ParseExpression(Res, EndLoc);
529 /// ParseExpression - Parse an expression and return it.
531 /// expr ::= expr +,- expr -> lowest.
532 /// expr ::= expr |,^,&,! expr -> middle.
533 /// expr ::= expr *,/,%,<<,>> expr -> highest.
534 /// expr ::= primaryexpr
536 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
537 // Parse the expression.
539 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
542 // Try to constant fold it up front, if possible.
544 if (Res->EvaluateAsAbsolute(Value))
545 Res = MCConstantExpr::Create(Value, getContext());
550 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
552 return ParseParenExpr(Res, EndLoc) ||
553 ParseBinOpRHS(1, Res, EndLoc);
556 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
559 SMLoc StartLoc = Lexer.getLoc();
560 if (ParseExpression(Expr))
563 if (!Expr->EvaluateAsAbsolute(Res))
564 return Error(StartLoc, "expected absolute expression");
569 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
570 MCBinaryExpr::Opcode &Kind) {
573 return 0; // not a binop.
575 // Lowest Precedence: &&, ||
576 case AsmToken::AmpAmp:
577 Kind = MCBinaryExpr::LAnd;
579 case AsmToken::PipePipe:
580 Kind = MCBinaryExpr::LOr;
583 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
585 Kind = MCBinaryExpr::Add;
587 case AsmToken::Minus:
588 Kind = MCBinaryExpr::Sub;
590 case AsmToken::EqualEqual:
591 Kind = MCBinaryExpr::EQ;
593 case AsmToken::ExclaimEqual:
594 case AsmToken::LessGreater:
595 Kind = MCBinaryExpr::NE;
598 Kind = MCBinaryExpr::LT;
600 case AsmToken::LessEqual:
601 Kind = MCBinaryExpr::LTE;
603 case AsmToken::Greater:
604 Kind = MCBinaryExpr::GT;
606 case AsmToken::GreaterEqual:
607 Kind = MCBinaryExpr::GTE;
610 // Intermediate Precedence: |, &, ^
612 // FIXME: gas seems to support '!' as an infix operator?
614 Kind = MCBinaryExpr::Or;
616 case AsmToken::Caret:
617 Kind = MCBinaryExpr::Xor;
620 Kind = MCBinaryExpr::And;
623 // Highest Precedence: *, /, %, <<, >>
625 Kind = MCBinaryExpr::Mul;
627 case AsmToken::Slash:
628 Kind = MCBinaryExpr::Div;
630 case AsmToken::Percent:
631 Kind = MCBinaryExpr::Mod;
633 case AsmToken::LessLess:
634 Kind = MCBinaryExpr::Shl;
636 case AsmToken::GreaterGreater:
637 Kind = MCBinaryExpr::Shr;
643 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
644 /// Res contains the LHS of the expression on input.
645 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
648 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
649 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
651 // If the next token is lower precedence than we are allowed to eat, return
652 // successfully with what we ate already.
653 if (TokPrec < Precedence)
658 // Eat the next primary expression.
660 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
662 // If BinOp binds less tightly with RHS than the operator after RHS, let
663 // the pending operator take RHS as its LHS.
664 MCBinaryExpr::Opcode Dummy;
665 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
666 if (TokPrec < NextTokPrec) {
667 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
670 // Merge LHS and RHS according to operator.
671 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
679 /// ::= EndOfStatement
680 /// ::= Label* Directive ...Operands... EndOfStatement
681 /// ::= Label* Identifier OperandList* EndOfStatement
682 bool AsmParser::ParseStatement() {
683 if (Lexer.is(AsmToken::EndOfStatement)) {
689 // Statements always start with an identifier.
690 AsmToken ID = getTok();
691 SMLoc IDLoc = ID.getLoc();
693 int64_t LocalLabelVal = -1;
694 // GUESS allow an integer followed by a ':' as a directional local label
695 if (Lexer.is(AsmToken::Integer)) {
696 LocalLabelVal = getTok().getIntVal();
697 if (LocalLabelVal < 0) {
698 if (!TheCondState.Ignore)
699 return TokError("unexpected token at start of statement");
703 IDVal = getTok().getString();
704 Lex(); // Consume the integer token to be used as an identifier token.
705 if (Lexer.getKind() != AsmToken::Colon) {
706 if (!TheCondState.Ignore)
707 return TokError("unexpected token at start of statement");
711 else if (ParseIdentifier(IDVal)) {
712 if (!TheCondState.Ignore)
713 return TokError("unexpected token at start of statement");
717 // Handle conditional assembly here before checking for skipping. We
718 // have to do this so that .endif isn't skipped in a ".if 0" block for
721 return ParseDirectiveIf(IDLoc);
722 if (IDVal == ".elseif")
723 return ParseDirectiveElseIf(IDLoc);
724 if (IDVal == ".else")
725 return ParseDirectiveElse(IDLoc);
726 if (IDVal == ".endif")
727 return ParseDirectiveEndIf(IDLoc);
729 // If we are in a ".if 0" block, ignore this statement.
730 if (TheCondState.Ignore) {
731 EatToEndOfStatement();
735 // FIXME: Recurse on local labels?
737 // See what kind of statement we have.
738 switch (Lexer.getKind()) {
739 case AsmToken::Colon: {
740 // identifier ':' -> Label.
743 // Diagnose attempt to use a variable as a label.
745 // FIXME: Diagnostics. Note the location of the definition as a label.
746 // FIXME: This doesn't diagnose assignment to a symbol which has been
747 // implicitly marked as external.
749 if (LocalLabelVal == -1)
750 Sym = getContext().GetOrCreateSymbol(IDVal);
752 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
753 if (!Sym->isUndefined() || Sym->isVariable())
754 return Error(IDLoc, "invalid symbol redefinition");
759 // Consume any end of statement token, if present, to avoid spurious
760 // AddBlankLine calls().
761 if (Lexer.is(AsmToken::EndOfStatement)) {
763 if (Lexer.is(AsmToken::Eof))
767 return ParseStatement();
770 case AsmToken::Equal:
771 // identifier '=' ... -> assignment statement
774 return ParseAssignment(IDVal);
776 default: // Normal instruction or directive.
780 // If macros are enabled, check to see if this is a macro instantiation.
782 if (const Macro *M = MacroMap.lookup(IDVal))
783 return HandleMacroEntry(IDVal, IDLoc, M);
785 // Otherwise, we have a normal instruction or directive.
786 if (IDVal[0] == '.') {
787 // Assembler features
789 return ParseDirectiveSet();
793 if (IDVal == ".ascii")
794 return ParseDirectiveAscii(false);
795 if (IDVal == ".asciz")
796 return ParseDirectiveAscii(true);
798 if (IDVal == ".byte")
799 return ParseDirectiveValue(1);
800 if (IDVal == ".short")
801 return ParseDirectiveValue(2);
802 if (IDVal == ".long")
803 return ParseDirectiveValue(4);
804 if (IDVal == ".quad")
805 return ParseDirectiveValue(8);
807 // FIXME: Target hooks for IsPow2.
808 if (IDVal == ".align")
809 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
810 if (IDVal == ".align32")
811 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
812 if (IDVal == ".balign")
813 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
814 if (IDVal == ".balignw")
815 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
816 if (IDVal == ".balignl")
817 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
818 if (IDVal == ".p2align")
819 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
820 if (IDVal == ".p2alignw")
821 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
822 if (IDVal == ".p2alignl")
823 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
826 return ParseDirectiveOrg();
828 if (IDVal == ".fill")
829 return ParseDirectiveFill();
830 if (IDVal == ".space")
831 return ParseDirectiveSpace();
833 // Symbol attribute directives
835 if (IDVal == ".globl" || IDVal == ".global")
836 return ParseDirectiveSymbolAttribute(MCSA_Global);
837 if (IDVal == ".hidden")
838 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
839 if (IDVal == ".indirect_symbol")
840 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
841 if (IDVal == ".internal")
842 return ParseDirectiveSymbolAttribute(MCSA_Internal);
843 if (IDVal == ".lazy_reference")
844 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
845 if (IDVal == ".no_dead_strip")
846 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
847 if (IDVal == ".private_extern")
848 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
849 if (IDVal == ".protected")
850 return ParseDirectiveSymbolAttribute(MCSA_Protected);
851 if (IDVal == ".reference")
852 return ParseDirectiveSymbolAttribute(MCSA_Reference);
853 if (IDVal == ".type")
854 return ParseDirectiveELFType();
855 if (IDVal == ".weak")
856 return ParseDirectiveSymbolAttribute(MCSA_Weak);
857 if (IDVal == ".weak_definition")
858 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
859 if (IDVal == ".weak_reference")
860 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
861 if (IDVal == ".weak_def_can_be_hidden")
862 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
864 if (IDVal == ".comm")
865 return ParseDirectiveComm(/*IsLocal=*/false);
866 if (IDVal == ".lcomm")
867 return ParseDirectiveComm(/*IsLocal=*/true);
869 if (IDVal == ".abort")
870 return ParseDirectiveAbort();
871 if (IDVal == ".include")
872 return ParseDirectiveInclude();
874 // Look up the handler in the handler table.
875 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
876 DirectiveMap.lookup(IDVal);
878 return (Handler.first->*Handler.second)(IDVal, IDLoc);
880 // Target hook for parsing target specific directives.
881 if (!getTargetParser().ParseDirective(ID))
884 Warning(IDLoc, "ignoring directive for now");
885 EatToEndOfStatement();
889 // Canonicalize the opcode to lower case.
890 SmallString<128> Opcode;
891 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
892 Opcode.push_back(tolower(IDVal[i]));
894 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
895 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
897 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
898 HadError = TokError("unexpected token in argument list");
900 // If parsing succeeded, match the instruction.
903 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
904 // Emit the instruction on success.
905 Out.EmitInstruction(Inst);
907 // Otherwise emit a diagnostic about the match failure and set the error
910 // FIXME: We should give nicer diagnostics about the exact failure.
911 Error(IDLoc, "unrecognized instruction");
916 // If there was no error, consume the end-of-statement token. Otherwise this
917 // will be done by our caller.
921 // Free any parsed operands.
922 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
923 delete ParsedOperands[i];
928 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
929 const std::vector<std::vector<AsmToken> > &A)
930 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
932 // Macro instantiation is lexical, unfortunately. We construct a new buffer
933 // to hold the macro body with substitutions.
934 SmallString<256> Buf;
935 raw_svector_ostream OS(Buf);
937 StringRef Body = M->Body;
938 while (!Body.empty()) {
939 // Scan for the next substitution.
940 std::size_t End = Body.size(), Pos = 0;
941 for (; Pos != End; ++Pos) {
942 // Check for a substitution or escape.
943 if (Body[Pos] != '$' || Pos + 1 == End)
946 char Next = Body[Pos + 1];
947 if (Next == '$' || Next == 'n' || isdigit(Next))
952 OS << Body.slice(0, Pos);
954 // Check if we reached the end.
958 switch (Body[Pos+1]) {
964 // $n => number of arguments
969 // $[0-9] => argument
971 // Missing arguments are ignored.
972 unsigned Index = Body[Pos+1] - '0';
973 if (Index >= A.size())
976 // Otherwise substitute with the token values, with spaces eliminated.
977 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
978 ie = A[Index].end(); it != ie; ++it)
979 OS << it->getString();
984 // Update the scan point.
985 Body = Body.substr(Pos + 2);
988 // We include the .endmacro in the buffer as our queue to exit the macro
992 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
995 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
997 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
998 // this, although we should protect against infinite loops.
999 if (ActiveMacros.size() == 20)
1000 return TokError("macros cannot be nested more than 20 levels deep");
1002 // Parse the macro instantiation arguments.
1003 std::vector<std::vector<AsmToken> > MacroArguments;
1004 MacroArguments.push_back(std::vector<AsmToken>());
1005 unsigned ParenLevel = 0;
1007 if (Lexer.is(AsmToken::Eof))
1008 return TokError("unexpected token in macro instantiation");
1009 if (Lexer.is(AsmToken::EndOfStatement))
1012 // If we aren't inside parentheses and this is a comma, start a new token
1014 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1015 MacroArguments.push_back(std::vector<AsmToken>());
1016 } else if (Lexer.is(AsmToken::LParen)) {
1018 } else if (Lexer.is(AsmToken::RParen)) {
1022 MacroArguments.back().push_back(getTok());
1027 // Create the macro instantiation object and add to the current macro
1028 // instantiation stack.
1029 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1032 ActiveMacros.push_back(MI);
1034 // Jump to the macro instantiation and prime the lexer.
1035 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1036 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1042 void AsmParser::HandleMacroExit() {
1043 // Jump to the EndOfStatement we should return to, and consume it.
1044 JumpToLoc(ActiveMacros.back()->ExitLoc);
1047 // Pop the instantiation entry.
1048 delete ActiveMacros.back();
1049 ActiveMacros.pop_back();
1052 bool AsmParser::ParseAssignment(StringRef Name) {
1053 // FIXME: Use better location, we should use proper tokens.
1054 SMLoc EqualLoc = Lexer.getLoc();
1056 const MCExpr *Value;
1057 if (ParseExpression(Value))
1060 if (Lexer.isNot(AsmToken::EndOfStatement))
1061 return TokError("unexpected token in assignment");
1063 // Eat the end of statement marker.
1066 // Validate that the LHS is allowed to be a variable (either it has not been
1067 // used as a symbol, or it is an absolute symbol).
1068 MCSymbol *Sym = getContext().LookupSymbol(Name);
1070 // Diagnose assignment to a label.
1072 // FIXME: Diagnostics. Note the location of the definition as a label.
1073 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1074 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1075 ; // Allow redefinitions of undefined symbols only used in directives.
1076 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1077 return Error(EqualLoc, "redefinition of '" + Name + "'");
1078 else if (!Sym->isVariable())
1079 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1080 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1081 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1084 Sym = getContext().GetOrCreateSymbol(Name);
1086 // FIXME: Handle '.'.
1088 Sym->setUsedInExpr(true);
1090 // Do the assignment.
1091 Out.EmitAssignment(Sym, Value);
1096 /// ParseIdentifier:
1099 bool AsmParser::ParseIdentifier(StringRef &Res) {
1100 if (Lexer.isNot(AsmToken::Identifier) &&
1101 Lexer.isNot(AsmToken::String))
1104 Res = getTok().getIdentifier();
1106 Lex(); // Consume the identifier token.
1111 /// ParseDirectiveSet:
1112 /// ::= .set identifier ',' expression
1113 bool AsmParser::ParseDirectiveSet() {
1116 if (ParseIdentifier(Name))
1117 return TokError("expected identifier after '.set' directive");
1119 if (getLexer().isNot(AsmToken::Comma))
1120 return TokError("unexpected token in '.set'");
1123 return ParseAssignment(Name);
1126 bool AsmParser::ParseEscapedString(std::string &Data) {
1127 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1130 StringRef Str = getTok().getStringContents();
1131 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1132 if (Str[i] != '\\') {
1137 // Recognize escaped characters. Note that this escape semantics currently
1138 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1141 return TokError("unexpected backslash at end of string");
1143 // Recognize octal sequences.
1144 if ((unsigned) (Str[i] - '0') <= 7) {
1145 // Consume up to three octal characters.
1146 unsigned Value = Str[i] - '0';
1148 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1150 Value = Value * 8 + (Str[i] - '0');
1152 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1154 Value = Value * 8 + (Str[i] - '0');
1159 return TokError("invalid octal escape sequence (out of range)");
1161 Data += (unsigned char) Value;
1165 // Otherwise recognize individual escapes.
1168 // Just reject invalid escape sequences for now.
1169 return TokError("invalid escape sequence (unrecognized character)");
1171 case 'b': Data += '\b'; break;
1172 case 'f': Data += '\f'; break;
1173 case 'n': Data += '\n'; break;
1174 case 'r': Data += '\r'; break;
1175 case 't': Data += '\t'; break;
1176 case '"': Data += '"'; break;
1177 case '\\': Data += '\\'; break;
1184 /// ParseDirectiveAscii:
1185 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1186 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1187 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1189 if (getLexer().isNot(AsmToken::String))
1190 return TokError("expected string in '.ascii' or '.asciz' directive");
1193 if (ParseEscapedString(Data))
1196 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1198 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1202 if (getLexer().is(AsmToken::EndOfStatement))
1205 if (getLexer().isNot(AsmToken::Comma))
1206 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1215 /// ParseDirectiveValue
1216 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1217 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1218 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1220 const MCExpr *Value;
1221 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1222 if (ParseExpression(Value))
1225 // Special case constant expressions to match code generator.
1226 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1227 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1229 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1231 if (getLexer().is(AsmToken::EndOfStatement))
1234 // FIXME: Improve diagnostic.
1235 if (getLexer().isNot(AsmToken::Comma))
1236 return TokError("unexpected token in directive");
1245 /// ParseDirectiveSpace
1246 /// ::= .space expression [ , expression ]
1247 bool AsmParser::ParseDirectiveSpace() {
1249 if (ParseAbsoluteExpression(NumBytes))
1252 int64_t FillExpr = 0;
1253 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1254 if (getLexer().isNot(AsmToken::Comma))
1255 return TokError("unexpected token in '.space' directive");
1258 if (ParseAbsoluteExpression(FillExpr))
1261 if (getLexer().isNot(AsmToken::EndOfStatement))
1262 return TokError("unexpected token in '.space' directive");
1268 return TokError("invalid number of bytes in '.space' directive");
1270 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1271 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1276 /// ParseDirectiveFill
1277 /// ::= .fill expression , expression , expression
1278 bool AsmParser::ParseDirectiveFill() {
1280 if (ParseAbsoluteExpression(NumValues))
1283 if (getLexer().isNot(AsmToken::Comma))
1284 return TokError("unexpected token in '.fill' directive");
1288 if (ParseAbsoluteExpression(FillSize))
1291 if (getLexer().isNot(AsmToken::Comma))
1292 return TokError("unexpected token in '.fill' directive");
1296 if (ParseAbsoluteExpression(FillExpr))
1299 if (getLexer().isNot(AsmToken::EndOfStatement))
1300 return TokError("unexpected token in '.fill' directive");
1304 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1305 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1307 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1308 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1313 /// ParseDirectiveOrg
1314 /// ::= .org expression [ , expression ]
1315 bool AsmParser::ParseDirectiveOrg() {
1316 const MCExpr *Offset;
1317 if (ParseExpression(Offset))
1320 // Parse optional fill expression.
1321 int64_t FillExpr = 0;
1322 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1323 if (getLexer().isNot(AsmToken::Comma))
1324 return TokError("unexpected token in '.org' directive");
1327 if (ParseAbsoluteExpression(FillExpr))
1330 if (getLexer().isNot(AsmToken::EndOfStatement))
1331 return TokError("unexpected token in '.org' directive");
1336 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1337 // has to be relative to the current section.
1338 getStreamer().EmitValueToOffset(Offset, FillExpr);
1343 /// ParseDirectiveAlign
1344 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1345 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1346 SMLoc AlignmentLoc = getLexer().getLoc();
1348 if (ParseAbsoluteExpression(Alignment))
1352 bool HasFillExpr = false;
1353 int64_t FillExpr = 0;
1354 int64_t MaxBytesToFill = 0;
1355 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1356 if (getLexer().isNot(AsmToken::Comma))
1357 return TokError("unexpected token in directive");
1360 // The fill expression can be omitted while specifying a maximum number of
1361 // alignment bytes, e.g:
1363 if (getLexer().isNot(AsmToken::Comma)) {
1365 if (ParseAbsoluteExpression(FillExpr))
1369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1370 if (getLexer().isNot(AsmToken::Comma))
1371 return TokError("unexpected token in directive");
1374 MaxBytesLoc = getLexer().getLoc();
1375 if (ParseAbsoluteExpression(MaxBytesToFill))
1378 if (getLexer().isNot(AsmToken::EndOfStatement))
1379 return TokError("unexpected token in directive");
1388 // Compute alignment in bytes.
1390 // FIXME: Diagnose overflow.
1391 if (Alignment >= 32) {
1392 Error(AlignmentLoc, "invalid alignment value");
1396 Alignment = 1ULL << Alignment;
1399 // Diagnose non-sensical max bytes to align.
1400 if (MaxBytesLoc.isValid()) {
1401 if (MaxBytesToFill < 1) {
1402 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1403 "many bytes, ignoring maximum bytes expression");
1407 if (MaxBytesToFill >= Alignment) {
1408 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1414 // Check whether we should use optimal code alignment for this .align
1417 // FIXME: This should be using a target hook.
1418 bool UseCodeAlign = false;
1419 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1420 getStreamer().getCurrentSection()))
1421 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1422 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1423 ValueSize == 1 && UseCodeAlign) {
1424 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1426 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1427 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1434 /// ParseDirectiveSymbolAttribute
1435 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1436 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1437 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1441 if (ParseIdentifier(Name))
1442 return TokError("expected identifier in directive");
1444 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1446 getStreamer().EmitSymbolAttribute(Sym, Attr);
1448 if (getLexer().is(AsmToken::EndOfStatement))
1451 if (getLexer().isNot(AsmToken::Comma))
1452 return TokError("unexpected token in directive");
1461 /// ParseDirectiveELFType
1462 /// ::= .type identifier , @attribute
1463 bool AsmParser::ParseDirectiveELFType() {
1465 if (ParseIdentifier(Name))
1466 return TokError("expected identifier in directive");
1468 // Handle the identifier as the key symbol.
1469 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1471 if (getLexer().isNot(AsmToken::Comma))
1472 return TokError("unexpected token in '.type' directive");
1475 if (getLexer().isNot(AsmToken::At))
1476 return TokError("expected '@' before type");
1482 TypeLoc = getLexer().getLoc();
1483 if (ParseIdentifier(Type))
1484 return TokError("expected symbol type in directive");
1486 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1487 .Case("function", MCSA_ELF_TypeFunction)
1488 .Case("object", MCSA_ELF_TypeObject)
1489 .Case("tls_object", MCSA_ELF_TypeTLS)
1490 .Case("common", MCSA_ELF_TypeCommon)
1491 .Case("notype", MCSA_ELF_TypeNoType)
1492 .Default(MCSA_Invalid);
1494 if (Attr == MCSA_Invalid)
1495 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1497 if (getLexer().isNot(AsmToken::EndOfStatement))
1498 return TokError("unexpected token in '.type' directive");
1502 getStreamer().EmitSymbolAttribute(Sym, Attr);
1507 /// ParseDirectiveComm
1508 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1509 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1510 SMLoc IDLoc = getLexer().getLoc();
1512 if (ParseIdentifier(Name))
1513 return TokError("expected identifier in directive");
1515 // Handle the identifier as the key symbol.
1516 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1518 if (getLexer().isNot(AsmToken::Comma))
1519 return TokError("unexpected token in directive");
1523 SMLoc SizeLoc = getLexer().getLoc();
1524 if (ParseAbsoluteExpression(Size))
1527 int64_t Pow2Alignment = 0;
1528 SMLoc Pow2AlignmentLoc;
1529 if (getLexer().is(AsmToken::Comma)) {
1531 Pow2AlignmentLoc = getLexer().getLoc();
1532 if (ParseAbsoluteExpression(Pow2Alignment))
1535 // If this target takes alignments in bytes (not log) validate and convert.
1536 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1537 if (!isPowerOf2_64(Pow2Alignment))
1538 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1539 Pow2Alignment = Log2_64(Pow2Alignment);
1543 if (getLexer().isNot(AsmToken::EndOfStatement))
1544 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1548 // NOTE: a size of zero for a .comm should create a undefined symbol
1549 // but a size of .lcomm creates a bss symbol of size zero.
1551 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1552 "be less than zero");
1554 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1555 // may internally end up wanting an alignment in bytes.
1556 // FIXME: Diagnose overflow.
1557 if (Pow2Alignment < 0)
1558 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1559 "alignment, can't be less than zero");
1561 if (!Sym->isUndefined())
1562 return Error(IDLoc, "invalid symbol redefinition");
1564 // '.lcomm' is equivalent to '.zerofill'.
1565 // Create the Symbol as a common or local common with Size and Pow2Alignment
1567 getStreamer().EmitZerofill(Ctx.getMachOSection(
1568 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1569 0, SectionKind::getBSS()),
1570 Sym, Size, 1 << Pow2Alignment);
1574 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1578 /// ParseDirectiveAbort
1579 /// ::= .abort [... message ...]
1580 bool AsmParser::ParseDirectiveAbort() {
1581 // FIXME: Use loc from directive.
1582 SMLoc Loc = getLexer().getLoc();
1584 StringRef Str = ParseStringToEndOfStatement();
1585 if (getLexer().isNot(AsmToken::EndOfStatement))
1586 return TokError("unexpected token in '.abort' directive");
1591 Error(Loc, ".abort detected. Assembly stopping.");
1593 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1594 // FIXME: Actually abort assembly here.
1599 /// ParseDirectiveInclude
1600 /// ::= .include "filename"
1601 bool AsmParser::ParseDirectiveInclude() {
1602 if (getLexer().isNot(AsmToken::String))
1603 return TokError("expected string in '.include' directive");
1605 std::string Filename = getTok().getString();
1606 SMLoc IncludeLoc = getLexer().getLoc();
1609 if (getLexer().isNot(AsmToken::EndOfStatement))
1610 return TokError("unexpected token in '.include' directive");
1612 // Strip the quotes.
1613 Filename = Filename.substr(1, Filename.size()-2);
1615 // Attempt to switch the lexer to the included file before consuming the end
1616 // of statement to avoid losing it when we switch.
1617 if (EnterIncludeFile(Filename)) {
1618 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1625 /// ParseDirectiveIf
1626 /// ::= .if expression
1627 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1628 TheCondStack.push_back(TheCondState);
1629 TheCondState.TheCond = AsmCond::IfCond;
1630 if(TheCondState.Ignore) {
1631 EatToEndOfStatement();
1635 if (ParseAbsoluteExpression(ExprValue))
1638 if (getLexer().isNot(AsmToken::EndOfStatement))
1639 return TokError("unexpected token in '.if' directive");
1643 TheCondState.CondMet = ExprValue;
1644 TheCondState.Ignore = !TheCondState.CondMet;
1650 /// ParseDirectiveElseIf
1651 /// ::= .elseif expression
1652 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1653 if (TheCondState.TheCond != AsmCond::IfCond &&
1654 TheCondState.TheCond != AsmCond::ElseIfCond)
1655 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1657 TheCondState.TheCond = AsmCond::ElseIfCond;
1659 bool LastIgnoreState = false;
1660 if (!TheCondStack.empty())
1661 LastIgnoreState = TheCondStack.back().Ignore;
1662 if (LastIgnoreState || TheCondState.CondMet) {
1663 TheCondState.Ignore = true;
1664 EatToEndOfStatement();
1668 if (ParseAbsoluteExpression(ExprValue))
1671 if (getLexer().isNot(AsmToken::EndOfStatement))
1672 return TokError("unexpected token in '.elseif' directive");
1675 TheCondState.CondMet = ExprValue;
1676 TheCondState.Ignore = !TheCondState.CondMet;
1682 /// ParseDirectiveElse
1684 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1685 if (getLexer().isNot(AsmToken::EndOfStatement))
1686 return TokError("unexpected token in '.else' directive");
1690 if (TheCondState.TheCond != AsmCond::IfCond &&
1691 TheCondState.TheCond != AsmCond::ElseIfCond)
1692 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1694 TheCondState.TheCond = AsmCond::ElseCond;
1695 bool LastIgnoreState = false;
1696 if (!TheCondStack.empty())
1697 LastIgnoreState = TheCondStack.back().Ignore;
1698 if (LastIgnoreState || TheCondState.CondMet)
1699 TheCondState.Ignore = true;
1701 TheCondState.Ignore = false;
1706 /// ParseDirectiveEndIf
1708 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1709 if (getLexer().isNot(AsmToken::EndOfStatement))
1710 return TokError("unexpected token in '.endif' directive");
1714 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1715 TheCondStack.empty())
1716 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1718 if (!TheCondStack.empty()) {
1719 TheCondState = TheCondStack.back();
1720 TheCondStack.pop_back();
1726 /// ParseDirectiveFile
1727 /// ::= .file [number] string
1728 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1729 // FIXME: I'm not sure what this is.
1730 int64_t FileNumber = -1;
1731 if (getLexer().is(AsmToken::Integer)) {
1732 FileNumber = getTok().getIntVal();
1736 return TokError("file number less than one");
1739 if (getLexer().isNot(AsmToken::String))
1740 return TokError("unexpected token in '.file' directive");
1742 StringRef Filename = getTok().getString();
1743 Filename = Filename.substr(1, Filename.size()-2);
1746 if (getLexer().isNot(AsmToken::EndOfStatement))
1747 return TokError("unexpected token in '.file' directive");
1749 if (FileNumber == -1)
1750 getStreamer().EmitFileDirective(Filename);
1752 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1757 /// ParseDirectiveLine
1758 /// ::= .line [number]
1759 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1760 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1761 if (getLexer().isNot(AsmToken::Integer))
1762 return TokError("unexpected token in '.line' directive");
1764 int64_t LineNumber = getTok().getIntVal();
1768 // FIXME: Do something with the .line.
1771 if (getLexer().isNot(AsmToken::EndOfStatement))
1772 return TokError("unexpected token in '.line' directive");
1778 /// ParseDirectiveLoc
1779 /// ::= .loc number [number [number]]
1780 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1781 if (getLexer().isNot(AsmToken::Integer))
1782 return TokError("unexpected token in '.loc' directive");
1784 // FIXME: What are these fields?
1785 int64_t FileNumber = getTok().getIntVal();
1787 // FIXME: Validate file.
1790 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1791 if (getLexer().isNot(AsmToken::Integer))
1792 return TokError("unexpected token in '.loc' directive");
1794 int64_t Param2 = getTok().getIntVal();
1798 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1799 if (getLexer().isNot(AsmToken::Integer))
1800 return TokError("unexpected token in '.loc' directive");
1802 int64_t Param3 = getTok().getIntVal();
1806 // FIXME: Do something with the .loc.
1810 if (getLexer().isNot(AsmToken::EndOfStatement))
1811 return TokError("unexpected token in '.file' directive");
1816 /// ParseDirectiveMacrosOnOff
1819 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1820 SMLoc DirectiveLoc) {
1821 if (getLexer().isNot(AsmToken::EndOfStatement))
1822 return Error(getLexer().getLoc(),
1823 "unexpected token in '" + Directive + "' directive");
1825 getParser().MacrosEnabled = Directive == ".macros_on";
1830 /// ParseDirectiveMacro
1832 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1833 SMLoc DirectiveLoc) {
1835 if (getParser().ParseIdentifier(Name))
1836 return TokError("expected identifier in directive");
1838 if (getLexer().isNot(AsmToken::EndOfStatement))
1839 return TokError("unexpected token in '.macro' directive");
1841 // Eat the end of statement.
1844 AsmToken EndToken, StartToken = getTok();
1846 // Lex the macro definition.
1848 // Check whether we have reached the end of the file.
1849 if (getLexer().is(AsmToken::Eof))
1850 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1852 // Otherwise, check whether we have reach the .endmacro.
1853 if (getLexer().is(AsmToken::Identifier) &&
1854 (getTok().getIdentifier() == ".endm" ||
1855 getTok().getIdentifier() == ".endmacro")) {
1856 EndToken = getTok();
1858 if (getLexer().isNot(AsmToken::EndOfStatement))
1859 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1864 // Otherwise, scan til the end of the statement.
1865 getParser().EatToEndOfStatement();
1868 if (getParser().MacroMap.lookup(Name)) {
1869 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1872 const char *BodyStart = StartToken.getLoc().getPointer();
1873 const char *BodyEnd = EndToken.getLoc().getPointer();
1874 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1875 getParser().MacroMap[Name] = new Macro(Name, Body);
1879 /// ParseDirectiveEndMacro
1882 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1883 SMLoc DirectiveLoc) {
1884 if (getLexer().isNot(AsmToken::EndOfStatement))
1885 return TokError("unexpected token in '" + Directive + "' directive");
1887 // If we are inside a macro instantiation, terminate the current
1889 if (!getParser().ActiveMacros.empty()) {
1890 getParser().HandleMacroExit();
1894 // Otherwise, this .endmacro is a stray entry in the file; well formed
1895 // .endmacro directives are handled during the macro definition parsing.
1896 return TokError("unexpected '" + Directive + "' in file, "
1897 "no current macro definition");
1900 /// \brief Create an MCAsmParser instance.
1901 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1902 MCContext &C, MCStreamer &Out,
1903 const MCAsmInfo &MAI) {
1904 return new AsmParser(T, SM, C, Out, MAI);