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 bool ParseStatement();
145 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
146 void HandleMacroExit();
148 void PrintMacroInstantiations();
149 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
151 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
152 bool EnterIncludeFile(const std::string &Filename);
154 /// \brief Reset the current lexer position to that given by \arg Loc. The
155 /// current token is not set; clients should ensure Lex() is called
157 void JumpToLoc(SMLoc Loc);
159 void EatToEndOfStatement();
161 /// \brief Parse up to the end of statement and a return the contents from the
162 /// current token until the end of the statement; the current token on exit
163 /// will be either the EndOfStatement or EOF.
164 StringRef ParseStringToEndOfStatement();
166 bool ParseAssignment(StringRef Name);
168 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
169 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
170 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
172 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
173 /// and set \arg Res to the identifier contents.
174 bool ParseIdentifier(StringRef &Res);
176 // Directive Parsing.
177 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
178 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
179 bool ParseDirectiveFill(); // ".fill"
180 bool ParseDirectiveSpace(); // ".space"
181 bool ParseDirectiveSet(); // ".set"
182 bool ParseDirectiveOrg(); // ".org"
183 // ".align{,32}", ".p2align{,w,l}"
184 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
186 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
187 /// accepts a single symbol (which should be a label or an external).
188 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
189 bool ParseDirectiveELFType(); // ELF specific ".type"
191 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
193 bool ParseDirectiveAbort(); // ".abort"
194 bool ParseDirectiveInclude(); // ".include"
196 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
197 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
198 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
199 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
201 /// ParseEscapedString - Parse the current token as a string which may include
202 /// escaped characters and return the string contents.
203 bool ParseEscapedString(std::string &Data);
206 /// \brief Generic implementations of directive handling, etc. which is shared
207 /// (or the default, at least) for all assembler parser.
208 class GenericAsmParser : public MCAsmParserExtension {
209 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
210 void AddDirectiveHandler(StringRef Directive) {
211 getParser().AddDirectiveHandler(this, Directive,
212 HandleDirective<GenericAsmParser, Handler>);
216 GenericAsmParser() {}
218 AsmParser &getParser() {
219 return (AsmParser&) this->MCAsmParserExtension::getParser();
222 virtual void Initialize(MCAsmParser &Parser) {
223 // Call the base implementation.
224 this->MCAsmParserExtension::Initialize(Parser);
226 // Debugging directives.
227 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
228 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
229 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
232 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
241 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
242 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
243 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
245 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
246 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
247 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
254 extern MCAsmParserExtension *createDarwinAsmParser();
255 extern MCAsmParserExtension *createELFAsmParser();
259 enum { DEFAULT_ADDRSPACE = 0 };
261 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
262 MCStreamer &_Out, const MCAsmInfo &_MAI)
263 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
264 GenericParser(new GenericAsmParser), PlatformParser(0),
265 CurBuffer(0), MacrosEnabled(true) {
266 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
268 // Initialize the generic parser.
269 GenericParser->Initialize(*this);
271 // Initialize the platform / file format parser.
273 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
275 if (_MAI.hasSubsectionsViaSymbols()) {
276 PlatformParser = createDarwinAsmParser();
277 PlatformParser->Initialize(*this);
279 PlatformParser = createELFAsmParser();
280 PlatformParser->Initialize(*this);
284 AsmParser::~AsmParser() {
285 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
287 // Destroy any macros.
288 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
289 ie = MacroMap.end(); it != ie; ++it)
290 delete it->getValue();
292 delete PlatformParser;
293 delete GenericParser;
296 void AsmParser::PrintMacroInstantiations() {
297 // Print the active macro instantiation stack.
298 for (std::vector<MacroInstantiation*>::const_reverse_iterator
299 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
300 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
304 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
305 PrintMessage(L, Msg.str(), "warning");
306 PrintMacroInstantiations();
309 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
311 PrintMessage(L, Msg.str(), "error");
312 PrintMacroInstantiations();
316 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
317 const char *Type) const {
318 SrcMgr.PrintMessage(Loc, Msg, Type);
321 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
322 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
328 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
333 void AsmParser::JumpToLoc(SMLoc Loc) {
334 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
335 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
338 const AsmToken &AsmParser::Lex() {
339 const AsmToken *tok = &Lexer.Lex();
341 if (tok->is(AsmToken::Eof)) {
342 // If this is the end of an included file, pop the parent file off the
344 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
345 if (ParentIncludeLoc != SMLoc()) {
346 JumpToLoc(ParentIncludeLoc);
351 if (tok->is(AsmToken::Error))
352 Error(Lexer.getErrLoc(), Lexer.getErr());
357 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
358 // Create the initial section, if requested.
360 // FIXME: Target hook & command line option for initial section.
361 if (!NoInitialTextSection)
362 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
363 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
364 0, SectionKind::getText()));
370 AsmCond StartingCondState = TheCondState;
372 // While we have input, parse each statement.
373 while (Lexer.isNot(AsmToken::Eof)) {
374 if (!ParseStatement()) continue;
376 // We had an error, validate that one was emitted and recover by skipping to
378 assert(HadError && "Parse statement returned an error, but none emitted!");
379 EatToEndOfStatement();
382 if (TheCondState.TheCond != StartingCondState.TheCond ||
383 TheCondState.Ignore != StartingCondState.Ignore)
384 return TokError("unmatched .ifs or .elses");
386 // Check to see there are no empty DwarfFile slots.
387 const std::vector<MCDwarfFile *> &MCDwarfFiles =
388 getContext().getMCDwarfFiles();
389 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
390 if (!MCDwarfFiles[i])
391 TokError("unassigned file number: " + Twine(i) + " for .file directives");
394 // Finalize the output stream if there are no errors and if the client wants
396 if (!HadError && !NoFinalize)
402 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
403 void AsmParser::EatToEndOfStatement() {
404 while (Lexer.isNot(AsmToken::EndOfStatement) &&
405 Lexer.isNot(AsmToken::Eof))
409 if (Lexer.is(AsmToken::EndOfStatement))
413 StringRef AsmParser::ParseStringToEndOfStatement() {
414 const char *Start = getTok().getLoc().getPointer();
416 while (Lexer.isNot(AsmToken::EndOfStatement) &&
417 Lexer.isNot(AsmToken::Eof))
420 const char *End = getTok().getLoc().getPointer();
421 return StringRef(Start, End - Start);
424 /// ParseParenExpr - Parse a paren expression and return it.
425 /// NOTE: This assumes the leading '(' has already been consumed.
427 /// parenexpr ::= expr)
429 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
430 if (ParseExpression(Res)) return true;
431 if (Lexer.isNot(AsmToken::RParen))
432 return TokError("expected ')' in parentheses expression");
433 EndLoc = Lexer.getLoc();
438 /// ParsePrimaryExpr - Parse a primary expression and return it.
439 /// primaryexpr ::= (parenexpr
440 /// primaryexpr ::= symbol
441 /// primaryexpr ::= number
442 /// primaryexpr ::= '.'
443 /// primaryexpr ::= ~,+,- primaryexpr
444 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
445 switch (Lexer.getKind()) {
447 return TokError("unknown token in expression");
448 case AsmToken::Exclaim:
449 Lex(); // Eat the operator.
450 if (ParsePrimaryExpr(Res, EndLoc))
452 Res = MCUnaryExpr::CreateLNot(Res, getContext());
454 case AsmToken::Dollar:
455 case AsmToken::String:
456 case AsmToken::Identifier: {
457 EndLoc = Lexer.getLoc();
459 StringRef Identifier;
460 if (ParseIdentifier(Identifier))
463 // This is a symbol reference.
464 std::pair<StringRef, StringRef> Split = Identifier.split('@');
465 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
467 // Mark the symbol as used in an expression.
468 Sym->setUsedInExpr(true);
470 // Lookup the symbol variant if used.
471 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
472 if (Split.first.size() != Identifier.size())
473 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
475 // If this is an absolute variable reference, substitute it now to preserve
476 // semantics in the face of reassignment.
477 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
479 return Error(EndLoc, "unexpected modified on variable reference");
481 Res = Sym->getVariableValue();
485 // Otherwise create a symbol ref.
486 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
489 case AsmToken::Integer: {
490 SMLoc Loc = getTok().getLoc();
491 int64_t IntVal = getTok().getIntVal();
492 Res = MCConstantExpr::Create(IntVal, getContext());
493 EndLoc = Lexer.getLoc();
495 // Look for 'b' or 'f' following an Integer as a directional label
496 if (Lexer.getKind() == AsmToken::Identifier) {
497 StringRef IDVal = getTok().getString();
498 if (IDVal == "f" || IDVal == "b"){
499 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
500 IDVal == "f" ? 1 : 0);
501 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
503 if(IDVal == "b" && Sym->isUndefined())
504 return Error(Loc, "invalid reference to undefined symbol");
505 EndLoc = Lexer.getLoc();
506 Lex(); // Eat identifier.
511 case AsmToken::Dot: {
512 // This is a '.' reference, which references the current PC. Emit a
513 // temporary label to the streamer and refer to it.
514 MCSymbol *Sym = Ctx.CreateTempSymbol();
516 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
517 EndLoc = Lexer.getLoc();
518 Lex(); // Eat identifier.
522 case AsmToken::LParen:
523 Lex(); // Eat the '('.
524 return ParseParenExpr(Res, EndLoc);
525 case AsmToken::Minus:
526 Lex(); // Eat the operator.
527 if (ParsePrimaryExpr(Res, EndLoc))
529 Res = MCUnaryExpr::CreateMinus(Res, getContext());
532 Lex(); // Eat the operator.
533 if (ParsePrimaryExpr(Res, EndLoc))
535 Res = MCUnaryExpr::CreatePlus(Res, getContext());
537 case AsmToken::Tilde:
538 Lex(); // Eat the operator.
539 if (ParsePrimaryExpr(Res, EndLoc))
541 Res = MCUnaryExpr::CreateNot(Res, getContext());
546 bool AsmParser::ParseExpression(const MCExpr *&Res) {
548 return ParseExpression(Res, EndLoc);
551 /// ParseExpression - Parse an expression and return it.
553 /// expr ::= expr +,- expr -> lowest.
554 /// expr ::= expr |,^,&,! expr -> middle.
555 /// expr ::= expr *,/,%,<<,>> expr -> highest.
556 /// expr ::= primaryexpr
558 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
559 // Parse the expression.
561 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
564 // Try to constant fold it up front, if possible.
566 if (Res->EvaluateAsAbsolute(Value))
567 Res = MCConstantExpr::Create(Value, getContext());
572 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
574 return ParseParenExpr(Res, EndLoc) ||
575 ParseBinOpRHS(1, Res, EndLoc);
578 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
581 SMLoc StartLoc = Lexer.getLoc();
582 if (ParseExpression(Expr))
585 if (!Expr->EvaluateAsAbsolute(Res))
586 return Error(StartLoc, "expected absolute expression");
591 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
592 MCBinaryExpr::Opcode &Kind) {
595 return 0; // not a binop.
597 // Lowest Precedence: &&, ||
598 case AsmToken::AmpAmp:
599 Kind = MCBinaryExpr::LAnd;
601 case AsmToken::PipePipe:
602 Kind = MCBinaryExpr::LOr;
605 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
607 Kind = MCBinaryExpr::Add;
609 case AsmToken::Minus:
610 Kind = MCBinaryExpr::Sub;
612 case AsmToken::EqualEqual:
613 Kind = MCBinaryExpr::EQ;
615 case AsmToken::ExclaimEqual:
616 case AsmToken::LessGreater:
617 Kind = MCBinaryExpr::NE;
620 Kind = MCBinaryExpr::LT;
622 case AsmToken::LessEqual:
623 Kind = MCBinaryExpr::LTE;
625 case AsmToken::Greater:
626 Kind = MCBinaryExpr::GT;
628 case AsmToken::GreaterEqual:
629 Kind = MCBinaryExpr::GTE;
632 // Intermediate Precedence: |, &, ^
634 // FIXME: gas seems to support '!' as an infix operator?
636 Kind = MCBinaryExpr::Or;
638 case AsmToken::Caret:
639 Kind = MCBinaryExpr::Xor;
642 Kind = MCBinaryExpr::And;
645 // Highest Precedence: *, /, %, <<, >>
647 Kind = MCBinaryExpr::Mul;
649 case AsmToken::Slash:
650 Kind = MCBinaryExpr::Div;
652 case AsmToken::Percent:
653 Kind = MCBinaryExpr::Mod;
655 case AsmToken::LessLess:
656 Kind = MCBinaryExpr::Shl;
658 case AsmToken::GreaterGreater:
659 Kind = MCBinaryExpr::Shr;
665 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
666 /// Res contains the LHS of the expression on input.
667 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
670 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
671 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
673 // If the next token is lower precedence than we are allowed to eat, return
674 // successfully with what we ate already.
675 if (TokPrec < Precedence)
680 // Eat the next primary expression.
682 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
684 // If BinOp binds less tightly with RHS than the operator after RHS, let
685 // the pending operator take RHS as its LHS.
686 MCBinaryExpr::Opcode Dummy;
687 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
688 if (TokPrec < NextTokPrec) {
689 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
692 // Merge LHS and RHS according to operator.
693 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
701 /// ::= EndOfStatement
702 /// ::= Label* Directive ...Operands... EndOfStatement
703 /// ::= Label* Identifier OperandList* EndOfStatement
704 bool AsmParser::ParseStatement() {
705 if (Lexer.is(AsmToken::EndOfStatement)) {
711 // Statements always start with an identifier.
712 AsmToken ID = getTok();
713 SMLoc IDLoc = ID.getLoc();
715 int64_t LocalLabelVal = -1;
716 // GUESS allow an integer followed by a ':' as a directional local label
717 if (Lexer.is(AsmToken::Integer)) {
718 LocalLabelVal = getTok().getIntVal();
719 if (LocalLabelVal < 0) {
720 if (!TheCondState.Ignore)
721 return TokError("unexpected token at start of statement");
725 IDVal = getTok().getString();
726 Lex(); // Consume the integer token to be used as an identifier token.
727 if (Lexer.getKind() != AsmToken::Colon) {
728 if (!TheCondState.Ignore)
729 return TokError("unexpected token at start of statement");
733 else if (ParseIdentifier(IDVal)) {
734 if (!TheCondState.Ignore)
735 return TokError("unexpected token at start of statement");
739 // Handle conditional assembly here before checking for skipping. We
740 // have to do this so that .endif isn't skipped in a ".if 0" block for
743 return ParseDirectiveIf(IDLoc);
744 if (IDVal == ".elseif")
745 return ParseDirectiveElseIf(IDLoc);
746 if (IDVal == ".else")
747 return ParseDirectiveElse(IDLoc);
748 if (IDVal == ".endif")
749 return ParseDirectiveEndIf(IDLoc);
751 // If we are in a ".if 0" block, ignore this statement.
752 if (TheCondState.Ignore) {
753 EatToEndOfStatement();
757 // FIXME: Recurse on local labels?
759 // See what kind of statement we have.
760 switch (Lexer.getKind()) {
761 case AsmToken::Colon: {
762 // identifier ':' -> Label.
765 // Diagnose attempt to use a variable as a label.
767 // FIXME: Diagnostics. Note the location of the definition as a label.
768 // FIXME: This doesn't diagnose assignment to a symbol which has been
769 // implicitly marked as external.
771 if (LocalLabelVal == -1)
772 Sym = getContext().GetOrCreateSymbol(IDVal);
774 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
775 if (!Sym->isUndefined() || Sym->isVariable())
776 return Error(IDLoc, "invalid symbol redefinition");
781 // Consume any end of statement token, if present, to avoid spurious
782 // AddBlankLine calls().
783 if (Lexer.is(AsmToken::EndOfStatement)) {
785 if (Lexer.is(AsmToken::Eof))
789 return ParseStatement();
792 case AsmToken::Equal:
793 // identifier '=' ... -> assignment statement
796 return ParseAssignment(IDVal);
798 default: // Normal instruction or directive.
802 // If macros are enabled, check to see if this is a macro instantiation.
804 if (const Macro *M = MacroMap.lookup(IDVal))
805 return HandleMacroEntry(IDVal, IDLoc, M);
807 // Otherwise, we have a normal instruction or directive.
808 if (IDVal[0] == '.') {
809 // Assembler features
811 return ParseDirectiveSet();
815 if (IDVal == ".ascii")
816 return ParseDirectiveAscii(false);
817 if (IDVal == ".asciz")
818 return ParseDirectiveAscii(true);
820 if (IDVal == ".byte")
821 return ParseDirectiveValue(1);
822 if (IDVal == ".short")
823 return ParseDirectiveValue(2);
824 if (IDVal == ".long")
825 return ParseDirectiveValue(4);
826 if (IDVal == ".quad")
827 return ParseDirectiveValue(8);
829 if (IDVal == ".align") {
830 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
831 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
833 if (IDVal == ".align32") {
834 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
835 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
837 if (IDVal == ".balign")
838 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
839 if (IDVal == ".balignw")
840 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
841 if (IDVal == ".balignl")
842 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
843 if (IDVal == ".p2align")
844 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
845 if (IDVal == ".p2alignw")
846 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
847 if (IDVal == ".p2alignl")
848 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
851 return ParseDirectiveOrg();
853 if (IDVal == ".fill")
854 return ParseDirectiveFill();
855 if (IDVal == ".space")
856 return ParseDirectiveSpace();
858 // Symbol attribute directives
860 if (IDVal == ".globl" || IDVal == ".global")
861 return ParseDirectiveSymbolAttribute(MCSA_Global);
862 if (IDVal == ".hidden")
863 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
864 if (IDVal == ".indirect_symbol")
865 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
866 if (IDVal == ".internal")
867 return ParseDirectiveSymbolAttribute(MCSA_Internal);
868 if (IDVal == ".lazy_reference")
869 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
870 if (IDVal == ".no_dead_strip")
871 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
872 if (IDVal == ".private_extern")
873 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
874 if (IDVal == ".protected")
875 return ParseDirectiveSymbolAttribute(MCSA_Protected);
876 if (IDVal == ".reference")
877 return ParseDirectiveSymbolAttribute(MCSA_Reference);
878 if (IDVal == ".type")
879 return ParseDirectiveELFType();
880 if (IDVal == ".weak")
881 return ParseDirectiveSymbolAttribute(MCSA_Weak);
882 if (IDVal == ".weak_definition")
883 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
884 if (IDVal == ".weak_reference")
885 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
886 if (IDVal == ".weak_def_can_be_hidden")
887 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
889 if (IDVal == ".comm")
890 return ParseDirectiveComm(/*IsLocal=*/false);
891 if (IDVal == ".lcomm")
892 return ParseDirectiveComm(/*IsLocal=*/true);
894 if (IDVal == ".abort")
895 return ParseDirectiveAbort();
896 if (IDVal == ".include")
897 return ParseDirectiveInclude();
899 // Look up the handler in the handler table.
900 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
901 DirectiveMap.lookup(IDVal);
903 return (*Handler.second)(Handler.first, IDVal, IDLoc);
905 // Target hook for parsing target specific directives.
906 if (!getTargetParser().ParseDirective(ID))
909 Warning(IDLoc, "ignoring directive for now");
910 EatToEndOfStatement();
914 // Canonicalize the opcode to lower case.
915 SmallString<128> Opcode;
916 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
917 Opcode.push_back(tolower(IDVal[i]));
919 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
920 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
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 // Free any parsed operands.
949 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
950 delete ParsedOperands[i];
955 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
956 const std::vector<std::vector<AsmToken> > &A)
957 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
959 // Macro instantiation is lexical, unfortunately. We construct a new buffer
960 // to hold the macro body with substitutions.
961 SmallString<256> Buf;
962 raw_svector_ostream OS(Buf);
964 StringRef Body = M->Body;
965 while (!Body.empty()) {
966 // Scan for the next substitution.
967 std::size_t End = Body.size(), Pos = 0;
968 for (; Pos != End; ++Pos) {
969 // Check for a substitution or escape.
970 if (Body[Pos] != '$' || Pos + 1 == End)
973 char Next = Body[Pos + 1];
974 if (Next == '$' || Next == 'n' || isdigit(Next))
979 OS << Body.slice(0, Pos);
981 // Check if we reached the end.
985 switch (Body[Pos+1]) {
991 // $n => number of arguments
996 // $[0-9] => argument
998 // Missing arguments are ignored.
999 unsigned Index = Body[Pos+1] - '0';
1000 if (Index >= A.size())
1003 // Otherwise substitute with the token values, with spaces eliminated.
1004 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1005 ie = A[Index].end(); it != ie; ++it)
1006 OS << it->getString();
1011 // Update the scan point.
1012 Body = Body.substr(Pos + 2);
1015 // We include the .endmacro in the buffer as our queue to exit the macro
1017 OS << ".endmacro\n";
1019 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1022 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1024 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1025 // this, although we should protect against infinite loops.
1026 if (ActiveMacros.size() == 20)
1027 return TokError("macros cannot be nested more than 20 levels deep");
1029 // Parse the macro instantiation arguments.
1030 std::vector<std::vector<AsmToken> > MacroArguments;
1031 MacroArguments.push_back(std::vector<AsmToken>());
1032 unsigned ParenLevel = 0;
1034 if (Lexer.is(AsmToken::Eof))
1035 return TokError("unexpected token in macro instantiation");
1036 if (Lexer.is(AsmToken::EndOfStatement))
1039 // If we aren't inside parentheses and this is a comma, start a new token
1041 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1042 MacroArguments.push_back(std::vector<AsmToken>());
1044 // Adjust the current parentheses level.
1045 if (Lexer.is(AsmToken::LParen))
1047 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1050 // Append the token to the current argument list.
1051 MacroArguments.back().push_back(getTok());
1056 // Create the macro instantiation object and add to the current macro
1057 // instantiation stack.
1058 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1061 ActiveMacros.push_back(MI);
1063 // Jump to the macro instantiation and prime the lexer.
1064 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1065 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1071 void AsmParser::HandleMacroExit() {
1072 // Jump to the EndOfStatement we should return to, and consume it.
1073 JumpToLoc(ActiveMacros.back()->ExitLoc);
1076 // Pop the instantiation entry.
1077 delete ActiveMacros.back();
1078 ActiveMacros.pop_back();
1081 bool AsmParser::ParseAssignment(StringRef Name) {
1082 // FIXME: Use better location, we should use proper tokens.
1083 SMLoc EqualLoc = Lexer.getLoc();
1085 const MCExpr *Value;
1086 if (ParseExpression(Value))
1089 if (Lexer.isNot(AsmToken::EndOfStatement))
1090 return TokError("unexpected token in assignment");
1092 // Eat the end of statement marker.
1095 // Validate that the LHS is allowed to be a variable (either it has not been
1096 // used as a symbol, or it is an absolute symbol).
1097 MCSymbol *Sym = getContext().LookupSymbol(Name);
1099 // Diagnose assignment to a label.
1101 // FIXME: Diagnostics. Note the location of the definition as a label.
1102 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1103 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1104 ; // Allow redefinitions of undefined symbols only used in directives.
1105 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1106 return Error(EqualLoc, "redefinition of '" + Name + "'");
1107 else if (!Sym->isVariable())
1108 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1109 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1110 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1113 Sym = getContext().GetOrCreateSymbol(Name);
1115 // FIXME: Handle '.'.
1117 Sym->setUsedInExpr(true);
1119 // Do the assignment.
1120 Out.EmitAssignment(Sym, Value);
1125 /// ParseIdentifier:
1128 bool AsmParser::ParseIdentifier(StringRef &Res) {
1129 // The assembler has relaxed rules for accepting identifiers, in particular we
1130 // allow things like '.globl $foo', which would normally be separate
1131 // tokens. At this level, we have already lexed so we cannot (currently)
1132 // handle this as a context dependent token, instead we detect adjacent tokens
1133 // and return the combined identifier.
1134 if (Lexer.is(AsmToken::Dollar)) {
1135 SMLoc DollarLoc = getLexer().getLoc();
1137 // Consume the dollar sign, and check for a following identifier.
1139 if (Lexer.isNot(AsmToken::Identifier))
1142 // We have a '$' followed by an identifier, make sure they are adjacent.
1143 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1146 // Construct the joined identifier and consume the token.
1147 Res = StringRef(DollarLoc.getPointer(),
1148 getTok().getIdentifier().size() + 1);
1153 if (Lexer.isNot(AsmToken::Identifier) &&
1154 Lexer.isNot(AsmToken::String))
1157 Res = getTok().getIdentifier();
1159 Lex(); // Consume the identifier token.
1164 /// ParseDirectiveSet:
1165 /// ::= .set identifier ',' expression
1166 bool AsmParser::ParseDirectiveSet() {
1169 if (ParseIdentifier(Name))
1170 return TokError("expected identifier after '.set' directive");
1172 if (getLexer().isNot(AsmToken::Comma))
1173 return TokError("unexpected token in '.set'");
1176 return ParseAssignment(Name);
1179 bool AsmParser::ParseEscapedString(std::string &Data) {
1180 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1183 StringRef Str = getTok().getStringContents();
1184 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1185 if (Str[i] != '\\') {
1190 // Recognize escaped characters. Note that this escape semantics currently
1191 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1194 return TokError("unexpected backslash at end of string");
1196 // Recognize octal sequences.
1197 if ((unsigned) (Str[i] - '0') <= 7) {
1198 // Consume up to three octal characters.
1199 unsigned Value = Str[i] - '0';
1201 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1203 Value = Value * 8 + (Str[i] - '0');
1205 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1207 Value = Value * 8 + (Str[i] - '0');
1212 return TokError("invalid octal escape sequence (out of range)");
1214 Data += (unsigned char) Value;
1218 // Otherwise recognize individual escapes.
1221 // Just reject invalid escape sequences for now.
1222 return TokError("invalid escape sequence (unrecognized character)");
1224 case 'b': Data += '\b'; break;
1225 case 'f': Data += '\f'; break;
1226 case 'n': Data += '\n'; break;
1227 case 'r': Data += '\r'; break;
1228 case 't': Data += '\t'; break;
1229 case '"': Data += '"'; break;
1230 case '\\': Data += '\\'; break;
1237 /// ParseDirectiveAscii:
1238 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1239 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1240 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1242 if (getLexer().isNot(AsmToken::String))
1243 return TokError("expected string in '.ascii' or '.asciz' directive");
1246 if (ParseEscapedString(Data))
1249 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1251 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1255 if (getLexer().is(AsmToken::EndOfStatement))
1258 if (getLexer().isNot(AsmToken::Comma))
1259 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1268 /// ParseDirectiveValue
1269 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1270 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1271 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1273 const MCExpr *Value;
1274 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1275 if (ParseExpression(Value))
1278 // Special case constant expressions to match code generator.
1279 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1280 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1282 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1284 if (getLexer().is(AsmToken::EndOfStatement))
1287 // FIXME: Improve diagnostic.
1288 if (getLexer().isNot(AsmToken::Comma))
1289 return TokError("unexpected token in directive");
1298 /// ParseDirectiveSpace
1299 /// ::= .space expression [ , expression ]
1300 bool AsmParser::ParseDirectiveSpace() {
1302 if (ParseAbsoluteExpression(NumBytes))
1305 int64_t FillExpr = 0;
1306 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1307 if (getLexer().isNot(AsmToken::Comma))
1308 return TokError("unexpected token in '.space' directive");
1311 if (ParseAbsoluteExpression(FillExpr))
1314 if (getLexer().isNot(AsmToken::EndOfStatement))
1315 return TokError("unexpected token in '.space' directive");
1321 return TokError("invalid number of bytes in '.space' directive");
1323 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1324 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1329 /// ParseDirectiveFill
1330 /// ::= .fill expression , expression , expression
1331 bool AsmParser::ParseDirectiveFill() {
1333 if (ParseAbsoluteExpression(NumValues))
1336 if (getLexer().isNot(AsmToken::Comma))
1337 return TokError("unexpected token in '.fill' directive");
1341 if (ParseAbsoluteExpression(FillSize))
1344 if (getLexer().isNot(AsmToken::Comma))
1345 return TokError("unexpected token in '.fill' directive");
1349 if (ParseAbsoluteExpression(FillExpr))
1352 if (getLexer().isNot(AsmToken::EndOfStatement))
1353 return TokError("unexpected token in '.fill' directive");
1357 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1358 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1360 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1361 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1366 /// ParseDirectiveOrg
1367 /// ::= .org expression [ , expression ]
1368 bool AsmParser::ParseDirectiveOrg() {
1369 const MCExpr *Offset;
1370 if (ParseExpression(Offset))
1373 // Parse optional fill expression.
1374 int64_t FillExpr = 0;
1375 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1376 if (getLexer().isNot(AsmToken::Comma))
1377 return TokError("unexpected token in '.org' directive");
1380 if (ParseAbsoluteExpression(FillExpr))
1383 if (getLexer().isNot(AsmToken::EndOfStatement))
1384 return TokError("unexpected token in '.org' directive");
1389 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1390 // has to be relative to the current section.
1391 getStreamer().EmitValueToOffset(Offset, FillExpr);
1396 /// ParseDirectiveAlign
1397 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1398 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1399 SMLoc AlignmentLoc = getLexer().getLoc();
1401 if (ParseAbsoluteExpression(Alignment))
1405 bool HasFillExpr = false;
1406 int64_t FillExpr = 0;
1407 int64_t MaxBytesToFill = 0;
1408 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1409 if (getLexer().isNot(AsmToken::Comma))
1410 return TokError("unexpected token in directive");
1413 // The fill expression can be omitted while specifying a maximum number of
1414 // alignment bytes, e.g:
1416 if (getLexer().isNot(AsmToken::Comma)) {
1418 if (ParseAbsoluteExpression(FillExpr))
1422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1423 if (getLexer().isNot(AsmToken::Comma))
1424 return TokError("unexpected token in directive");
1427 MaxBytesLoc = getLexer().getLoc();
1428 if (ParseAbsoluteExpression(MaxBytesToFill))
1431 if (getLexer().isNot(AsmToken::EndOfStatement))
1432 return TokError("unexpected token in directive");
1441 // Compute alignment in bytes.
1443 // FIXME: Diagnose overflow.
1444 if (Alignment >= 32) {
1445 Error(AlignmentLoc, "invalid alignment value");
1449 Alignment = 1ULL << Alignment;
1452 // Diagnose non-sensical max bytes to align.
1453 if (MaxBytesLoc.isValid()) {
1454 if (MaxBytesToFill < 1) {
1455 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1456 "many bytes, ignoring maximum bytes expression");
1460 if (MaxBytesToFill >= Alignment) {
1461 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1467 // Check whether we should use optimal code alignment for this .align
1470 // FIXME: This should be using a target hook.
1471 bool UseCodeAlign = false;
1472 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1473 getStreamer().getCurrentSection()))
1474 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1475 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1476 ValueSize == 1 && UseCodeAlign) {
1477 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1479 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1480 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1487 /// ParseDirectiveSymbolAttribute
1488 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1489 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1490 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1494 if (ParseIdentifier(Name))
1495 return TokError("expected identifier in directive");
1497 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1499 getStreamer().EmitSymbolAttribute(Sym, Attr);
1501 if (getLexer().is(AsmToken::EndOfStatement))
1504 if (getLexer().isNot(AsmToken::Comma))
1505 return TokError("unexpected token in directive");
1514 /// ParseDirectiveELFType
1515 /// ::= .type identifier , @attribute
1516 bool AsmParser::ParseDirectiveELFType() {
1518 if (ParseIdentifier(Name))
1519 return TokError("expected identifier in directive");
1521 // Handle the identifier as the key symbol.
1522 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1524 if (getLexer().isNot(AsmToken::Comma))
1525 return TokError("unexpected token in '.type' directive");
1528 if (getLexer().isNot(AsmToken::At))
1529 return TokError("expected '@' before type");
1535 TypeLoc = getLexer().getLoc();
1536 if (ParseIdentifier(Type))
1537 return TokError("expected symbol type in directive");
1539 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1540 .Case("function", MCSA_ELF_TypeFunction)
1541 .Case("object", MCSA_ELF_TypeObject)
1542 .Case("tls_object", MCSA_ELF_TypeTLS)
1543 .Case("common", MCSA_ELF_TypeCommon)
1544 .Case("notype", MCSA_ELF_TypeNoType)
1545 .Default(MCSA_Invalid);
1547 if (Attr == MCSA_Invalid)
1548 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1550 if (getLexer().isNot(AsmToken::EndOfStatement))
1551 return TokError("unexpected token in '.type' directive");
1555 getStreamer().EmitSymbolAttribute(Sym, Attr);
1560 /// ParseDirectiveComm
1561 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1562 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1563 SMLoc IDLoc = getLexer().getLoc();
1565 if (ParseIdentifier(Name))
1566 return TokError("expected identifier in directive");
1568 // Handle the identifier as the key symbol.
1569 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1571 if (getLexer().isNot(AsmToken::Comma))
1572 return TokError("unexpected token in directive");
1576 SMLoc SizeLoc = getLexer().getLoc();
1577 if (ParseAbsoluteExpression(Size))
1580 int64_t Pow2Alignment = 0;
1581 SMLoc Pow2AlignmentLoc;
1582 if (getLexer().is(AsmToken::Comma)) {
1584 Pow2AlignmentLoc = getLexer().getLoc();
1585 if (ParseAbsoluteExpression(Pow2Alignment))
1588 // If this target takes alignments in bytes (not log) validate and convert.
1589 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1590 if (!isPowerOf2_64(Pow2Alignment))
1591 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1592 Pow2Alignment = Log2_64(Pow2Alignment);
1596 if (getLexer().isNot(AsmToken::EndOfStatement))
1597 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1601 // NOTE: a size of zero for a .comm should create a undefined symbol
1602 // but a size of .lcomm creates a bss symbol of size zero.
1604 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1605 "be less than zero");
1607 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1608 // may internally end up wanting an alignment in bytes.
1609 // FIXME: Diagnose overflow.
1610 if (Pow2Alignment < 0)
1611 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1612 "alignment, can't be less than zero");
1614 if (!Sym->isUndefined())
1615 return Error(IDLoc, "invalid symbol redefinition");
1617 // '.lcomm' is equivalent to '.zerofill'.
1618 // Create the Symbol as a common or local common with Size and Pow2Alignment
1620 getStreamer().EmitZerofill(Ctx.getMachOSection(
1621 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1622 0, SectionKind::getBSS()),
1623 Sym, Size, 1 << Pow2Alignment);
1627 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1631 /// ParseDirectiveAbort
1632 /// ::= .abort [... message ...]
1633 bool AsmParser::ParseDirectiveAbort() {
1634 // FIXME: Use loc from directive.
1635 SMLoc Loc = getLexer().getLoc();
1637 StringRef Str = ParseStringToEndOfStatement();
1638 if (getLexer().isNot(AsmToken::EndOfStatement))
1639 return TokError("unexpected token in '.abort' directive");
1644 Error(Loc, ".abort detected. Assembly stopping.");
1646 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1647 // FIXME: Actually abort assembly here.
1652 /// ParseDirectiveInclude
1653 /// ::= .include "filename"
1654 bool AsmParser::ParseDirectiveInclude() {
1655 if (getLexer().isNot(AsmToken::String))
1656 return TokError("expected string in '.include' directive");
1658 std::string Filename = getTok().getString();
1659 SMLoc IncludeLoc = getLexer().getLoc();
1662 if (getLexer().isNot(AsmToken::EndOfStatement))
1663 return TokError("unexpected token in '.include' directive");
1665 // Strip the quotes.
1666 Filename = Filename.substr(1, Filename.size()-2);
1668 // Attempt to switch the lexer to the included file before consuming the end
1669 // of statement to avoid losing it when we switch.
1670 if (EnterIncludeFile(Filename)) {
1671 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1678 /// ParseDirectiveIf
1679 /// ::= .if expression
1680 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1681 TheCondStack.push_back(TheCondState);
1682 TheCondState.TheCond = AsmCond::IfCond;
1683 if(TheCondState.Ignore) {
1684 EatToEndOfStatement();
1688 if (ParseAbsoluteExpression(ExprValue))
1691 if (getLexer().isNot(AsmToken::EndOfStatement))
1692 return TokError("unexpected token in '.if' directive");
1696 TheCondState.CondMet = ExprValue;
1697 TheCondState.Ignore = !TheCondState.CondMet;
1703 /// ParseDirectiveElseIf
1704 /// ::= .elseif expression
1705 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1706 if (TheCondState.TheCond != AsmCond::IfCond &&
1707 TheCondState.TheCond != AsmCond::ElseIfCond)
1708 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1710 TheCondState.TheCond = AsmCond::ElseIfCond;
1712 bool LastIgnoreState = false;
1713 if (!TheCondStack.empty())
1714 LastIgnoreState = TheCondStack.back().Ignore;
1715 if (LastIgnoreState || TheCondState.CondMet) {
1716 TheCondState.Ignore = true;
1717 EatToEndOfStatement();
1721 if (ParseAbsoluteExpression(ExprValue))
1724 if (getLexer().isNot(AsmToken::EndOfStatement))
1725 return TokError("unexpected token in '.elseif' directive");
1728 TheCondState.CondMet = ExprValue;
1729 TheCondState.Ignore = !TheCondState.CondMet;
1735 /// ParseDirectiveElse
1737 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1738 if (getLexer().isNot(AsmToken::EndOfStatement))
1739 return TokError("unexpected token in '.else' directive");
1743 if (TheCondState.TheCond != AsmCond::IfCond &&
1744 TheCondState.TheCond != AsmCond::ElseIfCond)
1745 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1747 TheCondState.TheCond = AsmCond::ElseCond;
1748 bool LastIgnoreState = false;
1749 if (!TheCondStack.empty())
1750 LastIgnoreState = TheCondStack.back().Ignore;
1751 if (LastIgnoreState || TheCondState.CondMet)
1752 TheCondState.Ignore = true;
1754 TheCondState.Ignore = false;
1759 /// ParseDirectiveEndIf
1761 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1762 if (getLexer().isNot(AsmToken::EndOfStatement))
1763 return TokError("unexpected token in '.endif' directive");
1767 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1768 TheCondStack.empty())
1769 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1771 if (!TheCondStack.empty()) {
1772 TheCondState = TheCondStack.back();
1773 TheCondStack.pop_back();
1779 /// ParseDirectiveFile
1780 /// ::= .file [number] string
1781 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1782 // FIXME: I'm not sure what this is.
1783 int64_t FileNumber = -1;
1784 SMLoc FileNumberLoc = getLexer().getLoc();
1785 if (getLexer().is(AsmToken::Integer)) {
1786 FileNumber = getTok().getIntVal();
1790 return TokError("file number less than one");
1793 if (getLexer().isNot(AsmToken::String))
1794 return TokError("unexpected token in '.file' directive");
1796 StringRef Filename = getTok().getString();
1797 Filename = Filename.substr(1, Filename.size()-2);
1800 if (getLexer().isNot(AsmToken::EndOfStatement))
1801 return TokError("unexpected token in '.file' directive");
1803 if (FileNumber == -1)
1804 getStreamer().EmitFileDirective(Filename);
1806 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1807 Error(FileNumberLoc, "file number already allocated");
1808 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1814 /// ParseDirectiveLine
1815 /// ::= .line [number]
1816 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1817 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1818 if (getLexer().isNot(AsmToken::Integer))
1819 return TokError("unexpected token in '.line' directive");
1821 int64_t LineNumber = getTok().getIntVal();
1825 // FIXME: Do something with the .line.
1828 if (getLexer().isNot(AsmToken::EndOfStatement))
1829 return TokError("unexpected token in '.line' directive");
1835 /// ParseDirectiveLoc
1836 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1837 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1838 /// The first number is a file number, must have been previously assigned with
1839 /// a .file directive, the second number is the line number and optionally the
1840 /// third number is a column position (zero if not specified). The remaining
1841 /// optional items are .loc sub-directives.
1842 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1844 if (getLexer().isNot(AsmToken::Integer))
1845 return TokError("unexpected token in '.loc' directive");
1846 int64_t FileNumber = getTok().getIntVal();
1848 return TokError("file number less than one in '.loc' directive");
1849 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1850 return TokError("unassigned file number in '.loc' directive");
1853 int64_t LineNumber = 0;
1854 if (getLexer().is(AsmToken::Integer)) {
1855 LineNumber = getTok().getIntVal();
1857 return TokError("line number less than one in '.loc' directive");
1861 int64_t ColumnPos = 0;
1862 if (getLexer().is(AsmToken::Integer)) {
1863 ColumnPos = getTok().getIntVal();
1865 return TokError("column position less than zero in '.loc' directive");
1871 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1873 if (getLexer().is(AsmToken::EndOfStatement))
1877 SMLoc Loc = getTok().getLoc();
1878 if (getParser().ParseIdentifier(Name))
1879 return TokError("unexpected token in '.loc' directive");
1881 if (Name == "basic_block")
1882 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1883 else if (Name == "prologue_end")
1884 Flags |= DWARF2_FLAG_PROLOGUE_END;
1885 else if (Name == "epilogue_begin")
1886 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1887 else if (Name == "is_stmt") {
1888 SMLoc Loc = getTok().getLoc();
1889 const MCExpr *Value;
1890 if (getParser().ParseExpression(Value))
1892 // The expression must be the constant 0 or 1.
1893 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1894 int Value = MCE->getValue();
1896 Flags &= ~DWARF2_FLAG_IS_STMT;
1897 else if (Value == 1)
1898 Flags |= DWARF2_FLAG_IS_STMT;
1900 return Error(Loc, "is_stmt value not 0 or 1");
1903 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1906 else if (Name == "isa") {
1907 SMLoc Loc = getTok().getLoc();
1908 const MCExpr *Value;
1909 if (getParser().ParseExpression(Value))
1911 // The expression must be a constant greater or equal to 0.
1912 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1913 int Value = MCE->getValue();
1915 return Error(Loc, "isa number less than zero");
1919 return Error(Loc, "isa number not a constant value");
1923 return Error(Loc, "unknown sub-directive in '.loc' directive");
1926 if (getLexer().is(AsmToken::EndOfStatement))
1931 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1936 /// ParseDirectiveMacrosOnOff
1939 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1940 SMLoc DirectiveLoc) {
1941 if (getLexer().isNot(AsmToken::EndOfStatement))
1942 return Error(getLexer().getLoc(),
1943 "unexpected token in '" + Directive + "' directive");
1945 getParser().MacrosEnabled = Directive == ".macros_on";
1950 /// ParseDirectiveMacro
1952 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1953 SMLoc DirectiveLoc) {
1955 if (getParser().ParseIdentifier(Name))
1956 return TokError("expected identifier in directive");
1958 if (getLexer().isNot(AsmToken::EndOfStatement))
1959 return TokError("unexpected token in '.macro' directive");
1961 // Eat the end of statement.
1964 AsmToken EndToken, StartToken = getTok();
1966 // Lex the macro definition.
1968 // Check whether we have reached the end of the file.
1969 if (getLexer().is(AsmToken::Eof))
1970 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1972 // Otherwise, check whether we have reach the .endmacro.
1973 if (getLexer().is(AsmToken::Identifier) &&
1974 (getTok().getIdentifier() == ".endm" ||
1975 getTok().getIdentifier() == ".endmacro")) {
1976 EndToken = getTok();
1978 if (getLexer().isNot(AsmToken::EndOfStatement))
1979 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1984 // Otherwise, scan til the end of the statement.
1985 getParser().EatToEndOfStatement();
1988 if (getParser().MacroMap.lookup(Name)) {
1989 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1992 const char *BodyStart = StartToken.getLoc().getPointer();
1993 const char *BodyEnd = EndToken.getLoc().getPointer();
1994 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1995 getParser().MacroMap[Name] = new Macro(Name, Body);
1999 /// ParseDirectiveEndMacro
2002 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2003 SMLoc DirectiveLoc) {
2004 if (getLexer().isNot(AsmToken::EndOfStatement))
2005 return TokError("unexpected token in '" + Directive + "' directive");
2007 // If we are inside a macro instantiation, terminate the current
2009 if (!getParser().ActiveMacros.empty()) {
2010 getParser().HandleMacroExit();
2014 // Otherwise, this .endmacro is a stray entry in the file; well formed
2015 // .endmacro directives are handled during the macro definition parsing.
2016 return TokError("unexpected '" + Directive + "' in file, "
2017 "no current macro definition");
2020 /// \brief Create an MCAsmParser instance.
2021 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2022 MCContext &C, MCStreamer &Out,
2023 const MCAsmInfo &MAI) {
2024 return new AsmParser(T, SM, C, Out, MAI);