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;
106 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
107 const MCAsmInfo &MAI);
110 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
112 void AddDirectiveHandler(MCAsmParserExtension *Object,
114 DirectiveHandler Handler) {
115 DirectiveMap[Directive] = std::make_pair(Object, Handler);
119 /// @name MCAsmParser Interface
122 virtual SourceMgr &getSourceManager() { return SrcMgr; }
123 virtual MCAsmLexer &getLexer() { return Lexer; }
124 virtual MCContext &getContext() { return Ctx; }
125 virtual MCStreamer &getStreamer() { return Out; }
127 virtual void Warning(SMLoc L, const Twine &Meg);
128 virtual bool Error(SMLoc L, const Twine &Msg);
130 const AsmToken &Lex();
132 bool ParseExpression(const MCExpr *&Res);
133 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
134 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
135 virtual bool ParseAbsoluteExpression(int64_t &Res);
140 bool ParseStatement();
142 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
143 void HandleMacroExit();
145 void PrintMacroInstantiations();
146 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
148 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
149 bool EnterIncludeFile(const std::string &Filename);
151 /// \brief Reset the current lexer position to that given by \arg Loc. The
152 /// current token is not set; clients should ensure Lex() is called
154 void JumpToLoc(SMLoc Loc);
156 void EatToEndOfStatement();
158 /// \brief Parse up to the end of statement and a return the contents from the
159 /// current token until the end of the statement; the current token on exit
160 /// will be either the EndOfStatement or EOF.
161 StringRef ParseStringToEndOfStatement();
163 bool ParseAssignment(StringRef Name);
165 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
166 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
167 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
169 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
170 /// and set \arg Res to the identifier contents.
171 bool ParseIdentifier(StringRef &Res);
173 // Directive Parsing.
174 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
175 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
176 bool ParseDirectiveFill(); // ".fill"
177 bool ParseDirectiveSpace(); // ".space"
178 bool ParseDirectiveSet(); // ".set"
179 bool ParseDirectiveOrg(); // ".org"
180 // ".align{,32}", ".p2align{,w,l}"
181 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
183 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
184 /// accepts a single symbol (which should be a label or an external).
185 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
186 bool ParseDirectiveELFType(); // ELF specific ".type"
188 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
190 bool ParseDirectiveAbort(); // ".abort"
191 bool ParseDirectiveInclude(); // ".include"
193 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
194 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
195 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
196 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
198 /// ParseEscapedString - Parse the current token as a string which may include
199 /// escaped characters and return the string contents.
200 bool ParseEscapedString(std::string &Data);
203 /// \brief Generic implementations of directive handling, etc. which is shared
204 /// (or the default, at least) for all assembler parser.
205 class GenericAsmParser : public MCAsmParserExtension {
206 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
207 void AddDirectiveHandler(StringRef Directive) {
208 getParser().AddDirectiveHandler(this, Directive,
209 HandleDirective<GenericAsmParser, Handler>);
213 GenericAsmParser() {}
215 AsmParser &getParser() {
216 return (AsmParser&) this->MCAsmParserExtension::getParser();
219 virtual void Initialize(MCAsmParser &Parser) {
220 // Call the base implementation.
221 this->MCAsmParserExtension::Initialize(Parser);
223 // Debugging directives.
224 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
225 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
226 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
229 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
231 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
233 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
238 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
239 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
240 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
242 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
243 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
244 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
251 extern MCAsmParserExtension *createDarwinAsmParser();
252 extern MCAsmParserExtension *createELFAsmParser();
256 enum { DEFAULT_ADDRSPACE = 0 };
258 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
259 MCStreamer &_Out, const MCAsmInfo &_MAI)
260 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
261 GenericParser(new GenericAsmParser), PlatformParser(0),
262 CurBuffer(0), MacrosEnabled(true) {
263 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
265 // Initialize the generic parser.
266 GenericParser->Initialize(*this);
268 // Initialize the platform / file format parser.
270 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
272 if (_MAI.hasSubsectionsViaSymbols()) {
273 PlatformParser = createDarwinAsmParser();
274 PlatformParser->Initialize(*this);
276 PlatformParser = createELFAsmParser();
277 PlatformParser->Initialize(*this);
281 AsmParser::~AsmParser() {
282 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
284 // Destroy any macros.
285 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
286 ie = MacroMap.end(); it != ie; ++it)
287 delete it->getValue();
289 delete PlatformParser;
290 delete GenericParser;
293 void AsmParser::PrintMacroInstantiations() {
294 // Print the active macro instantiation stack.
295 for (std::vector<MacroInstantiation*>::const_reverse_iterator
296 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
297 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
301 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
302 PrintMessage(L, Msg.str(), "warning");
303 PrintMacroInstantiations();
306 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
307 PrintMessage(L, Msg.str(), "error");
308 PrintMacroInstantiations();
312 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
313 const char *Type) const {
314 SrcMgr.PrintMessage(Loc, Msg, Type);
317 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
318 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
324 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
329 void AsmParser::JumpToLoc(SMLoc Loc) {
330 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
331 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
334 const AsmToken &AsmParser::Lex() {
335 const AsmToken *tok = &Lexer.Lex();
337 if (tok->is(AsmToken::Eof)) {
338 // If this is the end of an included file, pop the parent file off the
340 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
341 if (ParentIncludeLoc != SMLoc()) {
342 JumpToLoc(ParentIncludeLoc);
347 if (tok->is(AsmToken::Error))
348 Error(Lexer.getErrLoc(), Lexer.getErr());
353 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
354 // Create the initial section, if requested.
356 // FIXME: Target hook & command line option for initial section.
357 if (!NoInitialTextSection)
358 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
359 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
360 0, SectionKind::getText()));
365 bool HadError = false;
367 AsmCond StartingCondState = TheCondState;
369 // While we have input, parse each statement.
370 while (Lexer.isNot(AsmToken::Eof)) {
371 if (!ParseStatement()) continue;
373 // We had an error, remember it and recover by skipping to the next line.
375 EatToEndOfStatement();
378 if (TheCondState.TheCond != StartingCondState.TheCond ||
379 TheCondState.Ignore != StartingCondState.Ignore)
380 return TokError("unmatched .ifs or .elses");
382 // Check to see there are no empty DwarfFile slots.
383 const std::vector<MCDwarfFile *> &MCDwarfFiles =
384 getContext().getMCDwarfFiles();
385 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
386 if (!MCDwarfFiles[i]){
387 TokError("unassigned file number: " + Twine(i) + " for .file directives");
392 // Finalize the output stream if there are no errors and if the client wants
394 if (!HadError && !NoFinalize)
400 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
401 void AsmParser::EatToEndOfStatement() {
402 while (Lexer.isNot(AsmToken::EndOfStatement) &&
403 Lexer.isNot(AsmToken::Eof))
407 if (Lexer.is(AsmToken::EndOfStatement))
411 StringRef AsmParser::ParseStringToEndOfStatement() {
412 const char *Start = getTok().getLoc().getPointer();
414 while (Lexer.isNot(AsmToken::EndOfStatement) &&
415 Lexer.isNot(AsmToken::Eof))
418 const char *End = getTok().getLoc().getPointer();
419 return StringRef(Start, End - Start);
422 /// ParseParenExpr - Parse a paren expression and return it.
423 /// NOTE: This assumes the leading '(' has already been consumed.
425 /// parenexpr ::= expr)
427 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
428 if (ParseExpression(Res)) return true;
429 if (Lexer.isNot(AsmToken::RParen))
430 return TokError("expected ')' in parentheses expression");
431 EndLoc = Lexer.getLoc();
436 /// ParsePrimaryExpr - Parse a primary expression and return it.
437 /// primaryexpr ::= (parenexpr
438 /// primaryexpr ::= symbol
439 /// primaryexpr ::= number
440 /// primaryexpr ::= '.'
441 /// primaryexpr ::= ~,+,- primaryexpr
442 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
443 switch (Lexer.getKind()) {
445 return TokError("unknown token in expression");
446 case AsmToken::Exclaim:
447 Lex(); // Eat the operator.
448 if (ParsePrimaryExpr(Res, EndLoc))
450 Res = MCUnaryExpr::CreateLNot(Res, getContext());
452 case AsmToken::Dollar:
453 case AsmToken::String:
454 case AsmToken::Identifier: {
455 EndLoc = Lexer.getLoc();
457 StringRef Identifier;
458 if (ParseIdentifier(Identifier))
461 // This is a symbol reference.
462 std::pair<StringRef, StringRef> Split = Identifier.split('@');
463 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
465 // Mark the symbol as used in an expression.
466 Sym->setUsedInExpr(true);
468 // Lookup the symbol variant if used.
469 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
470 if (Split.first.size() != Identifier.size())
471 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
473 // If this is an absolute variable reference, substitute it now to preserve
474 // semantics in the face of reassignment.
475 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
477 return Error(EndLoc, "unexpected modified on variable reference");
479 Res = Sym->getVariableValue();
483 // Otherwise create a symbol ref.
484 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
487 case AsmToken::Integer: {
488 SMLoc Loc = getTok().getLoc();
489 int64_t IntVal = getTok().getIntVal();
490 Res = MCConstantExpr::Create(IntVal, getContext());
491 EndLoc = Lexer.getLoc();
493 // Look for 'b' or 'f' following an Integer as a directional label
494 if (Lexer.getKind() == AsmToken::Identifier) {
495 StringRef IDVal = getTok().getString();
496 if (IDVal == "f" || IDVal == "b"){
497 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
498 IDVal == "f" ? 1 : 0);
499 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
501 if(IDVal == "b" && Sym->isUndefined())
502 return Error(Loc, "invalid reference to undefined symbol");
503 EndLoc = Lexer.getLoc();
504 Lex(); // Eat identifier.
509 case AsmToken::Dot: {
510 // This is a '.' reference, which references the current PC. Emit a
511 // temporary label to the streamer and refer to it.
512 MCSymbol *Sym = Ctx.CreateTempSymbol();
514 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
515 EndLoc = Lexer.getLoc();
516 Lex(); // Eat identifier.
520 case AsmToken::LParen:
521 Lex(); // Eat the '('.
522 return ParseParenExpr(Res, EndLoc);
523 case AsmToken::Minus:
524 Lex(); // Eat the operator.
525 if (ParsePrimaryExpr(Res, EndLoc))
527 Res = MCUnaryExpr::CreateMinus(Res, getContext());
530 Lex(); // Eat the operator.
531 if (ParsePrimaryExpr(Res, EndLoc))
533 Res = MCUnaryExpr::CreatePlus(Res, getContext());
535 case AsmToken::Tilde:
536 Lex(); // Eat the operator.
537 if (ParsePrimaryExpr(Res, EndLoc))
539 Res = MCUnaryExpr::CreateNot(Res, getContext());
544 bool AsmParser::ParseExpression(const MCExpr *&Res) {
546 return ParseExpression(Res, EndLoc);
549 /// ParseExpression - Parse an expression and return it.
551 /// expr ::= expr +,- expr -> lowest.
552 /// expr ::= expr |,^,&,! expr -> middle.
553 /// expr ::= expr *,/,%,<<,>> expr -> highest.
554 /// expr ::= primaryexpr
556 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
557 // Parse the expression.
559 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
562 // Try to constant fold it up front, if possible.
564 if (Res->EvaluateAsAbsolute(Value))
565 Res = MCConstantExpr::Create(Value, getContext());
570 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
572 return ParseParenExpr(Res, EndLoc) ||
573 ParseBinOpRHS(1, Res, EndLoc);
576 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
579 SMLoc StartLoc = Lexer.getLoc();
580 if (ParseExpression(Expr))
583 if (!Expr->EvaluateAsAbsolute(Res))
584 return Error(StartLoc, "expected absolute expression");
589 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
590 MCBinaryExpr::Opcode &Kind) {
593 return 0; // not a binop.
595 // Lowest Precedence: &&, ||
596 case AsmToken::AmpAmp:
597 Kind = MCBinaryExpr::LAnd;
599 case AsmToken::PipePipe:
600 Kind = MCBinaryExpr::LOr;
603 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
605 Kind = MCBinaryExpr::Add;
607 case AsmToken::Minus:
608 Kind = MCBinaryExpr::Sub;
610 case AsmToken::EqualEqual:
611 Kind = MCBinaryExpr::EQ;
613 case AsmToken::ExclaimEqual:
614 case AsmToken::LessGreater:
615 Kind = MCBinaryExpr::NE;
618 Kind = MCBinaryExpr::LT;
620 case AsmToken::LessEqual:
621 Kind = MCBinaryExpr::LTE;
623 case AsmToken::Greater:
624 Kind = MCBinaryExpr::GT;
626 case AsmToken::GreaterEqual:
627 Kind = MCBinaryExpr::GTE;
630 // Intermediate Precedence: |, &, ^
632 // FIXME: gas seems to support '!' as an infix operator?
634 Kind = MCBinaryExpr::Or;
636 case AsmToken::Caret:
637 Kind = MCBinaryExpr::Xor;
640 Kind = MCBinaryExpr::And;
643 // Highest Precedence: *, /, %, <<, >>
645 Kind = MCBinaryExpr::Mul;
647 case AsmToken::Slash:
648 Kind = MCBinaryExpr::Div;
650 case AsmToken::Percent:
651 Kind = MCBinaryExpr::Mod;
653 case AsmToken::LessLess:
654 Kind = MCBinaryExpr::Shl;
656 case AsmToken::GreaterGreater:
657 Kind = MCBinaryExpr::Shr;
663 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
664 /// Res contains the LHS of the expression on input.
665 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
668 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
669 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
671 // If the next token is lower precedence than we are allowed to eat, return
672 // successfully with what we ate already.
673 if (TokPrec < Precedence)
678 // Eat the next primary expression.
680 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
682 // If BinOp binds less tightly with RHS than the operator after RHS, let
683 // the pending operator take RHS as its LHS.
684 MCBinaryExpr::Opcode Dummy;
685 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
686 if (TokPrec < NextTokPrec) {
687 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
690 // Merge LHS and RHS according to operator.
691 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
699 /// ::= EndOfStatement
700 /// ::= Label* Directive ...Operands... EndOfStatement
701 /// ::= Label* Identifier OperandList* EndOfStatement
702 bool AsmParser::ParseStatement() {
703 if (Lexer.is(AsmToken::EndOfStatement)) {
709 // Statements always start with an identifier.
710 AsmToken ID = getTok();
711 SMLoc IDLoc = ID.getLoc();
713 int64_t LocalLabelVal = -1;
714 // GUESS allow an integer followed by a ':' as a directional local label
715 if (Lexer.is(AsmToken::Integer)) {
716 LocalLabelVal = getTok().getIntVal();
717 if (LocalLabelVal < 0) {
718 if (!TheCondState.Ignore)
719 return TokError("unexpected token at start of statement");
723 IDVal = getTok().getString();
724 Lex(); // Consume the integer token to be used as an identifier token.
725 if (Lexer.getKind() != AsmToken::Colon) {
726 if (!TheCondState.Ignore)
727 return TokError("unexpected token at start of statement");
731 else if (ParseIdentifier(IDVal)) {
732 if (!TheCondState.Ignore)
733 return TokError("unexpected token at start of statement");
737 // Handle conditional assembly here before checking for skipping. We
738 // have to do this so that .endif isn't skipped in a ".if 0" block for
741 return ParseDirectiveIf(IDLoc);
742 if (IDVal == ".elseif")
743 return ParseDirectiveElseIf(IDLoc);
744 if (IDVal == ".else")
745 return ParseDirectiveElse(IDLoc);
746 if (IDVal == ".endif")
747 return ParseDirectiveEndIf(IDLoc);
749 // If we are in a ".if 0" block, ignore this statement.
750 if (TheCondState.Ignore) {
751 EatToEndOfStatement();
755 // FIXME: Recurse on local labels?
757 // See what kind of statement we have.
758 switch (Lexer.getKind()) {
759 case AsmToken::Colon: {
760 // identifier ':' -> Label.
763 // Diagnose attempt to use a variable as a label.
765 // FIXME: Diagnostics. Note the location of the definition as a label.
766 // FIXME: This doesn't diagnose assignment to a symbol which has been
767 // implicitly marked as external.
769 if (LocalLabelVal == -1)
770 Sym = getContext().GetOrCreateSymbol(IDVal);
772 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
773 if (!Sym->isUndefined() || Sym->isVariable())
774 return Error(IDLoc, "invalid symbol redefinition");
779 // Consume any end of statement token, if present, to avoid spurious
780 // AddBlankLine calls().
781 if (Lexer.is(AsmToken::EndOfStatement)) {
783 if (Lexer.is(AsmToken::Eof))
787 return ParseStatement();
790 case AsmToken::Equal:
791 // identifier '=' ... -> assignment statement
794 return ParseAssignment(IDVal);
796 default: // Normal instruction or directive.
800 // If macros are enabled, check to see if this is a macro instantiation.
802 if (const Macro *M = MacroMap.lookup(IDVal))
803 return HandleMacroEntry(IDVal, IDLoc, M);
805 // Otherwise, we have a normal instruction or directive.
806 if (IDVal[0] == '.') {
807 // Assembler features
809 return ParseDirectiveSet();
813 if (IDVal == ".ascii")
814 return ParseDirectiveAscii(false);
815 if (IDVal == ".asciz")
816 return ParseDirectiveAscii(true);
818 if (IDVal == ".byte")
819 return ParseDirectiveValue(1);
820 if (IDVal == ".short")
821 return ParseDirectiveValue(2);
822 if (IDVal == ".long")
823 return ParseDirectiveValue(4);
824 if (IDVal == ".quad")
825 return ParseDirectiveValue(8);
827 if (IDVal == ".align") {
828 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
829 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
831 if (IDVal == ".align32") {
832 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
833 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
835 if (IDVal == ".balign")
836 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
837 if (IDVal == ".balignw")
838 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
839 if (IDVal == ".balignl")
840 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
841 if (IDVal == ".p2align")
842 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
843 if (IDVal == ".p2alignw")
844 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
845 if (IDVal == ".p2alignl")
846 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
849 return ParseDirectiveOrg();
851 if (IDVal == ".fill")
852 return ParseDirectiveFill();
853 if (IDVal == ".space")
854 return ParseDirectiveSpace();
856 // Symbol attribute directives
858 if (IDVal == ".globl" || IDVal == ".global")
859 return ParseDirectiveSymbolAttribute(MCSA_Global);
860 if (IDVal == ".hidden")
861 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
862 if (IDVal == ".indirect_symbol")
863 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
864 if (IDVal == ".internal")
865 return ParseDirectiveSymbolAttribute(MCSA_Internal);
866 if (IDVal == ".lazy_reference")
867 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
868 if (IDVal == ".no_dead_strip")
869 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
870 if (IDVal == ".private_extern")
871 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
872 if (IDVal == ".protected")
873 return ParseDirectiveSymbolAttribute(MCSA_Protected);
874 if (IDVal == ".reference")
875 return ParseDirectiveSymbolAttribute(MCSA_Reference);
876 if (IDVal == ".type")
877 return ParseDirectiveELFType();
878 if (IDVal == ".weak")
879 return ParseDirectiveSymbolAttribute(MCSA_Weak);
880 if (IDVal == ".weak_definition")
881 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
882 if (IDVal == ".weak_reference")
883 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
884 if (IDVal == ".weak_def_can_be_hidden")
885 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
887 if (IDVal == ".comm")
888 return ParseDirectiveComm(/*IsLocal=*/false);
889 if (IDVal == ".lcomm")
890 return ParseDirectiveComm(/*IsLocal=*/true);
892 if (IDVal == ".abort")
893 return ParseDirectiveAbort();
894 if (IDVal == ".include")
895 return ParseDirectiveInclude();
897 // Look up the handler in the handler table.
898 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
899 DirectiveMap.lookup(IDVal);
901 return (*Handler.second)(Handler.first, IDVal, IDLoc);
903 // Target hook for parsing target specific directives.
904 if (!getTargetParser().ParseDirective(ID))
907 Warning(IDLoc, "ignoring directive for now");
908 EatToEndOfStatement();
912 // Canonicalize the opcode to lower case.
913 SmallString<128> Opcode;
914 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
915 Opcode.push_back(tolower(IDVal[i]));
917 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
918 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
920 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
921 HadError = TokError("unexpected token in argument list");
923 // Dump the parsed representation, if requested.
924 if (getShowParsedOperands()) {
925 SmallString<256> Str;
926 raw_svector_ostream OS(Str);
927 OS << "parsed instruction: [";
928 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
931 ParsedOperands[i]->dump(OS);
935 PrintMessage(IDLoc, OS.str(), "note");
938 // If parsing succeeded, match the instruction.
941 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
942 // Emit the instruction on success.
943 Out.EmitInstruction(Inst);
948 // If there was no error, consume the end-of-statement token. Otherwise this
949 // will be done by our caller.
953 // Free any parsed operands.
954 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
955 delete ParsedOperands[i];
960 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
961 const std::vector<std::vector<AsmToken> > &A)
962 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
964 // Macro instantiation is lexical, unfortunately. We construct a new buffer
965 // to hold the macro body with substitutions.
966 SmallString<256> Buf;
967 raw_svector_ostream OS(Buf);
969 StringRef Body = M->Body;
970 while (!Body.empty()) {
971 // Scan for the next substitution.
972 std::size_t End = Body.size(), Pos = 0;
973 for (; Pos != End; ++Pos) {
974 // Check for a substitution or escape.
975 if (Body[Pos] != '$' || Pos + 1 == End)
978 char Next = Body[Pos + 1];
979 if (Next == '$' || Next == 'n' || isdigit(Next))
984 OS << Body.slice(0, Pos);
986 // Check if we reached the end.
990 switch (Body[Pos+1]) {
996 // $n => number of arguments
1001 // $[0-9] => argument
1003 // Missing arguments are ignored.
1004 unsigned Index = Body[Pos+1] - '0';
1005 if (Index >= A.size())
1008 // Otherwise substitute with the token values, with spaces eliminated.
1009 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1010 ie = A[Index].end(); it != ie; ++it)
1011 OS << it->getString();
1016 // Update the scan point.
1017 Body = Body.substr(Pos + 2);
1020 // We include the .endmacro in the buffer as our queue to exit the macro
1022 OS << ".endmacro\n";
1024 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1027 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1029 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1030 // this, although we should protect against infinite loops.
1031 if (ActiveMacros.size() == 20)
1032 return TokError("macros cannot be nested more than 20 levels deep");
1034 // Parse the macro instantiation arguments.
1035 std::vector<std::vector<AsmToken> > MacroArguments;
1036 MacroArguments.push_back(std::vector<AsmToken>());
1037 unsigned ParenLevel = 0;
1039 if (Lexer.is(AsmToken::Eof))
1040 return TokError("unexpected token in macro instantiation");
1041 if (Lexer.is(AsmToken::EndOfStatement))
1044 // If we aren't inside parentheses and this is a comma, start a new token
1046 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1047 MacroArguments.push_back(std::vector<AsmToken>());
1049 // Adjust the current parentheses level.
1050 if (Lexer.is(AsmToken::LParen))
1052 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1055 // Append the token to the current argument list.
1056 MacroArguments.back().push_back(getTok());
1061 // Create the macro instantiation object and add to the current macro
1062 // instantiation stack.
1063 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1066 ActiveMacros.push_back(MI);
1068 // Jump to the macro instantiation and prime the lexer.
1069 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1070 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1076 void AsmParser::HandleMacroExit() {
1077 // Jump to the EndOfStatement we should return to, and consume it.
1078 JumpToLoc(ActiveMacros.back()->ExitLoc);
1081 // Pop the instantiation entry.
1082 delete ActiveMacros.back();
1083 ActiveMacros.pop_back();
1086 bool AsmParser::ParseAssignment(StringRef Name) {
1087 // FIXME: Use better location, we should use proper tokens.
1088 SMLoc EqualLoc = Lexer.getLoc();
1090 const MCExpr *Value;
1091 if (ParseExpression(Value))
1094 if (Lexer.isNot(AsmToken::EndOfStatement))
1095 return TokError("unexpected token in assignment");
1097 // Eat the end of statement marker.
1100 // Validate that the LHS is allowed to be a variable (either it has not been
1101 // used as a symbol, or it is an absolute symbol).
1102 MCSymbol *Sym = getContext().LookupSymbol(Name);
1104 // Diagnose assignment to a label.
1106 // FIXME: Diagnostics. Note the location of the definition as a label.
1107 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1108 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1109 ; // Allow redefinitions of undefined symbols only used in directives.
1110 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1111 return Error(EqualLoc, "redefinition of '" + Name + "'");
1112 else if (!Sym->isVariable())
1113 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1114 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1115 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1118 Sym = getContext().GetOrCreateSymbol(Name);
1120 // FIXME: Handle '.'.
1122 Sym->setUsedInExpr(true);
1124 // Do the assignment.
1125 Out.EmitAssignment(Sym, Value);
1130 /// ParseIdentifier:
1133 bool AsmParser::ParseIdentifier(StringRef &Res) {
1134 // The assembler has relaxed rules for accepting identifiers, in particular we
1135 // allow things like '.globl $foo', which would normally be separate
1136 // tokens. At this level, we have already lexed so we cannot (currently)
1137 // handle this as a context dependent token, instead we detect adjacent tokens
1138 // and return the combined identifier.
1139 if (Lexer.is(AsmToken::Dollar)) {
1140 SMLoc DollarLoc = getLexer().getLoc();
1142 // Consume the dollar sign, and check for a following identifier.
1144 if (Lexer.isNot(AsmToken::Identifier))
1147 // We have a '$' followed by an identifier, make sure they are adjacent.
1148 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1151 // Construct the joined identifier and consume the token.
1152 Res = StringRef(DollarLoc.getPointer(),
1153 getTok().getIdentifier().size() + 1);
1158 if (Lexer.isNot(AsmToken::Identifier) &&
1159 Lexer.isNot(AsmToken::String))
1162 Res = getTok().getIdentifier();
1164 Lex(); // Consume the identifier token.
1169 /// ParseDirectiveSet:
1170 /// ::= .set identifier ',' expression
1171 bool AsmParser::ParseDirectiveSet() {
1174 if (ParseIdentifier(Name))
1175 return TokError("expected identifier after '.set' directive");
1177 if (getLexer().isNot(AsmToken::Comma))
1178 return TokError("unexpected token in '.set'");
1181 return ParseAssignment(Name);
1184 bool AsmParser::ParseEscapedString(std::string &Data) {
1185 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1188 StringRef Str = getTok().getStringContents();
1189 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1190 if (Str[i] != '\\') {
1195 // Recognize escaped characters. Note that this escape semantics currently
1196 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1199 return TokError("unexpected backslash at end of string");
1201 // Recognize octal sequences.
1202 if ((unsigned) (Str[i] - '0') <= 7) {
1203 // Consume up to three octal characters.
1204 unsigned Value = Str[i] - '0';
1206 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1208 Value = Value * 8 + (Str[i] - '0');
1210 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1212 Value = Value * 8 + (Str[i] - '0');
1217 return TokError("invalid octal escape sequence (out of range)");
1219 Data += (unsigned char) Value;
1223 // Otherwise recognize individual escapes.
1226 // Just reject invalid escape sequences for now.
1227 return TokError("invalid escape sequence (unrecognized character)");
1229 case 'b': Data += '\b'; break;
1230 case 'f': Data += '\f'; break;
1231 case 'n': Data += '\n'; break;
1232 case 'r': Data += '\r'; break;
1233 case 't': Data += '\t'; break;
1234 case '"': Data += '"'; break;
1235 case '\\': Data += '\\'; break;
1242 /// ParseDirectiveAscii:
1243 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1244 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1245 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1247 if (getLexer().isNot(AsmToken::String))
1248 return TokError("expected string in '.ascii' or '.asciz' directive");
1251 if (ParseEscapedString(Data))
1254 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1256 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1260 if (getLexer().is(AsmToken::EndOfStatement))
1263 if (getLexer().isNot(AsmToken::Comma))
1264 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1273 /// ParseDirectiveValue
1274 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1275 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1276 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1278 const MCExpr *Value;
1279 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1280 if (ParseExpression(Value))
1283 // Special case constant expressions to match code generator.
1284 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1285 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1287 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1289 if (getLexer().is(AsmToken::EndOfStatement))
1292 // FIXME: Improve diagnostic.
1293 if (getLexer().isNot(AsmToken::Comma))
1294 return TokError("unexpected token in directive");
1303 /// ParseDirectiveSpace
1304 /// ::= .space expression [ , expression ]
1305 bool AsmParser::ParseDirectiveSpace() {
1307 if (ParseAbsoluteExpression(NumBytes))
1310 int64_t FillExpr = 0;
1311 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1312 if (getLexer().isNot(AsmToken::Comma))
1313 return TokError("unexpected token in '.space' directive");
1316 if (ParseAbsoluteExpression(FillExpr))
1319 if (getLexer().isNot(AsmToken::EndOfStatement))
1320 return TokError("unexpected token in '.space' directive");
1326 return TokError("invalid number of bytes in '.space' directive");
1328 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1329 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1334 /// ParseDirectiveFill
1335 /// ::= .fill expression , expression , expression
1336 bool AsmParser::ParseDirectiveFill() {
1338 if (ParseAbsoluteExpression(NumValues))
1341 if (getLexer().isNot(AsmToken::Comma))
1342 return TokError("unexpected token in '.fill' directive");
1346 if (ParseAbsoluteExpression(FillSize))
1349 if (getLexer().isNot(AsmToken::Comma))
1350 return TokError("unexpected token in '.fill' directive");
1354 if (ParseAbsoluteExpression(FillExpr))
1357 if (getLexer().isNot(AsmToken::EndOfStatement))
1358 return TokError("unexpected token in '.fill' directive");
1362 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1363 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1365 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1366 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1371 /// ParseDirectiveOrg
1372 /// ::= .org expression [ , expression ]
1373 bool AsmParser::ParseDirectiveOrg() {
1374 const MCExpr *Offset;
1375 if (ParseExpression(Offset))
1378 // Parse optional fill expression.
1379 int64_t FillExpr = 0;
1380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1381 if (getLexer().isNot(AsmToken::Comma))
1382 return TokError("unexpected token in '.org' directive");
1385 if (ParseAbsoluteExpression(FillExpr))
1388 if (getLexer().isNot(AsmToken::EndOfStatement))
1389 return TokError("unexpected token in '.org' directive");
1394 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1395 // has to be relative to the current section.
1396 getStreamer().EmitValueToOffset(Offset, FillExpr);
1401 /// ParseDirectiveAlign
1402 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1403 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1404 SMLoc AlignmentLoc = getLexer().getLoc();
1406 if (ParseAbsoluteExpression(Alignment))
1410 bool HasFillExpr = false;
1411 int64_t FillExpr = 0;
1412 int64_t MaxBytesToFill = 0;
1413 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1414 if (getLexer().isNot(AsmToken::Comma))
1415 return TokError("unexpected token in directive");
1418 // The fill expression can be omitted while specifying a maximum number of
1419 // alignment bytes, e.g:
1421 if (getLexer().isNot(AsmToken::Comma)) {
1423 if (ParseAbsoluteExpression(FillExpr))
1427 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1428 if (getLexer().isNot(AsmToken::Comma))
1429 return TokError("unexpected token in directive");
1432 MaxBytesLoc = getLexer().getLoc();
1433 if (ParseAbsoluteExpression(MaxBytesToFill))
1436 if (getLexer().isNot(AsmToken::EndOfStatement))
1437 return TokError("unexpected token in directive");
1446 // Compute alignment in bytes.
1448 // FIXME: Diagnose overflow.
1449 if (Alignment >= 32) {
1450 Error(AlignmentLoc, "invalid alignment value");
1454 Alignment = 1ULL << Alignment;
1457 // Diagnose non-sensical max bytes to align.
1458 if (MaxBytesLoc.isValid()) {
1459 if (MaxBytesToFill < 1) {
1460 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1461 "many bytes, ignoring maximum bytes expression");
1465 if (MaxBytesToFill >= Alignment) {
1466 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1472 // Check whether we should use optimal code alignment for this .align
1475 // FIXME: This should be using a target hook.
1476 bool UseCodeAlign = false;
1477 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1478 getStreamer().getCurrentSection()))
1479 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1480 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1481 ValueSize == 1 && UseCodeAlign) {
1482 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1484 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1485 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1492 /// ParseDirectiveSymbolAttribute
1493 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1494 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1495 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1499 if (ParseIdentifier(Name))
1500 return TokError("expected identifier in directive");
1502 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1504 getStreamer().EmitSymbolAttribute(Sym, Attr);
1506 if (getLexer().is(AsmToken::EndOfStatement))
1509 if (getLexer().isNot(AsmToken::Comma))
1510 return TokError("unexpected token in directive");
1519 /// ParseDirectiveELFType
1520 /// ::= .type identifier , @attribute
1521 bool AsmParser::ParseDirectiveELFType() {
1523 if (ParseIdentifier(Name))
1524 return TokError("expected identifier in directive");
1526 // Handle the identifier as the key symbol.
1527 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1529 if (getLexer().isNot(AsmToken::Comma))
1530 return TokError("unexpected token in '.type' directive");
1533 if (getLexer().isNot(AsmToken::At))
1534 return TokError("expected '@' before type");
1540 TypeLoc = getLexer().getLoc();
1541 if (ParseIdentifier(Type))
1542 return TokError("expected symbol type in directive");
1544 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1545 .Case("function", MCSA_ELF_TypeFunction)
1546 .Case("object", MCSA_ELF_TypeObject)
1547 .Case("tls_object", MCSA_ELF_TypeTLS)
1548 .Case("common", MCSA_ELF_TypeCommon)
1549 .Case("notype", MCSA_ELF_TypeNoType)
1550 .Default(MCSA_Invalid);
1552 if (Attr == MCSA_Invalid)
1553 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1555 if (getLexer().isNot(AsmToken::EndOfStatement))
1556 return TokError("unexpected token in '.type' directive");
1560 getStreamer().EmitSymbolAttribute(Sym, Attr);
1565 /// ParseDirectiveComm
1566 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1567 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1568 SMLoc IDLoc = getLexer().getLoc();
1570 if (ParseIdentifier(Name))
1571 return TokError("expected identifier in directive");
1573 // Handle the identifier as the key symbol.
1574 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1576 if (getLexer().isNot(AsmToken::Comma))
1577 return TokError("unexpected token in directive");
1581 SMLoc SizeLoc = getLexer().getLoc();
1582 if (ParseAbsoluteExpression(Size))
1585 int64_t Pow2Alignment = 0;
1586 SMLoc Pow2AlignmentLoc;
1587 if (getLexer().is(AsmToken::Comma)) {
1589 Pow2AlignmentLoc = getLexer().getLoc();
1590 if (ParseAbsoluteExpression(Pow2Alignment))
1593 // If this target takes alignments in bytes (not log) validate and convert.
1594 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1595 if (!isPowerOf2_64(Pow2Alignment))
1596 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1597 Pow2Alignment = Log2_64(Pow2Alignment);
1601 if (getLexer().isNot(AsmToken::EndOfStatement))
1602 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1606 // NOTE: a size of zero for a .comm should create a undefined symbol
1607 // but a size of .lcomm creates a bss symbol of size zero.
1609 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1610 "be less than zero");
1612 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1613 // may internally end up wanting an alignment in bytes.
1614 // FIXME: Diagnose overflow.
1615 if (Pow2Alignment < 0)
1616 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1617 "alignment, can't be less than zero");
1619 if (!Sym->isUndefined())
1620 return Error(IDLoc, "invalid symbol redefinition");
1622 // '.lcomm' is equivalent to '.zerofill'.
1623 // Create the Symbol as a common or local common with Size and Pow2Alignment
1625 getStreamer().EmitZerofill(Ctx.getMachOSection(
1626 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1627 0, SectionKind::getBSS()),
1628 Sym, Size, 1 << Pow2Alignment);
1632 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1636 /// ParseDirectiveAbort
1637 /// ::= .abort [... message ...]
1638 bool AsmParser::ParseDirectiveAbort() {
1639 // FIXME: Use loc from directive.
1640 SMLoc Loc = getLexer().getLoc();
1642 StringRef Str = ParseStringToEndOfStatement();
1643 if (getLexer().isNot(AsmToken::EndOfStatement))
1644 return TokError("unexpected token in '.abort' directive");
1649 Error(Loc, ".abort detected. Assembly stopping.");
1651 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1652 // FIXME: Actually abort assembly here.
1657 /// ParseDirectiveInclude
1658 /// ::= .include "filename"
1659 bool AsmParser::ParseDirectiveInclude() {
1660 if (getLexer().isNot(AsmToken::String))
1661 return TokError("expected string in '.include' directive");
1663 std::string Filename = getTok().getString();
1664 SMLoc IncludeLoc = getLexer().getLoc();
1667 if (getLexer().isNot(AsmToken::EndOfStatement))
1668 return TokError("unexpected token in '.include' directive");
1670 // Strip the quotes.
1671 Filename = Filename.substr(1, Filename.size()-2);
1673 // Attempt to switch the lexer to the included file before consuming the end
1674 // of statement to avoid losing it when we switch.
1675 if (EnterIncludeFile(Filename)) {
1676 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1683 /// ParseDirectiveIf
1684 /// ::= .if expression
1685 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1686 TheCondStack.push_back(TheCondState);
1687 TheCondState.TheCond = AsmCond::IfCond;
1688 if(TheCondState.Ignore) {
1689 EatToEndOfStatement();
1693 if (ParseAbsoluteExpression(ExprValue))
1696 if (getLexer().isNot(AsmToken::EndOfStatement))
1697 return TokError("unexpected token in '.if' directive");
1701 TheCondState.CondMet = ExprValue;
1702 TheCondState.Ignore = !TheCondState.CondMet;
1708 /// ParseDirectiveElseIf
1709 /// ::= .elseif expression
1710 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1711 if (TheCondState.TheCond != AsmCond::IfCond &&
1712 TheCondState.TheCond != AsmCond::ElseIfCond)
1713 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1715 TheCondState.TheCond = AsmCond::ElseIfCond;
1717 bool LastIgnoreState = false;
1718 if (!TheCondStack.empty())
1719 LastIgnoreState = TheCondStack.back().Ignore;
1720 if (LastIgnoreState || TheCondState.CondMet) {
1721 TheCondState.Ignore = true;
1722 EatToEndOfStatement();
1726 if (ParseAbsoluteExpression(ExprValue))
1729 if (getLexer().isNot(AsmToken::EndOfStatement))
1730 return TokError("unexpected token in '.elseif' directive");
1733 TheCondState.CondMet = ExprValue;
1734 TheCondState.Ignore = !TheCondState.CondMet;
1740 /// ParseDirectiveElse
1742 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1743 if (getLexer().isNot(AsmToken::EndOfStatement))
1744 return TokError("unexpected token in '.else' directive");
1748 if (TheCondState.TheCond != AsmCond::IfCond &&
1749 TheCondState.TheCond != AsmCond::ElseIfCond)
1750 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1752 TheCondState.TheCond = AsmCond::ElseCond;
1753 bool LastIgnoreState = false;
1754 if (!TheCondStack.empty())
1755 LastIgnoreState = TheCondStack.back().Ignore;
1756 if (LastIgnoreState || TheCondState.CondMet)
1757 TheCondState.Ignore = true;
1759 TheCondState.Ignore = false;
1764 /// ParseDirectiveEndIf
1766 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1767 if (getLexer().isNot(AsmToken::EndOfStatement))
1768 return TokError("unexpected token in '.endif' directive");
1772 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1773 TheCondStack.empty())
1774 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1776 if (!TheCondStack.empty()) {
1777 TheCondState = TheCondStack.back();
1778 TheCondStack.pop_back();
1784 /// ParseDirectiveFile
1785 /// ::= .file [number] string
1786 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1787 // FIXME: I'm not sure what this is.
1788 int64_t FileNumber = -1;
1789 SMLoc FileNumberLoc = getLexer().getLoc();
1790 if (getLexer().is(AsmToken::Integer)) {
1791 FileNumber = getTok().getIntVal();
1795 return TokError("file number less than one");
1798 if (getLexer().isNot(AsmToken::String))
1799 return TokError("unexpected token in '.file' directive");
1801 StringRef Filename = getTok().getString();
1802 Filename = Filename.substr(1, Filename.size()-2);
1805 if (getLexer().isNot(AsmToken::EndOfStatement))
1806 return TokError("unexpected token in '.file' directive");
1808 if (FileNumber == -1)
1809 getStreamer().EmitFileDirective(Filename);
1811 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1812 Error(FileNumberLoc, "file number already allocated");
1813 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1819 /// ParseDirectiveLine
1820 /// ::= .line [number]
1821 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1822 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1823 if (getLexer().isNot(AsmToken::Integer))
1824 return TokError("unexpected token in '.line' directive");
1826 int64_t LineNumber = getTok().getIntVal();
1830 // FIXME: Do something with the .line.
1833 if (getLexer().isNot(AsmToken::EndOfStatement))
1834 return TokError("unexpected token in '.line' directive");
1840 /// ParseDirectiveLoc
1841 /// ::= .loc FileNumber LineNumber [ColumnPos] [basic_block] [prologue_end]
1842 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1843 /// The first number is a file number, must have been previously assigned with
1844 /// a .file directive, the second number is the line number and optionally the
1845 /// third number is a column position (zero if not specified). The remaining
1846 /// optional items are .loc sub-directives.
1847 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1849 if (getLexer().isNot(AsmToken::Integer))
1850 return TokError("unexpected token in '.loc' directive");
1851 int64_t FileNumber = getTok().getIntVal();
1853 return TokError("file number less than one in '.loc' directive");
1854 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1855 return TokError("unassigned file number in '.loc' directive");
1858 if (getLexer().isNot(AsmToken::Integer))
1859 return TokError("unexpected token in '.loc' directive");
1860 int64_t LineNumber = getTok().getIntVal();
1862 return TokError("line number less than one in '.loc' directive");
1865 int64_t ColumnPos = 0;
1866 if (getLexer().is(AsmToken::Integer)) {
1867 ColumnPos = getTok().getIntVal();
1869 return TokError("column position less than zero in '.loc' directive");
1875 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1877 if (getLexer().is(AsmToken::EndOfStatement))
1881 SMLoc Loc = getTok().getLoc();
1882 if (getParser().ParseIdentifier(Name))
1883 return TokError("unexpected token in '.loc' directive");
1885 if (Name == "basic_block")
1886 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1887 else if (Name == "prologue_end")
1888 Flags |= DWARF2_FLAG_PROLOGUE_END;
1889 else if (Name == "epilogue_begin")
1890 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1891 else if (Name == "is_stmt") {
1892 SMLoc Loc = getTok().getLoc();
1893 const MCExpr *Value;
1894 if (getParser().ParseExpression(Value))
1896 // The expression must be the constant 0 or 1.
1897 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1898 int Value = MCE->getValue();
1900 Flags &= ~DWARF2_FLAG_IS_STMT;
1901 else if (Value == 1)
1902 Flags |= DWARF2_FLAG_IS_STMT;
1904 return Error(Loc, "is_stmt value not 0 or 1");
1907 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1910 else if (Name == "isa") {
1911 SMLoc Loc = getTok().getLoc();
1912 const MCExpr *Value;
1913 if (getParser().ParseExpression(Value))
1915 // The expression must be a constant greater or equal to 0.
1916 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1917 int Value = MCE->getValue();
1919 return Error(Loc, "isa number less than zero");
1923 return Error(Loc, "isa number not a constant value");
1927 return Error(Loc, "unknown sub-directive in '.loc' directive");
1930 if (getLexer().is(AsmToken::EndOfStatement))
1935 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1940 /// ParseDirectiveMacrosOnOff
1943 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1944 SMLoc DirectiveLoc) {
1945 if (getLexer().isNot(AsmToken::EndOfStatement))
1946 return Error(getLexer().getLoc(),
1947 "unexpected token in '" + Directive + "' directive");
1949 getParser().MacrosEnabled = Directive == ".macros_on";
1954 /// ParseDirectiveMacro
1956 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1957 SMLoc DirectiveLoc) {
1959 if (getParser().ParseIdentifier(Name))
1960 return TokError("expected identifier in directive");
1962 if (getLexer().isNot(AsmToken::EndOfStatement))
1963 return TokError("unexpected token in '.macro' directive");
1965 // Eat the end of statement.
1968 AsmToken EndToken, StartToken = getTok();
1970 // Lex the macro definition.
1972 // Check whether we have reached the end of the file.
1973 if (getLexer().is(AsmToken::Eof))
1974 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1976 // Otherwise, check whether we have reach the .endmacro.
1977 if (getLexer().is(AsmToken::Identifier) &&
1978 (getTok().getIdentifier() == ".endm" ||
1979 getTok().getIdentifier() == ".endmacro")) {
1980 EndToken = getTok();
1982 if (getLexer().isNot(AsmToken::EndOfStatement))
1983 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1988 // Otherwise, scan til the end of the statement.
1989 getParser().EatToEndOfStatement();
1992 if (getParser().MacroMap.lookup(Name)) {
1993 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1996 const char *BodyStart = StartToken.getLoc().getPointer();
1997 const char *BodyEnd = EndToken.getLoc().getPointer();
1998 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1999 getParser().MacroMap[Name] = new Macro(Name, Body);
2003 /// ParseDirectiveEndMacro
2006 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2007 SMLoc DirectiveLoc) {
2008 if (getLexer().isNot(AsmToken::EndOfStatement))
2009 return TokError("unexpected token in '" + Directive + "' directive");
2011 // If we are inside a macro instantiation, terminate the current
2013 if (!getParser().ActiveMacros.empty()) {
2014 getParser().HandleMacroExit();
2018 // Otherwise, this .endmacro is a stray entry in the file; well formed
2019 // .endmacro directives are handled during the macro definition parsing.
2020 return TokError("unexpected '" + Directive + "' in file, "
2021 "no current macro definition");
2024 /// \brief Create an MCAsmParser instance.
2025 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2026 MCContext &C, MCStreamer &Out,
2027 const MCAsmInfo &MAI) {
2028 return new AsmParser(T, SM, C, Out, MAI);