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/MC/MCDwarf.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmParser.h"
40 /// \brief Helper class for tracking macro definitions.
46 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
49 /// \brief Helper class for storing information about an active macro
51 struct MacroInstantiation {
52 /// The macro being instantiated.
53 const Macro *TheMacro;
55 /// The macro instantiation with substitutions.
56 MemoryBuffer *Instantiation;
58 /// The location of the instantiation.
59 SMLoc InstantiationLoc;
61 /// The location where parsing should resume upon instantiation completion.
65 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66 const std::vector<std::vector<AsmToken> > &A);
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71 friend class GenericAsmParser;
73 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
74 void operator=(const AsmParser &); // DO NOT IMPLEMENT
80 MCAsmParserExtension *GenericParser;
81 MCAsmParserExtension *PlatformParser;
83 /// This is the current buffer index we're lexing from as managed by the
88 std::vector<AsmCond> TheCondStack;
90 /// DirectiveMap - This is a table handlers for directives. Each handler is
91 /// invoked after the directive identifier is read and is responsible for
92 /// parsing and validating the rest of the directive. The handler is passed
93 /// in the directive name and the location of the directive keyword.
94 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96 /// MacroMap - Map of currently defined macros.
97 StringMap<Macro*> MacroMap;
99 /// ActiveMacros - Stack of active macro instantiations.
100 std::vector<MacroInstantiation*> ActiveMacros;
102 /// Boolean tracking whether macro substitution is enabled.
103 unsigned MacrosEnabled : 1;
105 /// Flag tracking whether any errors have been encountered.
106 unsigned HadError : 1;
109 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110 const MCAsmInfo &MAI);
113 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 DirectiveHandler Handler) {
118 DirectiveMap[Directive] = std::make_pair(Object, Handler);
122 /// @name MCAsmParser Interface
125 virtual SourceMgr &getSourceManager() { return SrcMgr; }
126 virtual MCAsmLexer &getLexer() { return Lexer; }
127 virtual MCContext &getContext() { return Ctx; }
128 virtual MCStreamer &getStreamer() { return Out; }
130 virtual void Warning(SMLoc L, const Twine &Meg);
131 virtual bool Error(SMLoc L, const Twine &Msg);
133 const AsmToken &Lex();
135 bool ParseExpression(const MCExpr *&Res);
136 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseAbsoluteExpression(int64_t &Res);
143 void CheckForValidSection();
145 bool ParseStatement();
147 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148 void HandleMacroExit();
150 void PrintMacroInstantiations();
151 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
153 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
154 bool EnterIncludeFile(const std::string &Filename);
156 /// \brief Reset the current lexer position to that given by \arg Loc. The
157 /// current token is not set; clients should ensure Lex() is called
159 void JumpToLoc(SMLoc Loc);
161 void EatToEndOfStatement();
163 /// \brief Parse up to the end of statement and a return the contents from the
164 /// current token until the end of the statement; the current token on exit
165 /// will be either the EndOfStatement or EOF.
166 StringRef ParseStringToEndOfStatement();
168 bool ParseAssignment(StringRef Name);
170 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
171 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
175 /// and set \arg Res to the identifier contents.
176 bool ParseIdentifier(StringRef &Res);
178 // Directive Parsing.
179 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
180 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
181 bool ParseDirectiveFill(); // ".fill"
182 bool ParseDirectiveSpace(); // ".space"
183 bool ParseDirectiveSet(); // ".set"
184 bool ParseDirectiveOrg(); // ".org"
185 // ".align{,32}", ".p2align{,w,l}"
186 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
188 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
189 /// accepts a single symbol (which should be a label or an external).
190 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
191 bool ParseDirectiveELFType(); // ELF specific ".type"
193 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
195 bool ParseDirectiveAbort(); // ".abort"
196 bool ParseDirectiveInclude(); // ".include"
198 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
199 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
200 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
201 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
203 /// ParseEscapedString - Parse the current token as a string which may include
204 /// escaped characters and return the string contents.
205 bool ParseEscapedString(std::string &Data);
208 /// \brief Generic implementations of directive handling, etc. which is shared
209 /// (or the default, at least) for all assembler parser.
210 class GenericAsmParser : public MCAsmParserExtension {
211 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
212 void AddDirectiveHandler(StringRef Directive) {
213 getParser().AddDirectiveHandler(this, Directive,
214 HandleDirective<GenericAsmParser, Handler>);
218 GenericAsmParser() {}
220 AsmParser &getParser() {
221 return (AsmParser&) this->MCAsmParserExtension::getParser();
224 virtual void Initialize(MCAsmParser &Parser) {
225 // Call the base implementation.
226 this->MCAsmParserExtension::Initialize(Parser);
228 // Debugging directives.
229 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
230 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
231 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
243 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
244 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
245 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
247 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
248 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
249 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
256 extern MCAsmParserExtension *createDarwinAsmParser();
257 extern MCAsmParserExtension *createELFAsmParser();
261 enum { DEFAULT_ADDRSPACE = 0 };
263 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
264 MCStreamer &_Out, const MCAsmInfo &_MAI)
265 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
266 GenericParser(new GenericAsmParser), PlatformParser(0),
267 CurBuffer(0), MacrosEnabled(true) {
268 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
270 // Initialize the generic parser.
271 GenericParser->Initialize(*this);
273 // Initialize the platform / file format parser.
275 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
277 if (_MAI.hasSubsectionsViaSymbols()) {
278 PlatformParser = createDarwinAsmParser();
279 PlatformParser->Initialize(*this);
281 PlatformParser = createELFAsmParser();
282 PlatformParser->Initialize(*this);
286 AsmParser::~AsmParser() {
287 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
289 // Destroy any macros.
290 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
291 ie = MacroMap.end(); it != ie; ++it)
292 delete it->getValue();
294 delete PlatformParser;
295 delete GenericParser;
298 void AsmParser::PrintMacroInstantiations() {
299 // Print the active macro instantiation stack.
300 for (std::vector<MacroInstantiation*>::const_reverse_iterator
301 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
302 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
306 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
307 PrintMessage(L, Msg.str(), "warning");
308 PrintMacroInstantiations();
311 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
313 PrintMessage(L, Msg.str(), "error");
314 PrintMacroInstantiations();
318 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
319 const char *Type) const {
320 SrcMgr.PrintMessage(Loc, Msg, Type);
323 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
324 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
330 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
335 void AsmParser::JumpToLoc(SMLoc Loc) {
336 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
337 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
340 const AsmToken &AsmParser::Lex() {
341 const AsmToken *tok = &Lexer.Lex();
343 if (tok->is(AsmToken::Eof)) {
344 // If this is the end of an included file, pop the parent file off the
346 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
347 if (ParentIncludeLoc != SMLoc()) {
348 JumpToLoc(ParentIncludeLoc);
353 if (tok->is(AsmToken::Error))
354 Error(Lexer.getErrLoc(), Lexer.getErr());
359 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
360 // Create the initial section, if requested.
362 // FIXME: Target hook & command line option for initial section.
363 if (!NoInitialTextSection)
364 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
365 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
366 0, SectionKind::getText()));
372 AsmCond StartingCondState = TheCondState;
374 // While we have input, parse each statement.
375 while (Lexer.isNot(AsmToken::Eof)) {
376 if (!ParseStatement()) continue;
378 // We had an error, validate that one was emitted and recover by skipping to
380 assert(HadError && "Parse statement returned an error, but none emitted!");
381 EatToEndOfStatement();
384 if (TheCondState.TheCond != StartingCondState.TheCond ||
385 TheCondState.Ignore != StartingCondState.Ignore)
386 return TokError("unmatched .ifs or .elses");
388 // Check to see there are no empty DwarfFile slots.
389 const std::vector<MCDwarfFile *> &MCDwarfFiles =
390 getContext().getMCDwarfFiles();
391 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
392 if (!MCDwarfFiles[i])
393 TokError("unassigned file number: " + Twine(i) + " for .file directives");
396 // Finalize the output stream if there are no errors and if the client wants
398 if (!HadError && !NoFinalize)
404 void AsmParser::CheckForValidSection() {
405 if (!getStreamer().getCurrentSection()) {
406 TokError("expected section directive before assembly directive");
407 Out.SwitchSection(Ctx.getMachOSection(
409 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
410 0, SectionKind::getText()));
414 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
415 void AsmParser::EatToEndOfStatement() {
416 while (Lexer.isNot(AsmToken::EndOfStatement) &&
417 Lexer.isNot(AsmToken::Eof))
421 if (Lexer.is(AsmToken::EndOfStatement))
425 StringRef AsmParser::ParseStringToEndOfStatement() {
426 const char *Start = getTok().getLoc().getPointer();
428 while (Lexer.isNot(AsmToken::EndOfStatement) &&
429 Lexer.isNot(AsmToken::Eof))
432 const char *End = getTok().getLoc().getPointer();
433 return StringRef(Start, End - Start);
436 /// ParseParenExpr - Parse a paren expression and return it.
437 /// NOTE: This assumes the leading '(' has already been consumed.
439 /// parenexpr ::= expr)
441 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
442 if (ParseExpression(Res)) return true;
443 if (Lexer.isNot(AsmToken::RParen))
444 return TokError("expected ')' in parentheses expression");
445 EndLoc = Lexer.getLoc();
450 /// ParsePrimaryExpr - Parse a primary expression and return it.
451 /// primaryexpr ::= (parenexpr
452 /// primaryexpr ::= symbol
453 /// primaryexpr ::= number
454 /// primaryexpr ::= '.'
455 /// primaryexpr ::= ~,+,- primaryexpr
456 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
457 switch (Lexer.getKind()) {
459 return TokError("unknown token in expression");
460 case AsmToken::Exclaim:
461 Lex(); // Eat the operator.
462 if (ParsePrimaryExpr(Res, EndLoc))
464 Res = MCUnaryExpr::CreateLNot(Res, getContext());
466 case AsmToken::Dollar:
467 case AsmToken::String:
468 case AsmToken::Identifier: {
469 EndLoc = Lexer.getLoc();
471 StringRef Identifier;
472 if (ParseIdentifier(Identifier))
475 // This is a symbol reference.
476 std::pair<StringRef, StringRef> Split = Identifier.split('@');
477 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
479 // Mark the symbol as used in an expression.
480 Sym->setUsedInExpr(true);
482 // Lookup the symbol variant if used.
483 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
484 if (Split.first.size() != Identifier.size())
485 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
487 // If this is an absolute variable reference, substitute it now to preserve
488 // semantics in the face of reassignment.
489 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
491 return Error(EndLoc, "unexpected modified on variable reference");
493 Res = Sym->getVariableValue();
497 // Otherwise create a symbol ref.
498 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
501 case AsmToken::Integer: {
502 SMLoc Loc = getTok().getLoc();
503 int64_t IntVal = getTok().getIntVal();
504 Res = MCConstantExpr::Create(IntVal, getContext());
505 EndLoc = Lexer.getLoc();
507 // Look for 'b' or 'f' following an Integer as a directional label
508 if (Lexer.getKind() == AsmToken::Identifier) {
509 StringRef IDVal = getTok().getString();
510 if (IDVal == "f" || IDVal == "b"){
511 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
512 IDVal == "f" ? 1 : 0);
513 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
515 if(IDVal == "b" && Sym->isUndefined())
516 return Error(Loc, "invalid reference to undefined symbol");
517 EndLoc = Lexer.getLoc();
518 Lex(); // Eat identifier.
523 case AsmToken::Dot: {
524 // This is a '.' reference, which references the current PC. Emit a
525 // temporary label to the streamer and refer to it.
526 MCSymbol *Sym = Ctx.CreateTempSymbol();
528 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
529 EndLoc = Lexer.getLoc();
530 Lex(); // Eat identifier.
534 case AsmToken::LParen:
535 Lex(); // Eat the '('.
536 return ParseParenExpr(Res, EndLoc);
537 case AsmToken::Minus:
538 Lex(); // Eat the operator.
539 if (ParsePrimaryExpr(Res, EndLoc))
541 Res = MCUnaryExpr::CreateMinus(Res, getContext());
544 Lex(); // Eat the operator.
545 if (ParsePrimaryExpr(Res, EndLoc))
547 Res = MCUnaryExpr::CreatePlus(Res, getContext());
549 case AsmToken::Tilde:
550 Lex(); // Eat the operator.
551 if (ParsePrimaryExpr(Res, EndLoc))
553 Res = MCUnaryExpr::CreateNot(Res, getContext());
558 bool AsmParser::ParseExpression(const MCExpr *&Res) {
560 return ParseExpression(Res, EndLoc);
563 /// ParseExpression - Parse an expression and return it.
565 /// expr ::= expr +,- expr -> lowest.
566 /// expr ::= expr |,^,&,! expr -> middle.
567 /// expr ::= expr *,/,%,<<,>> expr -> highest.
568 /// expr ::= primaryexpr
570 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
571 // Parse the expression.
573 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
576 // Try to constant fold it up front, if possible.
578 if (Res->EvaluateAsAbsolute(Value))
579 Res = MCConstantExpr::Create(Value, getContext());
584 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
586 return ParseParenExpr(Res, EndLoc) ||
587 ParseBinOpRHS(1, Res, EndLoc);
590 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
593 SMLoc StartLoc = Lexer.getLoc();
594 if (ParseExpression(Expr))
597 if (!Expr->EvaluateAsAbsolute(Res))
598 return Error(StartLoc, "expected absolute expression");
603 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
604 MCBinaryExpr::Opcode &Kind) {
607 return 0; // not a binop.
609 // Lowest Precedence: &&, ||
610 case AsmToken::AmpAmp:
611 Kind = MCBinaryExpr::LAnd;
613 case AsmToken::PipePipe:
614 Kind = MCBinaryExpr::LOr;
617 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
619 Kind = MCBinaryExpr::Add;
621 case AsmToken::Minus:
622 Kind = MCBinaryExpr::Sub;
624 case AsmToken::EqualEqual:
625 Kind = MCBinaryExpr::EQ;
627 case AsmToken::ExclaimEqual:
628 case AsmToken::LessGreater:
629 Kind = MCBinaryExpr::NE;
632 Kind = MCBinaryExpr::LT;
634 case AsmToken::LessEqual:
635 Kind = MCBinaryExpr::LTE;
637 case AsmToken::Greater:
638 Kind = MCBinaryExpr::GT;
640 case AsmToken::GreaterEqual:
641 Kind = MCBinaryExpr::GTE;
644 // Intermediate Precedence: |, &, ^
646 // FIXME: gas seems to support '!' as an infix operator?
648 Kind = MCBinaryExpr::Or;
650 case AsmToken::Caret:
651 Kind = MCBinaryExpr::Xor;
654 Kind = MCBinaryExpr::And;
657 // Highest Precedence: *, /, %, <<, >>
659 Kind = MCBinaryExpr::Mul;
661 case AsmToken::Slash:
662 Kind = MCBinaryExpr::Div;
664 case AsmToken::Percent:
665 Kind = MCBinaryExpr::Mod;
667 case AsmToken::LessLess:
668 Kind = MCBinaryExpr::Shl;
670 case AsmToken::GreaterGreater:
671 Kind = MCBinaryExpr::Shr;
677 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
678 /// Res contains the LHS of the expression on input.
679 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
682 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
683 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
685 // If the next token is lower precedence than we are allowed to eat, return
686 // successfully with what we ate already.
687 if (TokPrec < Precedence)
692 // Eat the next primary expression.
694 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
696 // If BinOp binds less tightly with RHS than the operator after RHS, let
697 // the pending operator take RHS as its LHS.
698 MCBinaryExpr::Opcode Dummy;
699 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
700 if (TokPrec < NextTokPrec) {
701 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
704 // Merge LHS and RHS according to operator.
705 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
713 /// ::= EndOfStatement
714 /// ::= Label* Directive ...Operands... EndOfStatement
715 /// ::= Label* Identifier OperandList* EndOfStatement
716 bool AsmParser::ParseStatement() {
717 if (Lexer.is(AsmToken::EndOfStatement)) {
723 // Statements always start with an identifier.
724 AsmToken ID = getTok();
725 SMLoc IDLoc = ID.getLoc();
727 int64_t LocalLabelVal = -1;
728 // GUESS allow an integer followed by a ':' as a directional local label
729 if (Lexer.is(AsmToken::Integer)) {
730 LocalLabelVal = getTok().getIntVal();
731 if (LocalLabelVal < 0) {
732 if (!TheCondState.Ignore)
733 return TokError("unexpected token at start of statement");
737 IDVal = getTok().getString();
738 Lex(); // Consume the integer token to be used as an identifier token.
739 if (Lexer.getKind() != AsmToken::Colon) {
740 if (!TheCondState.Ignore)
741 return TokError("unexpected token at start of statement");
745 else if (ParseIdentifier(IDVal)) {
746 if (!TheCondState.Ignore)
747 return TokError("unexpected token at start of statement");
751 // Handle conditional assembly here before checking for skipping. We
752 // have to do this so that .endif isn't skipped in a ".if 0" block for
755 return ParseDirectiveIf(IDLoc);
756 if (IDVal == ".elseif")
757 return ParseDirectiveElseIf(IDLoc);
758 if (IDVal == ".else")
759 return ParseDirectiveElse(IDLoc);
760 if (IDVal == ".endif")
761 return ParseDirectiveEndIf(IDLoc);
763 // If we are in a ".if 0" block, ignore this statement.
764 if (TheCondState.Ignore) {
765 EatToEndOfStatement();
769 // FIXME: Recurse on local labels?
771 // See what kind of statement we have.
772 switch (Lexer.getKind()) {
773 case AsmToken::Colon: {
774 CheckForValidSection();
776 // identifier ':' -> Label.
779 // Diagnose attempt to use a variable as a label.
781 // FIXME: Diagnostics. Note the location of the definition as a label.
782 // FIXME: This doesn't diagnose assignment to a symbol which has been
783 // implicitly marked as external.
785 if (LocalLabelVal == -1)
786 Sym = getContext().GetOrCreateSymbol(IDVal);
788 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
789 if (!Sym->isUndefined() || Sym->isVariable())
790 return Error(IDLoc, "invalid symbol redefinition");
795 // Consume any end of statement token, if present, to avoid spurious
796 // AddBlankLine calls().
797 if (Lexer.is(AsmToken::EndOfStatement)) {
799 if (Lexer.is(AsmToken::Eof))
803 return ParseStatement();
806 case AsmToken::Equal:
807 // identifier '=' ... -> assignment statement
810 return ParseAssignment(IDVal);
812 default: // Normal instruction or directive.
816 // If macros are enabled, check to see if this is a macro instantiation.
818 if (const Macro *M = MacroMap.lookup(IDVal))
819 return HandleMacroEntry(IDVal, IDLoc, M);
821 // Otherwise, we have a normal instruction or directive.
822 if (IDVal[0] == '.') {
823 // Assembler features
825 return ParseDirectiveSet();
829 if (IDVal == ".ascii")
830 return ParseDirectiveAscii(false);
831 if (IDVal == ".asciz")
832 return ParseDirectiveAscii(true);
834 if (IDVal == ".byte")
835 return ParseDirectiveValue(1);
836 if (IDVal == ".short")
837 return ParseDirectiveValue(2);
838 if (IDVal == ".long")
839 return ParseDirectiveValue(4);
840 if (IDVal == ".quad")
841 return ParseDirectiveValue(8);
843 if (IDVal == ".align") {
844 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
845 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
847 if (IDVal == ".align32") {
848 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
849 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
851 if (IDVal == ".balign")
852 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
853 if (IDVal == ".balignw")
854 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
855 if (IDVal == ".balignl")
856 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
857 if (IDVal == ".p2align")
858 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
859 if (IDVal == ".p2alignw")
860 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
861 if (IDVal == ".p2alignl")
862 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
865 return ParseDirectiveOrg();
867 if (IDVal == ".fill")
868 return ParseDirectiveFill();
869 if (IDVal == ".space")
870 return ParseDirectiveSpace();
872 // Symbol attribute directives
874 if (IDVal == ".globl" || IDVal == ".global")
875 return ParseDirectiveSymbolAttribute(MCSA_Global);
876 if (IDVal == ".hidden")
877 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
878 if (IDVal == ".indirect_symbol")
879 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
880 if (IDVal == ".internal")
881 return ParseDirectiveSymbolAttribute(MCSA_Internal);
882 if (IDVal == ".lazy_reference")
883 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
884 if (IDVal == ".no_dead_strip")
885 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
886 if (IDVal == ".private_extern")
887 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
888 if (IDVal == ".protected")
889 return ParseDirectiveSymbolAttribute(MCSA_Protected);
890 if (IDVal == ".reference")
891 return ParseDirectiveSymbolAttribute(MCSA_Reference);
892 if (IDVal == ".type")
893 return ParseDirectiveELFType();
894 if (IDVal == ".weak")
895 return ParseDirectiveSymbolAttribute(MCSA_Weak);
896 if (IDVal == ".weak_definition")
897 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
898 if (IDVal == ".weak_reference")
899 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
900 if (IDVal == ".weak_def_can_be_hidden")
901 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
903 if (IDVal == ".comm")
904 return ParseDirectiveComm(/*IsLocal=*/false);
905 if (IDVal == ".lcomm")
906 return ParseDirectiveComm(/*IsLocal=*/true);
908 if (IDVal == ".abort")
909 return ParseDirectiveAbort();
910 if (IDVal == ".include")
911 return ParseDirectiveInclude();
913 // Look up the handler in the handler table.
914 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
915 DirectiveMap.lookup(IDVal);
917 return (*Handler.second)(Handler.first, IDVal, IDLoc);
919 // Target hook for parsing target specific directives.
920 if (!getTargetParser().ParseDirective(ID))
923 Warning(IDLoc, "ignoring directive for now");
924 EatToEndOfStatement();
928 CheckForValidSection();
930 // Canonicalize the opcode to lower case.
931 SmallString<128> Opcode;
932 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
933 Opcode.push_back(tolower(IDVal[i]));
935 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
936 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
939 // Dump the parsed representation, if requested.
940 if (getShowParsedOperands()) {
941 SmallString<256> Str;
942 raw_svector_ostream OS(Str);
943 OS << "parsed instruction: [";
944 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
947 ParsedOperands[i]->dump(OS);
951 PrintMessage(IDLoc, OS.str(), "note");
954 // If parsing succeeded, match the instruction.
957 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
958 // Emit the instruction on success.
959 Out.EmitInstruction(Inst);
964 // Free any parsed operands.
965 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
966 delete ParsedOperands[i];
968 // Don't skip the rest of the line, the instruction parser is responsible for
973 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
974 const std::vector<std::vector<AsmToken> > &A)
975 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
977 // Macro instantiation is lexical, unfortunately. We construct a new buffer
978 // to hold the macro body with substitutions.
979 SmallString<256> Buf;
980 raw_svector_ostream OS(Buf);
982 StringRef Body = M->Body;
983 while (!Body.empty()) {
984 // Scan for the next substitution.
985 std::size_t End = Body.size(), Pos = 0;
986 for (; Pos != End; ++Pos) {
987 // Check for a substitution or escape.
988 if (Body[Pos] != '$' || Pos + 1 == End)
991 char Next = Body[Pos + 1];
992 if (Next == '$' || Next == 'n' || isdigit(Next))
997 OS << Body.slice(0, Pos);
999 // Check if we reached the end.
1003 switch (Body[Pos+1]) {
1009 // $n => number of arguments
1014 // $[0-9] => argument
1016 // Missing arguments are ignored.
1017 unsigned Index = Body[Pos+1] - '0';
1018 if (Index >= A.size())
1021 // Otherwise substitute with the token values, with spaces eliminated.
1022 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1023 ie = A[Index].end(); it != ie; ++it)
1024 OS << it->getString();
1029 // Update the scan point.
1030 Body = Body.substr(Pos + 2);
1033 // We include the .endmacro in the buffer as our queue to exit the macro
1035 OS << ".endmacro\n";
1037 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1040 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1042 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1043 // this, although we should protect against infinite loops.
1044 if (ActiveMacros.size() == 20)
1045 return TokError("macros cannot be nested more than 20 levels deep");
1047 // Parse the macro instantiation arguments.
1048 std::vector<std::vector<AsmToken> > MacroArguments;
1049 MacroArguments.push_back(std::vector<AsmToken>());
1050 unsigned ParenLevel = 0;
1052 if (Lexer.is(AsmToken::Eof))
1053 return TokError("unexpected token in macro instantiation");
1054 if (Lexer.is(AsmToken::EndOfStatement))
1057 // If we aren't inside parentheses and this is a comma, start a new token
1059 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1060 MacroArguments.push_back(std::vector<AsmToken>());
1062 // Adjust the current parentheses level.
1063 if (Lexer.is(AsmToken::LParen))
1065 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1068 // Append the token to the current argument list.
1069 MacroArguments.back().push_back(getTok());
1074 // Create the macro instantiation object and add to the current macro
1075 // instantiation stack.
1076 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1079 ActiveMacros.push_back(MI);
1081 // Jump to the macro instantiation and prime the lexer.
1082 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1083 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1089 void AsmParser::HandleMacroExit() {
1090 // Jump to the EndOfStatement we should return to, and consume it.
1091 JumpToLoc(ActiveMacros.back()->ExitLoc);
1094 // Pop the instantiation entry.
1095 delete ActiveMacros.back();
1096 ActiveMacros.pop_back();
1099 bool AsmParser::ParseAssignment(StringRef Name) {
1100 // FIXME: Use better location, we should use proper tokens.
1101 SMLoc EqualLoc = Lexer.getLoc();
1103 const MCExpr *Value;
1104 if (ParseExpression(Value))
1107 if (Lexer.isNot(AsmToken::EndOfStatement))
1108 return TokError("unexpected token in assignment");
1110 // Eat the end of statement marker.
1113 // Validate that the LHS is allowed to be a variable (either it has not been
1114 // used as a symbol, or it is an absolute symbol).
1115 MCSymbol *Sym = getContext().LookupSymbol(Name);
1117 // Diagnose assignment to a label.
1119 // FIXME: Diagnostics. Note the location of the definition as a label.
1120 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1121 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1122 ; // Allow redefinitions of undefined symbols only used in directives.
1123 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1124 return Error(EqualLoc, "redefinition of '" + Name + "'");
1125 else if (!Sym->isVariable())
1126 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1127 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1128 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1131 Sym = getContext().GetOrCreateSymbol(Name);
1133 // FIXME: Handle '.'.
1135 Sym->setUsedInExpr(true);
1137 // Do the assignment.
1138 Out.EmitAssignment(Sym, Value);
1143 /// ParseIdentifier:
1146 bool AsmParser::ParseIdentifier(StringRef &Res) {
1147 // The assembler has relaxed rules for accepting identifiers, in particular we
1148 // allow things like '.globl $foo', which would normally be separate
1149 // tokens. At this level, we have already lexed so we cannot (currently)
1150 // handle this as a context dependent token, instead we detect adjacent tokens
1151 // and return the combined identifier.
1152 if (Lexer.is(AsmToken::Dollar)) {
1153 SMLoc DollarLoc = getLexer().getLoc();
1155 // Consume the dollar sign, and check for a following identifier.
1157 if (Lexer.isNot(AsmToken::Identifier))
1160 // We have a '$' followed by an identifier, make sure they are adjacent.
1161 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1164 // Construct the joined identifier and consume the token.
1165 Res = StringRef(DollarLoc.getPointer(),
1166 getTok().getIdentifier().size() + 1);
1171 if (Lexer.isNot(AsmToken::Identifier) &&
1172 Lexer.isNot(AsmToken::String))
1175 Res = getTok().getIdentifier();
1177 Lex(); // Consume the identifier token.
1182 /// ParseDirectiveSet:
1183 /// ::= .set identifier ',' expression
1184 bool AsmParser::ParseDirectiveSet() {
1187 if (ParseIdentifier(Name))
1188 return TokError("expected identifier after '.set' directive");
1190 if (getLexer().isNot(AsmToken::Comma))
1191 return TokError("unexpected token in '.set'");
1194 return ParseAssignment(Name);
1197 bool AsmParser::ParseEscapedString(std::string &Data) {
1198 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1201 StringRef Str = getTok().getStringContents();
1202 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1203 if (Str[i] != '\\') {
1208 // Recognize escaped characters. Note that this escape semantics currently
1209 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1212 return TokError("unexpected backslash at end of string");
1214 // Recognize octal sequences.
1215 if ((unsigned) (Str[i] - '0') <= 7) {
1216 // Consume up to three octal characters.
1217 unsigned Value = Str[i] - '0';
1219 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1221 Value = Value * 8 + (Str[i] - '0');
1223 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1225 Value = Value * 8 + (Str[i] - '0');
1230 return TokError("invalid octal escape sequence (out of range)");
1232 Data += (unsigned char) Value;
1236 // Otherwise recognize individual escapes.
1239 // Just reject invalid escape sequences for now.
1240 return TokError("invalid escape sequence (unrecognized character)");
1242 case 'b': Data += '\b'; break;
1243 case 'f': Data += '\f'; break;
1244 case 'n': Data += '\n'; break;
1245 case 'r': Data += '\r'; break;
1246 case 't': Data += '\t'; break;
1247 case '"': Data += '"'; break;
1248 case '\\': Data += '\\'; break;
1255 /// ParseDirectiveAscii:
1256 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1257 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1258 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1259 CheckForValidSection();
1262 if (getLexer().isNot(AsmToken::String))
1263 return TokError("expected string in '.ascii' or '.asciz' directive");
1266 if (ParseEscapedString(Data))
1269 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1271 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1275 if (getLexer().is(AsmToken::EndOfStatement))
1278 if (getLexer().isNot(AsmToken::Comma))
1279 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1288 /// ParseDirectiveValue
1289 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1290 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1291 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1292 CheckForValidSection();
1295 const MCExpr *Value;
1296 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1297 if (ParseExpression(Value))
1300 // Special case constant expressions to match code generator.
1301 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1302 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1304 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1306 if (getLexer().is(AsmToken::EndOfStatement))
1309 // FIXME: Improve diagnostic.
1310 if (getLexer().isNot(AsmToken::Comma))
1311 return TokError("unexpected token in directive");
1320 /// ParseDirectiveSpace
1321 /// ::= .space expression [ , expression ]
1322 bool AsmParser::ParseDirectiveSpace() {
1323 CheckForValidSection();
1326 if (ParseAbsoluteExpression(NumBytes))
1329 int64_t FillExpr = 0;
1330 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1331 if (getLexer().isNot(AsmToken::Comma))
1332 return TokError("unexpected token in '.space' directive");
1335 if (ParseAbsoluteExpression(FillExpr))
1338 if (getLexer().isNot(AsmToken::EndOfStatement))
1339 return TokError("unexpected token in '.space' directive");
1345 return TokError("invalid number of bytes in '.space' directive");
1347 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1348 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1353 /// ParseDirectiveFill
1354 /// ::= .fill expression , expression , expression
1355 bool AsmParser::ParseDirectiveFill() {
1356 CheckForValidSection();
1359 if (ParseAbsoluteExpression(NumValues))
1362 if (getLexer().isNot(AsmToken::Comma))
1363 return TokError("unexpected token in '.fill' directive");
1367 if (ParseAbsoluteExpression(FillSize))
1370 if (getLexer().isNot(AsmToken::Comma))
1371 return TokError("unexpected token in '.fill' directive");
1375 if (ParseAbsoluteExpression(FillExpr))
1378 if (getLexer().isNot(AsmToken::EndOfStatement))
1379 return TokError("unexpected token in '.fill' directive");
1383 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1384 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1386 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1387 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1392 /// ParseDirectiveOrg
1393 /// ::= .org expression [ , expression ]
1394 bool AsmParser::ParseDirectiveOrg() {
1395 CheckForValidSection();
1397 const MCExpr *Offset;
1398 if (ParseExpression(Offset))
1401 // Parse optional fill expression.
1402 int64_t FillExpr = 0;
1403 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1404 if (getLexer().isNot(AsmToken::Comma))
1405 return TokError("unexpected token in '.org' directive");
1408 if (ParseAbsoluteExpression(FillExpr))
1411 if (getLexer().isNot(AsmToken::EndOfStatement))
1412 return TokError("unexpected token in '.org' directive");
1417 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1418 // has to be relative to the current section.
1419 getStreamer().EmitValueToOffset(Offset, FillExpr);
1424 /// ParseDirectiveAlign
1425 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1426 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1427 CheckForValidSection();
1429 SMLoc AlignmentLoc = getLexer().getLoc();
1431 if (ParseAbsoluteExpression(Alignment))
1435 bool HasFillExpr = false;
1436 int64_t FillExpr = 0;
1437 int64_t MaxBytesToFill = 0;
1438 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1439 if (getLexer().isNot(AsmToken::Comma))
1440 return TokError("unexpected token in directive");
1443 // The fill expression can be omitted while specifying a maximum number of
1444 // alignment bytes, e.g:
1446 if (getLexer().isNot(AsmToken::Comma)) {
1448 if (ParseAbsoluteExpression(FillExpr))
1452 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1453 if (getLexer().isNot(AsmToken::Comma))
1454 return TokError("unexpected token in directive");
1457 MaxBytesLoc = getLexer().getLoc();
1458 if (ParseAbsoluteExpression(MaxBytesToFill))
1461 if (getLexer().isNot(AsmToken::EndOfStatement))
1462 return TokError("unexpected token in directive");
1471 // Compute alignment in bytes.
1473 // FIXME: Diagnose overflow.
1474 if (Alignment >= 32) {
1475 Error(AlignmentLoc, "invalid alignment value");
1479 Alignment = 1ULL << Alignment;
1482 // Diagnose non-sensical max bytes to align.
1483 if (MaxBytesLoc.isValid()) {
1484 if (MaxBytesToFill < 1) {
1485 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1486 "many bytes, ignoring maximum bytes expression");
1490 if (MaxBytesToFill >= Alignment) {
1491 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1497 // Check whether we should use optimal code alignment for this .align
1500 // FIXME: This should be using a target hook.
1501 bool UseCodeAlign = false;
1502 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1503 getStreamer().getCurrentSection()))
1504 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1505 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1506 ValueSize == 1 && UseCodeAlign) {
1507 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1509 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1510 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1517 /// ParseDirectiveSymbolAttribute
1518 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1519 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1520 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1524 if (ParseIdentifier(Name))
1525 return TokError("expected identifier in directive");
1527 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1529 getStreamer().EmitSymbolAttribute(Sym, Attr);
1531 if (getLexer().is(AsmToken::EndOfStatement))
1534 if (getLexer().isNot(AsmToken::Comma))
1535 return TokError("unexpected token in directive");
1544 /// ParseDirectiveELFType
1545 /// ::= .type identifier , @attribute
1546 bool AsmParser::ParseDirectiveELFType() {
1548 if (ParseIdentifier(Name))
1549 return TokError("expected identifier in directive");
1551 // Handle the identifier as the key symbol.
1552 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1554 if (getLexer().isNot(AsmToken::Comma))
1555 return TokError("unexpected token in '.type' directive");
1558 if (getLexer().isNot(AsmToken::At))
1559 return TokError("expected '@' before type");
1565 TypeLoc = getLexer().getLoc();
1566 if (ParseIdentifier(Type))
1567 return TokError("expected symbol type in directive");
1569 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1570 .Case("function", MCSA_ELF_TypeFunction)
1571 .Case("object", MCSA_ELF_TypeObject)
1572 .Case("tls_object", MCSA_ELF_TypeTLS)
1573 .Case("common", MCSA_ELF_TypeCommon)
1574 .Case("notype", MCSA_ELF_TypeNoType)
1575 .Default(MCSA_Invalid);
1577 if (Attr == MCSA_Invalid)
1578 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1580 if (getLexer().isNot(AsmToken::EndOfStatement))
1581 return TokError("unexpected token in '.type' directive");
1585 getStreamer().EmitSymbolAttribute(Sym, Attr);
1590 /// ParseDirectiveComm
1591 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1592 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1593 CheckForValidSection();
1595 SMLoc IDLoc = getLexer().getLoc();
1597 if (ParseIdentifier(Name))
1598 return TokError("expected identifier in directive");
1600 // Handle the identifier as the key symbol.
1601 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1603 if (getLexer().isNot(AsmToken::Comma))
1604 return TokError("unexpected token in directive");
1608 SMLoc SizeLoc = getLexer().getLoc();
1609 if (ParseAbsoluteExpression(Size))
1612 int64_t Pow2Alignment = 0;
1613 SMLoc Pow2AlignmentLoc;
1614 if (getLexer().is(AsmToken::Comma)) {
1616 Pow2AlignmentLoc = getLexer().getLoc();
1617 if (ParseAbsoluteExpression(Pow2Alignment))
1620 // If this target takes alignments in bytes (not log) validate and convert.
1621 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1622 if (!isPowerOf2_64(Pow2Alignment))
1623 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1624 Pow2Alignment = Log2_64(Pow2Alignment);
1628 if (getLexer().isNot(AsmToken::EndOfStatement))
1629 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1633 // NOTE: a size of zero for a .comm should create a undefined symbol
1634 // but a size of .lcomm creates a bss symbol of size zero.
1636 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1637 "be less than zero");
1639 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1640 // may internally end up wanting an alignment in bytes.
1641 // FIXME: Diagnose overflow.
1642 if (Pow2Alignment < 0)
1643 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1644 "alignment, can't be less than zero");
1646 if (!Sym->isUndefined())
1647 return Error(IDLoc, "invalid symbol redefinition");
1649 // '.lcomm' is equivalent to '.zerofill'.
1650 // Create the Symbol as a common or local common with Size and Pow2Alignment
1652 getStreamer().EmitZerofill(Ctx.getMachOSection(
1653 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1654 0, SectionKind::getBSS()),
1655 Sym, Size, 1 << Pow2Alignment);
1659 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1663 /// ParseDirectiveAbort
1664 /// ::= .abort [... message ...]
1665 bool AsmParser::ParseDirectiveAbort() {
1666 // FIXME: Use loc from directive.
1667 SMLoc Loc = getLexer().getLoc();
1669 StringRef Str = ParseStringToEndOfStatement();
1670 if (getLexer().isNot(AsmToken::EndOfStatement))
1671 return TokError("unexpected token in '.abort' directive");
1676 Error(Loc, ".abort detected. Assembly stopping.");
1678 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1679 // FIXME: Actually abort assembly here.
1684 /// ParseDirectiveInclude
1685 /// ::= .include "filename"
1686 bool AsmParser::ParseDirectiveInclude() {
1687 if (getLexer().isNot(AsmToken::String))
1688 return TokError("expected string in '.include' directive");
1690 std::string Filename = getTok().getString();
1691 SMLoc IncludeLoc = getLexer().getLoc();
1694 if (getLexer().isNot(AsmToken::EndOfStatement))
1695 return TokError("unexpected token in '.include' directive");
1697 // Strip the quotes.
1698 Filename = Filename.substr(1, Filename.size()-2);
1700 // Attempt to switch the lexer to the included file before consuming the end
1701 // of statement to avoid losing it when we switch.
1702 if (EnterIncludeFile(Filename)) {
1703 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1710 /// ParseDirectiveIf
1711 /// ::= .if expression
1712 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1713 TheCondStack.push_back(TheCondState);
1714 TheCondState.TheCond = AsmCond::IfCond;
1715 if(TheCondState.Ignore) {
1716 EatToEndOfStatement();
1720 if (ParseAbsoluteExpression(ExprValue))
1723 if (getLexer().isNot(AsmToken::EndOfStatement))
1724 return TokError("unexpected token in '.if' directive");
1728 TheCondState.CondMet = ExprValue;
1729 TheCondState.Ignore = !TheCondState.CondMet;
1735 /// ParseDirectiveElseIf
1736 /// ::= .elseif expression
1737 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1738 if (TheCondState.TheCond != AsmCond::IfCond &&
1739 TheCondState.TheCond != AsmCond::ElseIfCond)
1740 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1742 TheCondState.TheCond = AsmCond::ElseIfCond;
1744 bool LastIgnoreState = false;
1745 if (!TheCondStack.empty())
1746 LastIgnoreState = TheCondStack.back().Ignore;
1747 if (LastIgnoreState || TheCondState.CondMet) {
1748 TheCondState.Ignore = true;
1749 EatToEndOfStatement();
1753 if (ParseAbsoluteExpression(ExprValue))
1756 if (getLexer().isNot(AsmToken::EndOfStatement))
1757 return TokError("unexpected token in '.elseif' directive");
1760 TheCondState.CondMet = ExprValue;
1761 TheCondState.Ignore = !TheCondState.CondMet;
1767 /// ParseDirectiveElse
1769 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1770 if (getLexer().isNot(AsmToken::EndOfStatement))
1771 return TokError("unexpected token in '.else' directive");
1775 if (TheCondState.TheCond != AsmCond::IfCond &&
1776 TheCondState.TheCond != AsmCond::ElseIfCond)
1777 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1779 TheCondState.TheCond = AsmCond::ElseCond;
1780 bool LastIgnoreState = false;
1781 if (!TheCondStack.empty())
1782 LastIgnoreState = TheCondStack.back().Ignore;
1783 if (LastIgnoreState || TheCondState.CondMet)
1784 TheCondState.Ignore = true;
1786 TheCondState.Ignore = false;
1791 /// ParseDirectiveEndIf
1793 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1794 if (getLexer().isNot(AsmToken::EndOfStatement))
1795 return TokError("unexpected token in '.endif' directive");
1799 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1800 TheCondStack.empty())
1801 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1803 if (!TheCondStack.empty()) {
1804 TheCondState = TheCondStack.back();
1805 TheCondStack.pop_back();
1811 /// ParseDirectiveFile
1812 /// ::= .file [number] string
1813 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1814 // FIXME: I'm not sure what this is.
1815 int64_t FileNumber = -1;
1816 SMLoc FileNumberLoc = getLexer().getLoc();
1817 if (getLexer().is(AsmToken::Integer)) {
1818 FileNumber = getTok().getIntVal();
1822 return TokError("file number less than one");
1825 if (getLexer().isNot(AsmToken::String))
1826 return TokError("unexpected token in '.file' directive");
1828 StringRef Filename = getTok().getString();
1829 Filename = Filename.substr(1, Filename.size()-2);
1832 if (getLexer().isNot(AsmToken::EndOfStatement))
1833 return TokError("unexpected token in '.file' directive");
1835 if (FileNumber == -1)
1836 getStreamer().EmitFileDirective(Filename);
1838 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1839 Error(FileNumberLoc, "file number already allocated");
1840 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1846 /// ParseDirectiveLine
1847 /// ::= .line [number]
1848 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1849 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1850 if (getLexer().isNot(AsmToken::Integer))
1851 return TokError("unexpected token in '.line' directive");
1853 int64_t LineNumber = getTok().getIntVal();
1857 // FIXME: Do something with the .line.
1860 if (getLexer().isNot(AsmToken::EndOfStatement))
1861 return TokError("unexpected token in '.line' directive");
1867 /// ParseDirectiveLoc
1868 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1869 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1870 /// The first number is a file number, must have been previously assigned with
1871 /// a .file directive, the second number is the line number and optionally the
1872 /// third number is a column position (zero if not specified). The remaining
1873 /// optional items are .loc sub-directives.
1874 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1876 if (getLexer().isNot(AsmToken::Integer))
1877 return TokError("unexpected token in '.loc' directive");
1878 int64_t FileNumber = getTok().getIntVal();
1880 return TokError("file number less than one in '.loc' directive");
1881 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1882 return TokError("unassigned file number in '.loc' directive");
1885 int64_t LineNumber = 0;
1886 if (getLexer().is(AsmToken::Integer)) {
1887 LineNumber = getTok().getIntVal();
1889 return TokError("line number less than one in '.loc' directive");
1893 int64_t ColumnPos = 0;
1894 if (getLexer().is(AsmToken::Integer)) {
1895 ColumnPos = getTok().getIntVal();
1897 return TokError("column position less than zero in '.loc' directive");
1903 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1905 if (getLexer().is(AsmToken::EndOfStatement))
1909 SMLoc Loc = getTok().getLoc();
1910 if (getParser().ParseIdentifier(Name))
1911 return TokError("unexpected token in '.loc' directive");
1913 if (Name == "basic_block")
1914 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1915 else if (Name == "prologue_end")
1916 Flags |= DWARF2_FLAG_PROLOGUE_END;
1917 else if (Name == "epilogue_begin")
1918 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1919 else if (Name == "is_stmt") {
1920 SMLoc Loc = getTok().getLoc();
1921 const MCExpr *Value;
1922 if (getParser().ParseExpression(Value))
1924 // The expression must be the constant 0 or 1.
1925 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1926 int Value = MCE->getValue();
1928 Flags &= ~DWARF2_FLAG_IS_STMT;
1929 else if (Value == 1)
1930 Flags |= DWARF2_FLAG_IS_STMT;
1932 return Error(Loc, "is_stmt value not 0 or 1");
1935 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1938 else if (Name == "isa") {
1939 SMLoc Loc = getTok().getLoc();
1940 const MCExpr *Value;
1941 if (getParser().ParseExpression(Value))
1943 // The expression must be a constant greater or equal to 0.
1944 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1945 int Value = MCE->getValue();
1947 return Error(Loc, "isa number less than zero");
1951 return Error(Loc, "isa number not a constant value");
1955 return Error(Loc, "unknown sub-directive in '.loc' directive");
1958 if (getLexer().is(AsmToken::EndOfStatement))
1963 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1968 /// ParseDirectiveMacrosOnOff
1971 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1972 SMLoc DirectiveLoc) {
1973 if (getLexer().isNot(AsmToken::EndOfStatement))
1974 return Error(getLexer().getLoc(),
1975 "unexpected token in '" + Directive + "' directive");
1977 getParser().MacrosEnabled = Directive == ".macros_on";
1982 /// ParseDirectiveMacro
1984 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1985 SMLoc DirectiveLoc) {
1987 if (getParser().ParseIdentifier(Name))
1988 return TokError("expected identifier in directive");
1990 if (getLexer().isNot(AsmToken::EndOfStatement))
1991 return TokError("unexpected token in '.macro' directive");
1993 // Eat the end of statement.
1996 AsmToken EndToken, StartToken = getTok();
1998 // Lex the macro definition.
2000 // Check whether we have reached the end of the file.
2001 if (getLexer().is(AsmToken::Eof))
2002 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2004 // Otherwise, check whether we have reach the .endmacro.
2005 if (getLexer().is(AsmToken::Identifier) &&
2006 (getTok().getIdentifier() == ".endm" ||
2007 getTok().getIdentifier() == ".endmacro")) {
2008 EndToken = getTok();
2010 if (getLexer().isNot(AsmToken::EndOfStatement))
2011 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2016 // Otherwise, scan til the end of the statement.
2017 getParser().EatToEndOfStatement();
2020 if (getParser().MacroMap.lookup(Name)) {
2021 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2024 const char *BodyStart = StartToken.getLoc().getPointer();
2025 const char *BodyEnd = EndToken.getLoc().getPointer();
2026 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2027 getParser().MacroMap[Name] = new Macro(Name, Body);
2031 /// ParseDirectiveEndMacro
2034 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2035 SMLoc DirectiveLoc) {
2036 if (getLexer().isNot(AsmToken::EndOfStatement))
2037 return TokError("unexpected token in '" + Directive + "' directive");
2039 // If we are inside a macro instantiation, terminate the current
2041 if (!getParser().ActiveMacros.empty()) {
2042 getParser().HandleMacroExit();
2046 // Otherwise, this .endmacro is a stray entry in the file; well formed
2047 // .endmacro directives are handled during the macro definition parsing.
2048 return TokError("unexpected '" + Directive + "' in file, "
2049 "no current macro definition");
2052 /// \brief Create an MCAsmParser instance.
2053 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2054 MCContext &C, MCStreamer &Out,
2055 const MCAsmInfo &MAI) {
2056 return new AsmParser(T, SM, C, Out, MAI);