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");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
246 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
247 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
248 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
250 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
251 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
252 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
254 void ParseUleb128(uint64_t Value);
255 void ParseSleb128(int64_t Value);
256 bool ParseDirectiveLEB128(StringRef, SMLoc);
263 extern MCAsmParserExtension *createDarwinAsmParser();
264 extern MCAsmParserExtension *createELFAsmParser();
268 enum { DEFAULT_ADDRSPACE = 0 };
270 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
271 MCStreamer &_Out, const MCAsmInfo &_MAI)
272 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
273 GenericParser(new GenericAsmParser), PlatformParser(0),
274 CurBuffer(0), MacrosEnabled(true) {
275 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
277 // Initialize the generic parser.
278 GenericParser->Initialize(*this);
280 // Initialize the platform / file format parser.
282 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
284 if (_MAI.hasSubsectionsViaSymbols()) {
285 PlatformParser = createDarwinAsmParser();
286 PlatformParser->Initialize(*this);
288 PlatformParser = createELFAsmParser();
289 PlatformParser->Initialize(*this);
293 AsmParser::~AsmParser() {
294 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
296 // Destroy any macros.
297 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
298 ie = MacroMap.end(); it != ie; ++it)
299 delete it->getValue();
301 delete PlatformParser;
302 delete GenericParser;
305 void AsmParser::PrintMacroInstantiations() {
306 // Print the active macro instantiation stack.
307 for (std::vector<MacroInstantiation*>::const_reverse_iterator
308 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
309 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
313 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
314 PrintMessage(L, Msg.str(), "warning");
315 PrintMacroInstantiations();
318 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
320 PrintMessage(L, Msg.str(), "error");
321 PrintMacroInstantiations();
325 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
326 const char *Type) const {
327 SrcMgr.PrintMessage(Loc, Msg, Type);
330 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
331 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
337 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
342 void AsmParser::JumpToLoc(SMLoc Loc) {
343 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
344 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
347 const AsmToken &AsmParser::Lex() {
348 const AsmToken *tok = &Lexer.Lex();
350 if (tok->is(AsmToken::Eof)) {
351 // If this is the end of an included file, pop the parent file off the
353 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
354 if (ParentIncludeLoc != SMLoc()) {
355 JumpToLoc(ParentIncludeLoc);
360 if (tok->is(AsmToken::Error))
361 Error(Lexer.getErrLoc(), Lexer.getErr());
366 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
367 // Create the initial section, if requested.
368 if (!NoInitialTextSection)
375 AsmCond StartingCondState = TheCondState;
377 // While we have input, parse each statement.
378 while (Lexer.isNot(AsmToken::Eof)) {
379 if (!ParseStatement()) continue;
381 // We had an error, validate that one was emitted and recover by skipping to
383 assert(HadError && "Parse statement returned an error, but none emitted!");
384 EatToEndOfStatement();
387 if (TheCondState.TheCond != StartingCondState.TheCond ||
388 TheCondState.Ignore != StartingCondState.Ignore)
389 return TokError("unmatched .ifs or .elses");
391 // Check to see there are no empty DwarfFile slots.
392 const std::vector<MCDwarfFile *> &MCDwarfFiles =
393 getContext().getMCDwarfFiles();
394 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
395 if (!MCDwarfFiles[i])
396 TokError("unassigned file number: " + Twine(i) + " for .file directives");
399 // Finalize the output stream if there are no errors and if the client wants
401 if (!HadError && !NoFinalize)
407 void AsmParser::CheckForValidSection() {
408 if (!getStreamer().getCurrentSection()) {
409 TokError("expected section directive before assembly directive");
410 Out.SwitchSection(Ctx.getMachOSection(
412 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
413 0, SectionKind::getText()));
417 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
418 void AsmParser::EatToEndOfStatement() {
419 while (Lexer.isNot(AsmToken::EndOfStatement) &&
420 Lexer.isNot(AsmToken::Eof))
424 if (Lexer.is(AsmToken::EndOfStatement))
428 StringRef AsmParser::ParseStringToEndOfStatement() {
429 const char *Start = getTok().getLoc().getPointer();
431 while (Lexer.isNot(AsmToken::EndOfStatement) &&
432 Lexer.isNot(AsmToken::Eof))
435 const char *End = getTok().getLoc().getPointer();
436 return StringRef(Start, End - Start);
439 /// ParseParenExpr - Parse a paren expression and return it.
440 /// NOTE: This assumes the leading '(' has already been consumed.
442 /// parenexpr ::= expr)
444 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
445 if (ParseExpression(Res)) return true;
446 if (Lexer.isNot(AsmToken::RParen))
447 return TokError("expected ')' in parentheses expression");
448 EndLoc = Lexer.getLoc();
453 /// ParsePrimaryExpr - Parse a primary expression and return it.
454 /// primaryexpr ::= (parenexpr
455 /// primaryexpr ::= symbol
456 /// primaryexpr ::= number
457 /// primaryexpr ::= '.'
458 /// primaryexpr ::= ~,+,- primaryexpr
459 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
460 switch (Lexer.getKind()) {
462 return TokError("unknown token in expression");
463 case AsmToken::Exclaim:
464 Lex(); // Eat the operator.
465 if (ParsePrimaryExpr(Res, EndLoc))
467 Res = MCUnaryExpr::CreateLNot(Res, getContext());
469 case AsmToken::Dollar:
470 case AsmToken::String:
471 case AsmToken::Identifier: {
472 EndLoc = Lexer.getLoc();
474 StringRef Identifier;
475 if (ParseIdentifier(Identifier))
478 // This is a symbol reference.
479 std::pair<StringRef, StringRef> Split = Identifier.split('@');
480 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
482 // Mark the symbol as used in an expression.
483 Sym->setUsedInExpr(true);
485 // Lookup the symbol variant if used.
486 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
487 if (Split.first.size() != Identifier.size())
488 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
490 // If this is an absolute variable reference, substitute it now to preserve
491 // semantics in the face of reassignment.
492 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
494 return Error(EndLoc, "unexpected modified on variable reference");
496 Res = Sym->getVariableValue();
500 // Otherwise create a symbol ref.
501 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
504 case AsmToken::Integer: {
505 SMLoc Loc = getTok().getLoc();
506 int64_t IntVal = getTok().getIntVal();
507 Res = MCConstantExpr::Create(IntVal, getContext());
508 EndLoc = Lexer.getLoc();
510 // Look for 'b' or 'f' following an Integer as a directional label
511 if (Lexer.getKind() == AsmToken::Identifier) {
512 StringRef IDVal = getTok().getString();
513 if (IDVal == "f" || IDVal == "b"){
514 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
515 IDVal == "f" ? 1 : 0);
516 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
518 if(IDVal == "b" && Sym->isUndefined())
519 return Error(Loc, "invalid reference to undefined symbol");
520 EndLoc = Lexer.getLoc();
521 Lex(); // Eat identifier.
526 case AsmToken::Dot: {
527 // This is a '.' reference, which references the current PC. Emit a
528 // temporary label to the streamer and refer to it.
529 MCSymbol *Sym = Ctx.CreateTempSymbol();
531 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
532 EndLoc = Lexer.getLoc();
533 Lex(); // Eat identifier.
537 case AsmToken::LParen:
538 Lex(); // Eat the '('.
539 return ParseParenExpr(Res, EndLoc);
540 case AsmToken::Minus:
541 Lex(); // Eat the operator.
542 if (ParsePrimaryExpr(Res, EndLoc))
544 Res = MCUnaryExpr::CreateMinus(Res, getContext());
547 Lex(); // Eat the operator.
548 if (ParsePrimaryExpr(Res, EndLoc))
550 Res = MCUnaryExpr::CreatePlus(Res, getContext());
552 case AsmToken::Tilde:
553 Lex(); // Eat the operator.
554 if (ParsePrimaryExpr(Res, EndLoc))
556 Res = MCUnaryExpr::CreateNot(Res, getContext());
561 bool AsmParser::ParseExpression(const MCExpr *&Res) {
563 return ParseExpression(Res, EndLoc);
566 /// ParseExpression - Parse an expression and return it.
568 /// expr ::= expr +,- expr -> lowest.
569 /// expr ::= expr |,^,&,! expr -> middle.
570 /// expr ::= expr *,/,%,<<,>> expr -> highest.
571 /// expr ::= primaryexpr
573 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
574 // Parse the expression.
576 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
579 // Try to constant fold it up front, if possible.
581 if (Res->EvaluateAsAbsolute(Value))
582 Res = MCConstantExpr::Create(Value, getContext());
587 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
589 return ParseParenExpr(Res, EndLoc) ||
590 ParseBinOpRHS(1, Res, EndLoc);
593 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
596 SMLoc StartLoc = Lexer.getLoc();
597 if (ParseExpression(Expr))
600 if (!Expr->EvaluateAsAbsolute(Res))
601 return Error(StartLoc, "expected absolute expression");
606 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
607 MCBinaryExpr::Opcode &Kind) {
610 return 0; // not a binop.
612 // Lowest Precedence: &&, ||
613 case AsmToken::AmpAmp:
614 Kind = MCBinaryExpr::LAnd;
616 case AsmToken::PipePipe:
617 Kind = MCBinaryExpr::LOr;
620 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
622 Kind = MCBinaryExpr::Add;
624 case AsmToken::Minus:
625 Kind = MCBinaryExpr::Sub;
627 case AsmToken::EqualEqual:
628 Kind = MCBinaryExpr::EQ;
630 case AsmToken::ExclaimEqual:
631 case AsmToken::LessGreater:
632 Kind = MCBinaryExpr::NE;
635 Kind = MCBinaryExpr::LT;
637 case AsmToken::LessEqual:
638 Kind = MCBinaryExpr::LTE;
640 case AsmToken::Greater:
641 Kind = MCBinaryExpr::GT;
643 case AsmToken::GreaterEqual:
644 Kind = MCBinaryExpr::GTE;
647 // Intermediate Precedence: |, &, ^
649 // FIXME: gas seems to support '!' as an infix operator?
651 Kind = MCBinaryExpr::Or;
653 case AsmToken::Caret:
654 Kind = MCBinaryExpr::Xor;
657 Kind = MCBinaryExpr::And;
660 // Highest Precedence: *, /, %, <<, >>
662 Kind = MCBinaryExpr::Mul;
664 case AsmToken::Slash:
665 Kind = MCBinaryExpr::Div;
667 case AsmToken::Percent:
668 Kind = MCBinaryExpr::Mod;
670 case AsmToken::LessLess:
671 Kind = MCBinaryExpr::Shl;
673 case AsmToken::GreaterGreater:
674 Kind = MCBinaryExpr::Shr;
680 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
681 /// Res contains the LHS of the expression on input.
682 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
685 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
686 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
688 // If the next token is lower precedence than we are allowed to eat, return
689 // successfully with what we ate already.
690 if (TokPrec < Precedence)
695 // Eat the next primary expression.
697 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
699 // If BinOp binds less tightly with RHS than the operator after RHS, let
700 // the pending operator take RHS as its LHS.
701 MCBinaryExpr::Opcode Dummy;
702 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
703 if (TokPrec < NextTokPrec) {
704 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
707 // Merge LHS and RHS according to operator.
708 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
716 /// ::= EndOfStatement
717 /// ::= Label* Directive ...Operands... EndOfStatement
718 /// ::= Label* Identifier OperandList* EndOfStatement
719 bool AsmParser::ParseStatement() {
720 if (Lexer.is(AsmToken::EndOfStatement)) {
726 // Statements always start with an identifier.
727 AsmToken ID = getTok();
728 SMLoc IDLoc = ID.getLoc();
730 int64_t LocalLabelVal = -1;
731 // GUESS allow an integer followed by a ':' as a directional local label
732 if (Lexer.is(AsmToken::Integer)) {
733 LocalLabelVal = getTok().getIntVal();
734 if (LocalLabelVal < 0) {
735 if (!TheCondState.Ignore)
736 return TokError("unexpected token at start of statement");
740 IDVal = getTok().getString();
741 Lex(); // Consume the integer token to be used as an identifier token.
742 if (Lexer.getKind() != AsmToken::Colon) {
743 if (!TheCondState.Ignore)
744 return TokError("unexpected token at start of statement");
748 else if (ParseIdentifier(IDVal)) {
749 if (!TheCondState.Ignore)
750 return TokError("unexpected token at start of statement");
754 // Handle conditional assembly here before checking for skipping. We
755 // have to do this so that .endif isn't skipped in a ".if 0" block for
758 return ParseDirectiveIf(IDLoc);
759 if (IDVal == ".elseif")
760 return ParseDirectiveElseIf(IDLoc);
761 if (IDVal == ".else")
762 return ParseDirectiveElse(IDLoc);
763 if (IDVal == ".endif")
764 return ParseDirectiveEndIf(IDLoc);
766 // If we are in a ".if 0" block, ignore this statement.
767 if (TheCondState.Ignore) {
768 EatToEndOfStatement();
772 // FIXME: Recurse on local labels?
774 // See what kind of statement we have.
775 switch (Lexer.getKind()) {
776 case AsmToken::Colon: {
777 CheckForValidSection();
779 // identifier ':' -> Label.
782 // Diagnose attempt to use a variable as a label.
784 // FIXME: Diagnostics. Note the location of the definition as a label.
785 // FIXME: This doesn't diagnose assignment to a symbol which has been
786 // implicitly marked as external.
788 if (LocalLabelVal == -1)
789 Sym = getContext().GetOrCreateSymbol(IDVal);
791 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
792 if (!Sym->isUndefined() || Sym->isVariable())
793 return Error(IDLoc, "invalid symbol redefinition");
798 // Consume any end of statement token, if present, to avoid spurious
799 // AddBlankLine calls().
800 if (Lexer.is(AsmToken::EndOfStatement)) {
802 if (Lexer.is(AsmToken::Eof))
806 return ParseStatement();
809 case AsmToken::Equal:
810 // identifier '=' ... -> assignment statement
813 return ParseAssignment(IDVal);
815 default: // Normal instruction or directive.
819 // If macros are enabled, check to see if this is a macro instantiation.
821 if (const Macro *M = MacroMap.lookup(IDVal))
822 return HandleMacroEntry(IDVal, IDLoc, M);
824 // Otherwise, we have a normal instruction or directive.
825 if (IDVal[0] == '.') {
826 // Assembler features
828 return ParseDirectiveSet();
832 if (IDVal == ".ascii")
833 return ParseDirectiveAscii(false);
834 if (IDVal == ".asciz")
835 return ParseDirectiveAscii(true);
837 if (IDVal == ".byte")
838 return ParseDirectiveValue(1);
839 if (IDVal == ".short")
840 return ParseDirectiveValue(2);
841 if (IDVal == ".long")
842 return ParseDirectiveValue(4);
843 if (IDVal == ".quad")
844 return ParseDirectiveValue(8);
846 if (IDVal == ".align") {
847 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
848 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
850 if (IDVal == ".align32") {
851 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
852 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
854 if (IDVal == ".balign")
855 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
856 if (IDVal == ".balignw")
857 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
858 if (IDVal == ".balignl")
859 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
860 if (IDVal == ".p2align")
861 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
862 if (IDVal == ".p2alignw")
863 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
864 if (IDVal == ".p2alignl")
865 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
868 return ParseDirectiveOrg();
870 if (IDVal == ".fill")
871 return ParseDirectiveFill();
872 if (IDVal == ".space")
873 return ParseDirectiveSpace();
875 // Symbol attribute directives
877 if (IDVal == ".globl" || IDVal == ".global")
878 return ParseDirectiveSymbolAttribute(MCSA_Global);
879 if (IDVal == ".hidden")
880 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
881 if (IDVal == ".indirect_symbol")
882 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
883 if (IDVal == ".internal")
884 return ParseDirectiveSymbolAttribute(MCSA_Internal);
885 if (IDVal == ".lazy_reference")
886 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
887 if (IDVal == ".no_dead_strip")
888 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
889 if (IDVal == ".private_extern")
890 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
891 if (IDVal == ".protected")
892 return ParseDirectiveSymbolAttribute(MCSA_Protected);
893 if (IDVal == ".reference")
894 return ParseDirectiveSymbolAttribute(MCSA_Reference);
895 if (IDVal == ".type")
896 return ParseDirectiveELFType();
897 if (IDVal == ".weak")
898 return ParseDirectiveSymbolAttribute(MCSA_Weak);
899 if (IDVal == ".weak_definition")
900 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
901 if (IDVal == ".weak_reference")
902 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
903 if (IDVal == ".weak_def_can_be_hidden")
904 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
906 if (IDVal == ".comm")
907 return ParseDirectiveComm(/*IsLocal=*/false);
908 if (IDVal == ".lcomm")
909 return ParseDirectiveComm(/*IsLocal=*/true);
911 if (IDVal == ".abort")
912 return ParseDirectiveAbort();
913 if (IDVal == ".include")
914 return ParseDirectiveInclude();
916 // Look up the handler in the handler table.
917 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
918 DirectiveMap.lookup(IDVal);
920 return (*Handler.second)(Handler.first, IDVal, IDLoc);
922 // Target hook for parsing target specific directives.
923 if (!getTargetParser().ParseDirective(ID))
926 Warning(IDLoc, "ignoring directive for now");
927 EatToEndOfStatement();
931 CheckForValidSection();
933 // Canonicalize the opcode to lower case.
934 SmallString<128> Opcode;
935 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
936 Opcode.push_back(tolower(IDVal[i]));
938 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
939 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
942 // Dump the parsed representation, if requested.
943 if (getShowParsedOperands()) {
944 SmallString<256> Str;
945 raw_svector_ostream OS(Str);
946 OS << "parsed instruction: [";
947 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
950 ParsedOperands[i]->dump(OS);
954 PrintMessage(IDLoc, OS.str(), "note");
957 // If parsing succeeded, match the instruction.
960 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
961 // Emit the instruction on success.
962 Out.EmitInstruction(Inst);
967 // Free any parsed operands.
968 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
969 delete ParsedOperands[i];
971 // Don't skip the rest of the line, the instruction parser is responsible for
976 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
977 const std::vector<std::vector<AsmToken> > &A)
978 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
980 // Macro instantiation is lexical, unfortunately. We construct a new buffer
981 // to hold the macro body with substitutions.
982 SmallString<256> Buf;
983 raw_svector_ostream OS(Buf);
985 StringRef Body = M->Body;
986 while (!Body.empty()) {
987 // Scan for the next substitution.
988 std::size_t End = Body.size(), Pos = 0;
989 for (; Pos != End; ++Pos) {
990 // Check for a substitution or escape.
991 if (Body[Pos] != '$' || Pos + 1 == End)
994 char Next = Body[Pos + 1];
995 if (Next == '$' || Next == 'n' || isdigit(Next))
1000 OS << Body.slice(0, Pos);
1002 // Check if we reached the end.
1006 switch (Body[Pos+1]) {
1012 // $n => number of arguments
1017 // $[0-9] => argument
1019 // Missing arguments are ignored.
1020 unsigned Index = Body[Pos+1] - '0';
1021 if (Index >= A.size())
1024 // Otherwise substitute with the token values, with spaces eliminated.
1025 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1026 ie = A[Index].end(); it != ie; ++it)
1027 OS << it->getString();
1032 // Update the scan point.
1033 Body = Body.substr(Pos + 2);
1036 // We include the .endmacro in the buffer as our queue to exit the macro
1038 OS << ".endmacro\n";
1040 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1043 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1045 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1046 // this, although we should protect against infinite loops.
1047 if (ActiveMacros.size() == 20)
1048 return TokError("macros cannot be nested more than 20 levels deep");
1050 // Parse the macro instantiation arguments.
1051 std::vector<std::vector<AsmToken> > MacroArguments;
1052 MacroArguments.push_back(std::vector<AsmToken>());
1053 unsigned ParenLevel = 0;
1055 if (Lexer.is(AsmToken::Eof))
1056 return TokError("unexpected token in macro instantiation");
1057 if (Lexer.is(AsmToken::EndOfStatement))
1060 // If we aren't inside parentheses and this is a comma, start a new token
1062 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1063 MacroArguments.push_back(std::vector<AsmToken>());
1065 // Adjust the current parentheses level.
1066 if (Lexer.is(AsmToken::LParen))
1068 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1071 // Append the token to the current argument list.
1072 MacroArguments.back().push_back(getTok());
1077 // Create the macro instantiation object and add to the current macro
1078 // instantiation stack.
1079 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1082 ActiveMacros.push_back(MI);
1084 // Jump to the macro instantiation and prime the lexer.
1085 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1086 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1092 void AsmParser::HandleMacroExit() {
1093 // Jump to the EndOfStatement we should return to, and consume it.
1094 JumpToLoc(ActiveMacros.back()->ExitLoc);
1097 // Pop the instantiation entry.
1098 delete ActiveMacros.back();
1099 ActiveMacros.pop_back();
1102 bool AsmParser::ParseAssignment(StringRef Name) {
1103 // FIXME: Use better location, we should use proper tokens.
1104 SMLoc EqualLoc = Lexer.getLoc();
1106 const MCExpr *Value;
1107 if (ParseExpression(Value))
1110 if (Lexer.isNot(AsmToken::EndOfStatement))
1111 return TokError("unexpected token in assignment");
1113 // Eat the end of statement marker.
1116 // Validate that the LHS is allowed to be a variable (either it has not been
1117 // used as a symbol, or it is an absolute symbol).
1118 MCSymbol *Sym = getContext().LookupSymbol(Name);
1120 // Diagnose assignment to a label.
1122 // FIXME: Diagnostics. Note the location of the definition as a label.
1123 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1124 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1125 ; // Allow redefinitions of undefined symbols only used in directives.
1126 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1127 return Error(EqualLoc, "redefinition of '" + Name + "'");
1128 else if (!Sym->isVariable())
1129 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1130 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1131 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1134 Sym = getContext().GetOrCreateSymbol(Name);
1136 // FIXME: Handle '.'.
1138 Sym->setUsedInExpr(true);
1140 // Do the assignment.
1141 Out.EmitAssignment(Sym, Value);
1146 /// ParseIdentifier:
1149 bool AsmParser::ParseIdentifier(StringRef &Res) {
1150 // The assembler has relaxed rules for accepting identifiers, in particular we
1151 // allow things like '.globl $foo', which would normally be separate
1152 // tokens. At this level, we have already lexed so we cannot (currently)
1153 // handle this as a context dependent token, instead we detect adjacent tokens
1154 // and return the combined identifier.
1155 if (Lexer.is(AsmToken::Dollar)) {
1156 SMLoc DollarLoc = getLexer().getLoc();
1158 // Consume the dollar sign, and check for a following identifier.
1160 if (Lexer.isNot(AsmToken::Identifier))
1163 // We have a '$' followed by an identifier, make sure they are adjacent.
1164 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1167 // Construct the joined identifier and consume the token.
1168 Res = StringRef(DollarLoc.getPointer(),
1169 getTok().getIdentifier().size() + 1);
1174 if (Lexer.isNot(AsmToken::Identifier) &&
1175 Lexer.isNot(AsmToken::String))
1178 Res = getTok().getIdentifier();
1180 Lex(); // Consume the identifier token.
1185 /// ParseDirectiveSet:
1186 /// ::= .set identifier ',' expression
1187 bool AsmParser::ParseDirectiveSet() {
1190 if (ParseIdentifier(Name))
1191 return TokError("expected identifier after '.set' directive");
1193 if (getLexer().isNot(AsmToken::Comma))
1194 return TokError("unexpected token in '.set'");
1197 return ParseAssignment(Name);
1200 bool AsmParser::ParseEscapedString(std::string &Data) {
1201 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1204 StringRef Str = getTok().getStringContents();
1205 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1206 if (Str[i] != '\\') {
1211 // Recognize escaped characters. Note that this escape semantics currently
1212 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1215 return TokError("unexpected backslash at end of string");
1217 // Recognize octal sequences.
1218 if ((unsigned) (Str[i] - '0') <= 7) {
1219 // Consume up to three octal characters.
1220 unsigned Value = Str[i] - '0';
1222 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1224 Value = Value * 8 + (Str[i] - '0');
1226 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1228 Value = Value * 8 + (Str[i] - '0');
1233 return TokError("invalid octal escape sequence (out of range)");
1235 Data += (unsigned char) Value;
1239 // Otherwise recognize individual escapes.
1242 // Just reject invalid escape sequences for now.
1243 return TokError("invalid escape sequence (unrecognized character)");
1245 case 'b': Data += '\b'; break;
1246 case 'f': Data += '\f'; break;
1247 case 'n': Data += '\n'; break;
1248 case 'r': Data += '\r'; break;
1249 case 't': Data += '\t'; break;
1250 case '"': Data += '"'; break;
1251 case '\\': Data += '\\'; break;
1258 /// ParseDirectiveAscii:
1259 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1260 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1261 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1262 CheckForValidSection();
1265 if (getLexer().isNot(AsmToken::String))
1266 return TokError("expected string in '.ascii' or '.asciz' directive");
1269 if (ParseEscapedString(Data))
1272 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1274 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1278 if (getLexer().is(AsmToken::EndOfStatement))
1281 if (getLexer().isNot(AsmToken::Comma))
1282 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1291 /// ParseDirectiveValue
1292 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1293 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1295 CheckForValidSection();
1298 const MCExpr *Value;
1299 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1300 if (ParseExpression(Value))
1303 // Special case constant expressions to match code generator.
1304 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1305 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1307 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1309 if (getLexer().is(AsmToken::EndOfStatement))
1312 // FIXME: Improve diagnostic.
1313 if (getLexer().isNot(AsmToken::Comma))
1314 return TokError("unexpected token in directive");
1323 /// ParseDirectiveSpace
1324 /// ::= .space expression [ , expression ]
1325 bool AsmParser::ParseDirectiveSpace() {
1326 CheckForValidSection();
1329 if (ParseAbsoluteExpression(NumBytes))
1332 int64_t FillExpr = 0;
1333 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1334 if (getLexer().isNot(AsmToken::Comma))
1335 return TokError("unexpected token in '.space' directive");
1338 if (ParseAbsoluteExpression(FillExpr))
1341 if (getLexer().isNot(AsmToken::EndOfStatement))
1342 return TokError("unexpected token in '.space' directive");
1348 return TokError("invalid number of bytes in '.space' directive");
1350 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1351 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1356 /// ParseDirectiveFill
1357 /// ::= .fill expression , expression , expression
1358 bool AsmParser::ParseDirectiveFill() {
1359 CheckForValidSection();
1362 if (ParseAbsoluteExpression(NumValues))
1365 if (getLexer().isNot(AsmToken::Comma))
1366 return TokError("unexpected token in '.fill' directive");
1370 if (ParseAbsoluteExpression(FillSize))
1373 if (getLexer().isNot(AsmToken::Comma))
1374 return TokError("unexpected token in '.fill' directive");
1378 if (ParseAbsoluteExpression(FillExpr))
1381 if (getLexer().isNot(AsmToken::EndOfStatement))
1382 return TokError("unexpected token in '.fill' directive");
1386 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1387 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1389 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1390 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1395 /// ParseDirectiveOrg
1396 /// ::= .org expression [ , expression ]
1397 bool AsmParser::ParseDirectiveOrg() {
1398 CheckForValidSection();
1400 const MCExpr *Offset;
1401 if (ParseExpression(Offset))
1404 // Parse optional fill expression.
1405 int64_t FillExpr = 0;
1406 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1407 if (getLexer().isNot(AsmToken::Comma))
1408 return TokError("unexpected token in '.org' directive");
1411 if (ParseAbsoluteExpression(FillExpr))
1414 if (getLexer().isNot(AsmToken::EndOfStatement))
1415 return TokError("unexpected token in '.org' directive");
1420 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1421 // has to be relative to the current section.
1422 getStreamer().EmitValueToOffset(Offset, FillExpr);
1427 /// ParseDirectiveAlign
1428 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1429 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1430 CheckForValidSection();
1432 SMLoc AlignmentLoc = getLexer().getLoc();
1434 if (ParseAbsoluteExpression(Alignment))
1438 bool HasFillExpr = false;
1439 int64_t FillExpr = 0;
1440 int64_t MaxBytesToFill = 0;
1441 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1442 if (getLexer().isNot(AsmToken::Comma))
1443 return TokError("unexpected token in directive");
1446 // The fill expression can be omitted while specifying a maximum number of
1447 // alignment bytes, e.g:
1449 if (getLexer().isNot(AsmToken::Comma)) {
1451 if (ParseAbsoluteExpression(FillExpr))
1455 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1456 if (getLexer().isNot(AsmToken::Comma))
1457 return TokError("unexpected token in directive");
1460 MaxBytesLoc = getLexer().getLoc();
1461 if (ParseAbsoluteExpression(MaxBytesToFill))
1464 if (getLexer().isNot(AsmToken::EndOfStatement))
1465 return TokError("unexpected token in directive");
1474 // Compute alignment in bytes.
1476 // FIXME: Diagnose overflow.
1477 if (Alignment >= 32) {
1478 Error(AlignmentLoc, "invalid alignment value");
1482 Alignment = 1ULL << Alignment;
1485 // Diagnose non-sensical max bytes to align.
1486 if (MaxBytesLoc.isValid()) {
1487 if (MaxBytesToFill < 1) {
1488 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1489 "many bytes, ignoring maximum bytes expression");
1493 if (MaxBytesToFill >= Alignment) {
1494 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1500 // Check whether we should use optimal code alignment for this .align
1503 // FIXME: This should be using a target hook.
1504 bool UseCodeAlign = false;
1505 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1506 getStreamer().getCurrentSection()))
1507 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1508 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1509 ValueSize == 1 && UseCodeAlign) {
1510 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1512 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1513 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1520 /// ParseDirectiveSymbolAttribute
1521 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1522 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1523 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1527 if (ParseIdentifier(Name))
1528 return TokError("expected identifier in directive");
1530 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1532 getStreamer().EmitSymbolAttribute(Sym, Attr);
1534 if (getLexer().is(AsmToken::EndOfStatement))
1537 if (getLexer().isNot(AsmToken::Comma))
1538 return TokError("unexpected token in directive");
1547 /// ParseDirectiveELFType
1548 /// ::= .type identifier , @attribute
1549 bool AsmParser::ParseDirectiveELFType() {
1551 if (ParseIdentifier(Name))
1552 return TokError("expected identifier in directive");
1554 // Handle the identifier as the key symbol.
1555 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1557 if (getLexer().isNot(AsmToken::Comma))
1558 return TokError("unexpected token in '.type' directive");
1561 if (getLexer().isNot(AsmToken::At))
1562 return TokError("expected '@' before type");
1568 TypeLoc = getLexer().getLoc();
1569 if (ParseIdentifier(Type))
1570 return TokError("expected symbol type in directive");
1572 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1573 .Case("function", MCSA_ELF_TypeFunction)
1574 .Case("object", MCSA_ELF_TypeObject)
1575 .Case("tls_object", MCSA_ELF_TypeTLS)
1576 .Case("common", MCSA_ELF_TypeCommon)
1577 .Case("notype", MCSA_ELF_TypeNoType)
1578 .Default(MCSA_Invalid);
1580 if (Attr == MCSA_Invalid)
1581 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1583 if (getLexer().isNot(AsmToken::EndOfStatement))
1584 return TokError("unexpected token in '.type' directive");
1588 getStreamer().EmitSymbolAttribute(Sym, Attr);
1593 /// ParseDirectiveComm
1594 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1595 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1596 CheckForValidSection();
1598 SMLoc IDLoc = getLexer().getLoc();
1600 if (ParseIdentifier(Name))
1601 return TokError("expected identifier in directive");
1603 // Handle the identifier as the key symbol.
1604 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1606 if (getLexer().isNot(AsmToken::Comma))
1607 return TokError("unexpected token in directive");
1611 SMLoc SizeLoc = getLexer().getLoc();
1612 if (ParseAbsoluteExpression(Size))
1615 int64_t Pow2Alignment = 0;
1616 SMLoc Pow2AlignmentLoc;
1617 if (getLexer().is(AsmToken::Comma)) {
1619 Pow2AlignmentLoc = getLexer().getLoc();
1620 if (ParseAbsoluteExpression(Pow2Alignment))
1623 // If this target takes alignments in bytes (not log) validate and convert.
1624 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1625 if (!isPowerOf2_64(Pow2Alignment))
1626 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1627 Pow2Alignment = Log2_64(Pow2Alignment);
1631 if (getLexer().isNot(AsmToken::EndOfStatement))
1632 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1636 // NOTE: a size of zero for a .comm should create a undefined symbol
1637 // but a size of .lcomm creates a bss symbol of size zero.
1639 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1640 "be less than zero");
1642 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1643 // may internally end up wanting an alignment in bytes.
1644 // FIXME: Diagnose overflow.
1645 if (Pow2Alignment < 0)
1646 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1647 "alignment, can't be less than zero");
1649 if (!Sym->isUndefined())
1650 return Error(IDLoc, "invalid symbol redefinition");
1652 // '.lcomm' is equivalent to '.zerofill'.
1653 // Create the Symbol as a common or local common with Size and Pow2Alignment
1655 getStreamer().EmitZerofill(Ctx.getMachOSection(
1656 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1657 0, SectionKind::getBSS()),
1658 Sym, Size, 1 << Pow2Alignment);
1662 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1666 /// ParseDirectiveAbort
1667 /// ::= .abort [... message ...]
1668 bool AsmParser::ParseDirectiveAbort() {
1669 // FIXME: Use loc from directive.
1670 SMLoc Loc = getLexer().getLoc();
1672 StringRef Str = ParseStringToEndOfStatement();
1673 if (getLexer().isNot(AsmToken::EndOfStatement))
1674 return TokError("unexpected token in '.abort' directive");
1679 Error(Loc, ".abort detected. Assembly stopping.");
1681 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1682 // FIXME: Actually abort assembly here.
1687 /// ParseDirectiveInclude
1688 /// ::= .include "filename"
1689 bool AsmParser::ParseDirectiveInclude() {
1690 if (getLexer().isNot(AsmToken::String))
1691 return TokError("expected string in '.include' directive");
1693 std::string Filename = getTok().getString();
1694 SMLoc IncludeLoc = getLexer().getLoc();
1697 if (getLexer().isNot(AsmToken::EndOfStatement))
1698 return TokError("unexpected token in '.include' directive");
1700 // Strip the quotes.
1701 Filename = Filename.substr(1, Filename.size()-2);
1703 // Attempt to switch the lexer to the included file before consuming the end
1704 // of statement to avoid losing it when we switch.
1705 if (EnterIncludeFile(Filename)) {
1706 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1713 /// ParseDirectiveIf
1714 /// ::= .if expression
1715 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1716 TheCondStack.push_back(TheCondState);
1717 TheCondState.TheCond = AsmCond::IfCond;
1718 if(TheCondState.Ignore) {
1719 EatToEndOfStatement();
1723 if (ParseAbsoluteExpression(ExprValue))
1726 if (getLexer().isNot(AsmToken::EndOfStatement))
1727 return TokError("unexpected token in '.if' directive");
1731 TheCondState.CondMet = ExprValue;
1732 TheCondState.Ignore = !TheCondState.CondMet;
1738 /// ParseDirectiveElseIf
1739 /// ::= .elseif expression
1740 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1741 if (TheCondState.TheCond != AsmCond::IfCond &&
1742 TheCondState.TheCond != AsmCond::ElseIfCond)
1743 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1745 TheCondState.TheCond = AsmCond::ElseIfCond;
1747 bool LastIgnoreState = false;
1748 if (!TheCondStack.empty())
1749 LastIgnoreState = TheCondStack.back().Ignore;
1750 if (LastIgnoreState || TheCondState.CondMet) {
1751 TheCondState.Ignore = true;
1752 EatToEndOfStatement();
1756 if (ParseAbsoluteExpression(ExprValue))
1759 if (getLexer().isNot(AsmToken::EndOfStatement))
1760 return TokError("unexpected token in '.elseif' directive");
1763 TheCondState.CondMet = ExprValue;
1764 TheCondState.Ignore = !TheCondState.CondMet;
1770 /// ParseDirectiveElse
1772 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1773 if (getLexer().isNot(AsmToken::EndOfStatement))
1774 return TokError("unexpected token in '.else' directive");
1778 if (TheCondState.TheCond != AsmCond::IfCond &&
1779 TheCondState.TheCond != AsmCond::ElseIfCond)
1780 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1782 TheCondState.TheCond = AsmCond::ElseCond;
1783 bool LastIgnoreState = false;
1784 if (!TheCondStack.empty())
1785 LastIgnoreState = TheCondStack.back().Ignore;
1786 if (LastIgnoreState || TheCondState.CondMet)
1787 TheCondState.Ignore = true;
1789 TheCondState.Ignore = false;
1794 /// ParseDirectiveEndIf
1796 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1797 if (getLexer().isNot(AsmToken::EndOfStatement))
1798 return TokError("unexpected token in '.endif' directive");
1802 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1803 TheCondStack.empty())
1804 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1806 if (!TheCondStack.empty()) {
1807 TheCondState = TheCondStack.back();
1808 TheCondStack.pop_back();
1814 /// ParseDirectiveFile
1815 /// ::= .file [number] string
1816 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1817 // FIXME: I'm not sure what this is.
1818 int64_t FileNumber = -1;
1819 SMLoc FileNumberLoc = getLexer().getLoc();
1820 if (getLexer().is(AsmToken::Integer)) {
1821 FileNumber = getTok().getIntVal();
1825 return TokError("file number less than one");
1828 if (getLexer().isNot(AsmToken::String))
1829 return TokError("unexpected token in '.file' directive");
1831 StringRef Filename = getTok().getString();
1832 Filename = Filename.substr(1, Filename.size()-2);
1835 if (getLexer().isNot(AsmToken::EndOfStatement))
1836 return TokError("unexpected token in '.file' directive");
1838 if (FileNumber == -1)
1839 getStreamer().EmitFileDirective(Filename);
1841 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1842 Error(FileNumberLoc, "file number already allocated");
1843 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1849 /// ParseDirectiveLine
1850 /// ::= .line [number]
1851 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1852 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1853 if (getLexer().isNot(AsmToken::Integer))
1854 return TokError("unexpected token in '.line' directive");
1856 int64_t LineNumber = getTok().getIntVal();
1860 // FIXME: Do something with the .line.
1863 if (getLexer().isNot(AsmToken::EndOfStatement))
1864 return TokError("unexpected token in '.line' directive");
1870 /// ParseDirectiveLoc
1871 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1872 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1873 /// The first number is a file number, must have been previously assigned with
1874 /// a .file directive, the second number is the line number and optionally the
1875 /// third number is a column position (zero if not specified). The remaining
1876 /// optional items are .loc sub-directives.
1877 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1879 if (getLexer().isNot(AsmToken::Integer))
1880 return TokError("unexpected token in '.loc' directive");
1881 int64_t FileNumber = getTok().getIntVal();
1883 return TokError("file number less than one in '.loc' directive");
1884 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1885 return TokError("unassigned file number in '.loc' directive");
1888 int64_t LineNumber = 0;
1889 if (getLexer().is(AsmToken::Integer)) {
1890 LineNumber = getTok().getIntVal();
1892 return TokError("line number less than one in '.loc' directive");
1896 int64_t ColumnPos = 0;
1897 if (getLexer().is(AsmToken::Integer)) {
1898 ColumnPos = getTok().getIntVal();
1900 return TokError("column position less than zero in '.loc' directive");
1906 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1908 if (getLexer().is(AsmToken::EndOfStatement))
1912 SMLoc Loc = getTok().getLoc();
1913 if (getParser().ParseIdentifier(Name))
1914 return TokError("unexpected token in '.loc' directive");
1916 if (Name == "basic_block")
1917 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1918 else if (Name == "prologue_end")
1919 Flags |= DWARF2_FLAG_PROLOGUE_END;
1920 else if (Name == "epilogue_begin")
1921 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1922 else if (Name == "is_stmt") {
1923 SMLoc Loc = getTok().getLoc();
1924 const MCExpr *Value;
1925 if (getParser().ParseExpression(Value))
1927 // The expression must be the constant 0 or 1.
1928 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1929 int Value = MCE->getValue();
1931 Flags &= ~DWARF2_FLAG_IS_STMT;
1932 else if (Value == 1)
1933 Flags |= DWARF2_FLAG_IS_STMT;
1935 return Error(Loc, "is_stmt value not 0 or 1");
1938 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1941 else if (Name == "isa") {
1942 SMLoc Loc = getTok().getLoc();
1943 const MCExpr *Value;
1944 if (getParser().ParseExpression(Value))
1946 // The expression must be a constant greater or equal to 0.
1947 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1948 int Value = MCE->getValue();
1950 return Error(Loc, "isa number less than zero");
1954 return Error(Loc, "isa number not a constant value");
1958 return Error(Loc, "unknown sub-directive in '.loc' directive");
1961 if (getLexer().is(AsmToken::EndOfStatement))
1966 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1971 /// ParseDirectiveMacrosOnOff
1974 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1975 SMLoc DirectiveLoc) {
1976 if (getLexer().isNot(AsmToken::EndOfStatement))
1977 return Error(getLexer().getLoc(),
1978 "unexpected token in '" + Directive + "' directive");
1980 getParser().MacrosEnabled = Directive == ".macros_on";
1985 /// ParseDirectiveMacro
1987 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1988 SMLoc DirectiveLoc) {
1990 if (getParser().ParseIdentifier(Name))
1991 return TokError("expected identifier in directive");
1993 if (getLexer().isNot(AsmToken::EndOfStatement))
1994 return TokError("unexpected token in '.macro' directive");
1996 // Eat the end of statement.
1999 AsmToken EndToken, StartToken = getTok();
2001 // Lex the macro definition.
2003 // Check whether we have reached the end of the file.
2004 if (getLexer().is(AsmToken::Eof))
2005 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2007 // Otherwise, check whether we have reach the .endmacro.
2008 if (getLexer().is(AsmToken::Identifier) &&
2009 (getTok().getIdentifier() == ".endm" ||
2010 getTok().getIdentifier() == ".endmacro")) {
2011 EndToken = getTok();
2013 if (getLexer().isNot(AsmToken::EndOfStatement))
2014 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2019 // Otherwise, scan til the end of the statement.
2020 getParser().EatToEndOfStatement();
2023 if (getParser().MacroMap.lookup(Name)) {
2024 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2027 const char *BodyStart = StartToken.getLoc().getPointer();
2028 const char *BodyEnd = EndToken.getLoc().getPointer();
2029 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2030 getParser().MacroMap[Name] = new Macro(Name, Body);
2034 /// ParseDirectiveEndMacro
2037 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2038 SMLoc DirectiveLoc) {
2039 if (getLexer().isNot(AsmToken::EndOfStatement))
2040 return TokError("unexpected token in '" + Directive + "' directive");
2042 // If we are inside a macro instantiation, terminate the current
2044 if (!getParser().ActiveMacros.empty()) {
2045 getParser().HandleMacroExit();
2049 // Otherwise, this .endmacro is a stray entry in the file; well formed
2050 // .endmacro directives are handled during the macro definition parsing.
2051 return TokError("unexpected '" + Directive + "' in file, "
2052 "no current macro definition");
2055 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2056 const uint64_t Mask = (1 << 7) - 1;
2058 unsigned Byte = Value & Mask;
2060 if (Value) // Not the last one
2062 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2066 void GenericAsmParser::ParseSleb128(int64_t Value) {
2067 const int64_t Mask = (1 << 7) - 1;
2069 unsigned Byte = Value & Mask;
2071 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2072 (Value == -1 && (Byte & 0x40) != 0));
2075 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2081 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2083 if (getParser().ParseAbsoluteExpression(Value))
2086 if (getLexer().isNot(AsmToken::EndOfStatement))
2087 return TokError("unexpected token in directive");
2089 if (DirName[1] == 's')
2090 ParseSleb128(Value);
2092 ParseUleb128(Value);
2097 /// \brief Create an MCAsmParser instance.
2098 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2099 MCContext &C, MCStreamer &Out,
2100 const MCAsmInfo &MAI) {
2101 return new AsmParser(T, SM, C, Out, MAI);