1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmParser.h"
40 /// \brief Helper class for tracking macro definitions.
46 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
49 /// \brief Helper class for storing information about an active macro
51 struct MacroInstantiation {
52 /// The macro being instantiated.
53 const Macro *TheMacro;
55 /// The macro instantiation with substitutions.
56 MemoryBuffer *Instantiation;
58 /// The location of the instantiation.
59 SMLoc InstantiationLoc;
61 /// The location where parsing should resume upon instantiation completion.
65 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66 const std::vector<std::vector<AsmToken> > &A);
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71 friend class GenericAsmParser;
73 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
74 void operator=(const AsmParser &); // DO NOT IMPLEMENT
80 MCAsmParserExtension *GenericParser;
81 MCAsmParserExtension *PlatformParser;
83 /// This is the current buffer index we're lexing from as managed by the
88 std::vector<AsmCond> TheCondStack;
90 /// DirectiveMap - This is a table handlers for directives. Each handler is
91 /// invoked after the directive identifier is read and is responsible for
92 /// parsing and validating the rest of the directive. The handler is passed
93 /// in the directive name and the location of the directive keyword.
94 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96 /// MacroMap - Map of currently defined macros.
97 StringMap<Macro*> MacroMap;
99 /// ActiveMacros - Stack of active macro instantiations.
100 std::vector<MacroInstantiation*> ActiveMacros;
102 /// Boolean tracking whether macro substitution is enabled.
103 unsigned MacrosEnabled : 1;
105 /// Flag tracking whether any errors have been encountered.
106 unsigned HadError : 1;
109 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110 const MCAsmInfo &MAI);
113 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 DirectiveHandler Handler) {
118 DirectiveMap[Directive] = std::make_pair(Object, Handler);
122 /// @name MCAsmParser Interface
125 virtual SourceMgr &getSourceManager() { return SrcMgr; }
126 virtual MCAsmLexer &getLexer() { return Lexer; }
127 virtual MCContext &getContext() { return Ctx; }
128 virtual MCStreamer &getStreamer() { return Out; }
130 virtual void Warning(SMLoc L, const Twine &Meg);
131 virtual bool Error(SMLoc L, const Twine &Msg);
133 const AsmToken &Lex();
135 bool ParseExpression(const MCExpr *&Res);
136 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseAbsoluteExpression(int64_t &Res);
143 void CheckForValidSection();
145 bool ParseStatement();
147 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148 void HandleMacroExit();
150 void PrintMacroInstantiations();
151 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
153 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
154 bool EnterIncludeFile(const std::string &Filename);
156 /// \brief Reset the current lexer position to that given by \arg Loc. The
157 /// current token is not set; clients should ensure Lex() is called
159 void JumpToLoc(SMLoc Loc);
161 void EatToEndOfStatement();
163 /// \brief Parse up to the end of statement and a return the contents from the
164 /// current token until the end of the statement; the current token on exit
165 /// will be either the EndOfStatement or EOF.
166 StringRef ParseStringToEndOfStatement();
168 bool ParseAssignment(StringRef Name);
170 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
171 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
175 /// and set \arg Res to the identifier contents.
176 bool ParseIdentifier(StringRef &Res);
178 // Directive Parsing.
179 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
180 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
181 bool ParseDirectiveFill(); // ".fill"
182 bool ParseDirectiveSpace(); // ".space"
183 bool ParseDirectiveZero(); // ".zero"
184 bool ParseDirectiveSet(); // ".set"
185 bool ParseDirectiveOrg(); // ".org"
186 // ".align{,32}", ".p2align{,w,l}"
187 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
189 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
190 /// accepts a single symbol (which should be a label or an external).
191 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
192 bool ParseDirectiveELFType(); // ELF specific ".type"
194 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
196 bool ParseDirectiveAbort(); // ".abort"
197 bool ParseDirectiveInclude(); // ".include"
199 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
200 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
201 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
202 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
204 /// ParseEscapedString - Parse the current token as a string which may include
205 /// escaped characters and return the string contents.
206 bool ParseEscapedString(std::string &Data);
209 /// \brief Generic implementations of directive handling, etc. which is shared
210 /// (or the default, at least) for all assembler parser.
211 class GenericAsmParser : public MCAsmParserExtension {
212 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
213 void AddDirectiveHandler(StringRef Directive) {
214 getParser().AddDirectiveHandler(this, Directive,
215 HandleDirective<GenericAsmParser, Handler>);
219 GenericAsmParser() {}
221 AsmParser &getParser() {
222 return (AsmParser&) this->MCAsmParserExtension::getParser();
225 virtual void Initialize(MCAsmParser &Parser) {
226 // Call the base implementation.
227 this->MCAsmParserExtension::Initialize(Parser);
229 // Debugging directives.
230 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
231 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
232 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
247 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
248 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
249 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
251 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
252 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
253 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
255 void ParseUleb128(uint64_t Value);
256 void ParseSleb128(int64_t Value);
257 bool ParseDirectiveLEB128(StringRef, SMLoc);
264 extern MCAsmParserExtension *createDarwinAsmParser();
265 extern MCAsmParserExtension *createELFAsmParser();
269 enum { DEFAULT_ADDRSPACE = 0 };
271 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
272 MCStreamer &_Out, const MCAsmInfo &_MAI)
273 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
274 GenericParser(new GenericAsmParser), PlatformParser(0),
275 CurBuffer(0), MacrosEnabled(true) {
276 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
278 // Initialize the generic parser.
279 GenericParser->Initialize(*this);
281 // Initialize the platform / file format parser.
283 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
285 if (_MAI.hasSubsectionsViaSymbols()) {
286 PlatformParser = createDarwinAsmParser();
287 PlatformParser->Initialize(*this);
289 PlatformParser = createELFAsmParser();
290 PlatformParser->Initialize(*this);
294 AsmParser::~AsmParser() {
295 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
297 // Destroy any macros.
298 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
299 ie = MacroMap.end(); it != ie; ++it)
300 delete it->getValue();
302 delete PlatformParser;
303 delete GenericParser;
306 void AsmParser::PrintMacroInstantiations() {
307 // Print the active macro instantiation stack.
308 for (std::vector<MacroInstantiation*>::const_reverse_iterator
309 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
310 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
314 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
315 PrintMessage(L, Msg.str(), "warning");
316 PrintMacroInstantiations();
319 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
321 PrintMessage(L, Msg.str(), "error");
322 PrintMacroInstantiations();
326 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
327 const char *Type) const {
328 SrcMgr.PrintMessage(Loc, Msg, Type);
331 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
332 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
338 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
343 void AsmParser::JumpToLoc(SMLoc Loc) {
344 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
345 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
348 const AsmToken &AsmParser::Lex() {
349 const AsmToken *tok = &Lexer.Lex();
351 if (tok->is(AsmToken::Eof)) {
352 // If this is the end of an included file, pop the parent file off the
354 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
355 if (ParentIncludeLoc != SMLoc()) {
356 JumpToLoc(ParentIncludeLoc);
361 if (tok->is(AsmToken::Error))
362 Error(Lexer.getErrLoc(), Lexer.getErr());
367 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
368 // Create the initial section, if requested.
369 if (!NoInitialTextSection)
376 AsmCond StartingCondState = TheCondState;
378 // While we have input, parse each statement.
379 while (Lexer.isNot(AsmToken::Eof)) {
380 if (!ParseStatement()) continue;
382 // We had an error, validate that one was emitted and recover by skipping to
384 assert(HadError && "Parse statement returned an error, but none emitted!");
385 EatToEndOfStatement();
388 if (TheCondState.TheCond != StartingCondState.TheCond ||
389 TheCondState.Ignore != StartingCondState.Ignore)
390 return TokError("unmatched .ifs or .elses");
392 // Check to see there are no empty DwarfFile slots.
393 const std::vector<MCDwarfFile *> &MCDwarfFiles =
394 getContext().getMCDwarfFiles();
395 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
396 if (!MCDwarfFiles[i])
397 TokError("unassigned file number: " + Twine(i) + " for .file directives");
400 // Finalize the output stream if there are no errors and if the client wants
402 if (!HadError && !NoFinalize)
408 void AsmParser::CheckForValidSection() {
409 if (!getStreamer().getCurrentSection()) {
410 TokError("expected section directive before assembly directive");
411 Out.SwitchSection(Ctx.getMachOSection(
413 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
414 0, SectionKind::getText()));
418 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
419 void AsmParser::EatToEndOfStatement() {
420 while (Lexer.isNot(AsmToken::EndOfStatement) &&
421 Lexer.isNot(AsmToken::Eof))
425 if (Lexer.is(AsmToken::EndOfStatement))
429 StringRef AsmParser::ParseStringToEndOfStatement() {
430 const char *Start = getTok().getLoc().getPointer();
432 while (Lexer.isNot(AsmToken::EndOfStatement) &&
433 Lexer.isNot(AsmToken::Eof))
436 const char *End = getTok().getLoc().getPointer();
437 return StringRef(Start, End - Start);
440 /// ParseParenExpr - Parse a paren expression and return it.
441 /// NOTE: This assumes the leading '(' has already been consumed.
443 /// parenexpr ::= expr)
445 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
446 if (ParseExpression(Res)) return true;
447 if (Lexer.isNot(AsmToken::RParen))
448 return TokError("expected ')' in parentheses expression");
449 EndLoc = Lexer.getLoc();
454 /// ParsePrimaryExpr - Parse a primary expression and return it.
455 /// primaryexpr ::= (parenexpr
456 /// primaryexpr ::= symbol
457 /// primaryexpr ::= number
458 /// primaryexpr ::= '.'
459 /// primaryexpr ::= ~,+,- primaryexpr
460 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
461 switch (Lexer.getKind()) {
463 return TokError("unknown token in expression");
464 case AsmToken::Exclaim:
465 Lex(); // Eat the operator.
466 if (ParsePrimaryExpr(Res, EndLoc))
468 Res = MCUnaryExpr::CreateLNot(Res, getContext());
470 case AsmToken::Dollar:
471 case AsmToken::String:
472 case AsmToken::Identifier: {
473 EndLoc = Lexer.getLoc();
475 StringRef Identifier;
476 if (ParseIdentifier(Identifier))
479 // This is a symbol reference.
480 std::pair<StringRef, StringRef> Split = Identifier.split('@');
481 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
483 // Mark the symbol as used in an expression.
484 Sym->setUsedInExpr(true);
486 // Lookup the symbol variant if used.
487 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
488 if (Split.first.size() != Identifier.size())
489 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
491 // If this is an absolute variable reference, substitute it now to preserve
492 // semantics in the face of reassignment.
493 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
495 return Error(EndLoc, "unexpected modified on variable reference");
497 Res = Sym->getVariableValue();
501 // Otherwise create a symbol ref.
502 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
505 case AsmToken::Integer: {
506 SMLoc Loc = getTok().getLoc();
507 int64_t IntVal = getTok().getIntVal();
508 Res = MCConstantExpr::Create(IntVal, getContext());
509 EndLoc = Lexer.getLoc();
511 // Look for 'b' or 'f' following an Integer as a directional label
512 if (Lexer.getKind() == AsmToken::Identifier) {
513 StringRef IDVal = getTok().getString();
514 if (IDVal == "f" || IDVal == "b"){
515 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
516 IDVal == "f" ? 1 : 0);
517 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
519 if(IDVal == "b" && Sym->isUndefined())
520 return Error(Loc, "invalid reference to undefined symbol");
521 EndLoc = Lexer.getLoc();
522 Lex(); // Eat identifier.
527 case AsmToken::Dot: {
528 // This is a '.' reference, which references the current PC. Emit a
529 // temporary label to the streamer and refer to it.
530 MCSymbol *Sym = Ctx.CreateTempSymbol();
532 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
533 EndLoc = Lexer.getLoc();
534 Lex(); // Eat identifier.
538 case AsmToken::LParen:
539 Lex(); // Eat the '('.
540 return ParseParenExpr(Res, EndLoc);
541 case AsmToken::Minus:
542 Lex(); // Eat the operator.
543 if (ParsePrimaryExpr(Res, EndLoc))
545 Res = MCUnaryExpr::CreateMinus(Res, getContext());
548 Lex(); // Eat the operator.
549 if (ParsePrimaryExpr(Res, EndLoc))
551 Res = MCUnaryExpr::CreatePlus(Res, getContext());
553 case AsmToken::Tilde:
554 Lex(); // Eat the operator.
555 if (ParsePrimaryExpr(Res, EndLoc))
557 Res = MCUnaryExpr::CreateNot(Res, getContext());
562 bool AsmParser::ParseExpression(const MCExpr *&Res) {
564 return ParseExpression(Res, EndLoc);
567 /// ParseExpression - Parse an expression and return it.
569 /// expr ::= expr +,- expr -> lowest.
570 /// expr ::= expr |,^,&,! expr -> middle.
571 /// expr ::= expr *,/,%,<<,>> expr -> highest.
572 /// expr ::= primaryexpr
574 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
575 // Parse the expression.
577 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
580 // Try to constant fold it up front, if possible.
582 if (Res->EvaluateAsAbsolute(Value))
583 Res = MCConstantExpr::Create(Value, getContext());
588 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
590 return ParseParenExpr(Res, EndLoc) ||
591 ParseBinOpRHS(1, Res, EndLoc);
594 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
597 SMLoc StartLoc = Lexer.getLoc();
598 if (ParseExpression(Expr))
601 if (!Expr->EvaluateAsAbsolute(Res))
602 return Error(StartLoc, "expected absolute expression");
607 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
608 MCBinaryExpr::Opcode &Kind) {
611 return 0; // not a binop.
613 // Lowest Precedence: &&, ||
614 case AsmToken::AmpAmp:
615 Kind = MCBinaryExpr::LAnd;
617 case AsmToken::PipePipe:
618 Kind = MCBinaryExpr::LOr;
621 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
623 Kind = MCBinaryExpr::Add;
625 case AsmToken::Minus:
626 Kind = MCBinaryExpr::Sub;
628 case AsmToken::EqualEqual:
629 Kind = MCBinaryExpr::EQ;
631 case AsmToken::ExclaimEqual:
632 case AsmToken::LessGreater:
633 Kind = MCBinaryExpr::NE;
636 Kind = MCBinaryExpr::LT;
638 case AsmToken::LessEqual:
639 Kind = MCBinaryExpr::LTE;
641 case AsmToken::Greater:
642 Kind = MCBinaryExpr::GT;
644 case AsmToken::GreaterEqual:
645 Kind = MCBinaryExpr::GTE;
648 // Intermediate Precedence: |, &, ^
650 // FIXME: gas seems to support '!' as an infix operator?
652 Kind = MCBinaryExpr::Or;
654 case AsmToken::Caret:
655 Kind = MCBinaryExpr::Xor;
658 Kind = MCBinaryExpr::And;
661 // Highest Precedence: *, /, %, <<, >>
663 Kind = MCBinaryExpr::Mul;
665 case AsmToken::Slash:
666 Kind = MCBinaryExpr::Div;
668 case AsmToken::Percent:
669 Kind = MCBinaryExpr::Mod;
671 case AsmToken::LessLess:
672 Kind = MCBinaryExpr::Shl;
674 case AsmToken::GreaterGreater:
675 Kind = MCBinaryExpr::Shr;
681 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
682 /// Res contains the LHS of the expression on input.
683 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
686 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
687 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
689 // If the next token is lower precedence than we are allowed to eat, return
690 // successfully with what we ate already.
691 if (TokPrec < Precedence)
696 // Eat the next primary expression.
698 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
700 // If BinOp binds less tightly with RHS than the operator after RHS, let
701 // the pending operator take RHS as its LHS.
702 MCBinaryExpr::Opcode Dummy;
703 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
704 if (TokPrec < NextTokPrec) {
705 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
708 // Merge LHS and RHS according to operator.
709 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
717 /// ::= EndOfStatement
718 /// ::= Label* Directive ...Operands... EndOfStatement
719 /// ::= Label* Identifier OperandList* EndOfStatement
720 bool AsmParser::ParseStatement() {
721 if (Lexer.is(AsmToken::EndOfStatement)) {
727 // Statements always start with an identifier.
728 AsmToken ID = getTok();
729 SMLoc IDLoc = ID.getLoc();
731 int64_t LocalLabelVal = -1;
732 // GUESS allow an integer followed by a ':' as a directional local label
733 if (Lexer.is(AsmToken::Integer)) {
734 LocalLabelVal = getTok().getIntVal();
735 if (LocalLabelVal < 0) {
736 if (!TheCondState.Ignore)
737 return TokError("unexpected token at start of statement");
741 IDVal = getTok().getString();
742 Lex(); // Consume the integer token to be used as an identifier token.
743 if (Lexer.getKind() != AsmToken::Colon) {
744 if (!TheCondState.Ignore)
745 return TokError("unexpected token at start of statement");
749 else if (ParseIdentifier(IDVal)) {
750 if (!TheCondState.Ignore)
751 return TokError("unexpected token at start of statement");
755 // Handle conditional assembly here before checking for skipping. We
756 // have to do this so that .endif isn't skipped in a ".if 0" block for
759 return ParseDirectiveIf(IDLoc);
760 if (IDVal == ".elseif")
761 return ParseDirectiveElseIf(IDLoc);
762 if (IDVal == ".else")
763 return ParseDirectiveElse(IDLoc);
764 if (IDVal == ".endif")
765 return ParseDirectiveEndIf(IDLoc);
767 // If we are in a ".if 0" block, ignore this statement.
768 if (TheCondState.Ignore) {
769 EatToEndOfStatement();
773 // FIXME: Recurse on local labels?
775 // See what kind of statement we have.
776 switch (Lexer.getKind()) {
777 case AsmToken::Colon: {
778 CheckForValidSection();
780 // identifier ':' -> Label.
783 // Diagnose attempt to use a variable as a label.
785 // FIXME: Diagnostics. Note the location of the definition as a label.
786 // FIXME: This doesn't diagnose assignment to a symbol which has been
787 // implicitly marked as external.
789 if (LocalLabelVal == -1)
790 Sym = getContext().GetOrCreateSymbol(IDVal);
792 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
793 if (!Sym->isUndefined() || Sym->isVariable())
794 return Error(IDLoc, "invalid symbol redefinition");
799 // Consume any end of statement token, if present, to avoid spurious
800 // AddBlankLine calls().
801 if (Lexer.is(AsmToken::EndOfStatement)) {
803 if (Lexer.is(AsmToken::Eof))
807 return ParseStatement();
810 case AsmToken::Equal:
811 // identifier '=' ... -> assignment statement
814 return ParseAssignment(IDVal);
816 default: // Normal instruction or directive.
820 // If macros are enabled, check to see if this is a macro instantiation.
822 if (const Macro *M = MacroMap.lookup(IDVal))
823 return HandleMacroEntry(IDVal, IDLoc, M);
825 // Otherwise, we have a normal instruction or directive.
826 if (IDVal[0] == '.') {
827 // Assembler features
829 return ParseDirectiveSet();
833 if (IDVal == ".ascii")
834 return ParseDirectiveAscii(false);
835 if (IDVal == ".asciz")
836 return ParseDirectiveAscii(true);
838 if (IDVal == ".byte")
839 return ParseDirectiveValue(1);
840 if (IDVal == ".short")
841 return ParseDirectiveValue(2);
842 if (IDVal == ".long")
843 return ParseDirectiveValue(4);
844 if (IDVal == ".quad")
845 return ParseDirectiveValue(8);
847 if (IDVal == ".align") {
848 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
849 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
851 if (IDVal == ".align32") {
852 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
853 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
855 if (IDVal == ".balign")
856 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
857 if (IDVal == ".balignw")
858 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
859 if (IDVal == ".balignl")
860 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
861 if (IDVal == ".p2align")
862 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
863 if (IDVal == ".p2alignw")
864 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
865 if (IDVal == ".p2alignl")
866 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
869 return ParseDirectiveOrg();
871 if (IDVal == ".fill")
872 return ParseDirectiveFill();
873 if (IDVal == ".space")
874 return ParseDirectiveSpace();
875 if (IDVal == ".zero")
876 return ParseDirectiveZero();
878 // Symbol attribute directives
880 if (IDVal == ".globl" || IDVal == ".global")
881 return ParseDirectiveSymbolAttribute(MCSA_Global);
882 if (IDVal == ".hidden")
883 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
884 if (IDVal == ".indirect_symbol")
885 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
886 if (IDVal == ".internal")
887 return ParseDirectiveSymbolAttribute(MCSA_Internal);
888 if (IDVal == ".lazy_reference")
889 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
890 if (IDVal == ".no_dead_strip")
891 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
892 if (IDVal == ".private_extern")
893 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
894 if (IDVal == ".protected")
895 return ParseDirectiveSymbolAttribute(MCSA_Protected);
896 if (IDVal == ".reference")
897 return ParseDirectiveSymbolAttribute(MCSA_Reference);
898 if (IDVal == ".type")
899 return ParseDirectiveELFType();
900 if (IDVal == ".weak")
901 return ParseDirectiveSymbolAttribute(MCSA_Weak);
902 if (IDVal == ".weak_definition")
903 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
904 if (IDVal == ".weak_reference")
905 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
906 if (IDVal == ".weak_def_can_be_hidden")
907 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
909 if (IDVal == ".comm")
910 return ParseDirectiveComm(/*IsLocal=*/false);
911 if (IDVal == ".lcomm")
912 return ParseDirectiveComm(/*IsLocal=*/true);
914 if (IDVal == ".abort")
915 return ParseDirectiveAbort();
916 if (IDVal == ".include")
917 return ParseDirectiveInclude();
919 // Look up the handler in the handler table.
920 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
921 DirectiveMap.lookup(IDVal);
923 return (*Handler.second)(Handler.first, IDVal, IDLoc);
925 // Target hook for parsing target specific directives.
926 if (!getTargetParser().ParseDirective(ID))
929 Warning(IDLoc, "ignoring directive for now");
930 EatToEndOfStatement();
934 CheckForValidSection();
936 // Canonicalize the opcode to lower case.
937 SmallString<128> Opcode;
938 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
939 Opcode.push_back(tolower(IDVal[i]));
941 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
942 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
945 // Dump the parsed representation, if requested.
946 if (getShowParsedOperands()) {
947 SmallString<256> Str;
948 raw_svector_ostream OS(Str);
949 OS << "parsed instruction: [";
950 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
953 ParsedOperands[i]->dump(OS);
957 PrintMessage(IDLoc, OS.str(), "note");
960 // If parsing succeeded, match the instruction.
963 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
964 // Emit the instruction on success.
965 Out.EmitInstruction(Inst);
970 // Free any parsed operands.
971 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
972 delete ParsedOperands[i];
974 // Don't skip the rest of the line, the instruction parser is responsible for
979 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
980 const std::vector<std::vector<AsmToken> > &A)
981 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
983 // Macro instantiation is lexical, unfortunately. We construct a new buffer
984 // to hold the macro body with substitutions.
985 SmallString<256> Buf;
986 raw_svector_ostream OS(Buf);
988 StringRef Body = M->Body;
989 while (!Body.empty()) {
990 // Scan for the next substitution.
991 std::size_t End = Body.size(), Pos = 0;
992 for (; Pos != End; ++Pos) {
993 // Check for a substitution or escape.
994 if (Body[Pos] != '$' || Pos + 1 == End)
997 char Next = Body[Pos + 1];
998 if (Next == '$' || Next == 'n' || isdigit(Next))
1003 OS << Body.slice(0, Pos);
1005 // Check if we reached the end.
1009 switch (Body[Pos+1]) {
1015 // $n => number of arguments
1020 // $[0-9] => argument
1022 // Missing arguments are ignored.
1023 unsigned Index = Body[Pos+1] - '0';
1024 if (Index >= A.size())
1027 // Otherwise substitute with the token values, with spaces eliminated.
1028 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1029 ie = A[Index].end(); it != ie; ++it)
1030 OS << it->getString();
1035 // Update the scan point.
1036 Body = Body.substr(Pos + 2);
1039 // We include the .endmacro in the buffer as our queue to exit the macro
1041 OS << ".endmacro\n";
1043 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1046 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1048 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1049 // this, although we should protect against infinite loops.
1050 if (ActiveMacros.size() == 20)
1051 return TokError("macros cannot be nested more than 20 levels deep");
1053 // Parse the macro instantiation arguments.
1054 std::vector<std::vector<AsmToken> > MacroArguments;
1055 MacroArguments.push_back(std::vector<AsmToken>());
1056 unsigned ParenLevel = 0;
1058 if (Lexer.is(AsmToken::Eof))
1059 return TokError("unexpected token in macro instantiation");
1060 if (Lexer.is(AsmToken::EndOfStatement))
1063 // If we aren't inside parentheses and this is a comma, start a new token
1065 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1066 MacroArguments.push_back(std::vector<AsmToken>());
1068 // Adjust the current parentheses level.
1069 if (Lexer.is(AsmToken::LParen))
1071 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1074 // Append the token to the current argument list.
1075 MacroArguments.back().push_back(getTok());
1080 // Create the macro instantiation object and add to the current macro
1081 // instantiation stack.
1082 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1085 ActiveMacros.push_back(MI);
1087 // Jump to the macro instantiation and prime the lexer.
1088 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1089 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1095 void AsmParser::HandleMacroExit() {
1096 // Jump to the EndOfStatement we should return to, and consume it.
1097 JumpToLoc(ActiveMacros.back()->ExitLoc);
1100 // Pop the instantiation entry.
1101 delete ActiveMacros.back();
1102 ActiveMacros.pop_back();
1105 bool AsmParser::ParseAssignment(StringRef Name) {
1106 // FIXME: Use better location, we should use proper tokens.
1107 SMLoc EqualLoc = Lexer.getLoc();
1109 const MCExpr *Value;
1110 if (ParseExpression(Value))
1113 if (Lexer.isNot(AsmToken::EndOfStatement))
1114 return TokError("unexpected token in assignment");
1116 // Eat the end of statement marker.
1119 // Validate that the LHS is allowed to be a variable (either it has not been
1120 // used as a symbol, or it is an absolute symbol).
1121 MCSymbol *Sym = getContext().LookupSymbol(Name);
1123 // Diagnose assignment to a label.
1125 // FIXME: Diagnostics. Note the location of the definition as a label.
1126 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1127 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1128 ; // Allow redefinitions of undefined symbols only used in directives.
1129 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1130 return Error(EqualLoc, "redefinition of '" + Name + "'");
1131 else if (!Sym->isVariable())
1132 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1133 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1134 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1137 Sym = getContext().GetOrCreateSymbol(Name);
1139 // FIXME: Handle '.'.
1141 Sym->setUsedInExpr(true);
1143 // Do the assignment.
1144 Out.EmitAssignment(Sym, Value);
1149 /// ParseIdentifier:
1152 bool AsmParser::ParseIdentifier(StringRef &Res) {
1153 // The assembler has relaxed rules for accepting identifiers, in particular we
1154 // allow things like '.globl $foo', which would normally be separate
1155 // tokens. At this level, we have already lexed so we cannot (currently)
1156 // handle this as a context dependent token, instead we detect adjacent tokens
1157 // and return the combined identifier.
1158 if (Lexer.is(AsmToken::Dollar)) {
1159 SMLoc DollarLoc = getLexer().getLoc();
1161 // Consume the dollar sign, and check for a following identifier.
1163 if (Lexer.isNot(AsmToken::Identifier))
1166 // We have a '$' followed by an identifier, make sure they are adjacent.
1167 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1170 // Construct the joined identifier and consume the token.
1171 Res = StringRef(DollarLoc.getPointer(),
1172 getTok().getIdentifier().size() + 1);
1177 if (Lexer.isNot(AsmToken::Identifier) &&
1178 Lexer.isNot(AsmToken::String))
1181 Res = getTok().getIdentifier();
1183 Lex(); // Consume the identifier token.
1188 /// ParseDirectiveSet:
1189 /// ::= .set identifier ',' expression
1190 bool AsmParser::ParseDirectiveSet() {
1193 if (ParseIdentifier(Name))
1194 return TokError("expected identifier after '.set' directive");
1196 if (getLexer().isNot(AsmToken::Comma))
1197 return TokError("unexpected token in '.set'");
1200 return ParseAssignment(Name);
1203 bool AsmParser::ParseEscapedString(std::string &Data) {
1204 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1207 StringRef Str = getTok().getStringContents();
1208 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1209 if (Str[i] != '\\') {
1214 // Recognize escaped characters. Note that this escape semantics currently
1215 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1218 return TokError("unexpected backslash at end of string");
1220 // Recognize octal sequences.
1221 if ((unsigned) (Str[i] - '0') <= 7) {
1222 // Consume up to three octal characters.
1223 unsigned Value = Str[i] - '0';
1225 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1227 Value = Value * 8 + (Str[i] - '0');
1229 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1231 Value = Value * 8 + (Str[i] - '0');
1236 return TokError("invalid octal escape sequence (out of range)");
1238 Data += (unsigned char) Value;
1242 // Otherwise recognize individual escapes.
1245 // Just reject invalid escape sequences for now.
1246 return TokError("invalid escape sequence (unrecognized character)");
1248 case 'b': Data += '\b'; break;
1249 case 'f': Data += '\f'; break;
1250 case 'n': Data += '\n'; break;
1251 case 'r': Data += '\r'; break;
1252 case 't': Data += '\t'; break;
1253 case '"': Data += '"'; break;
1254 case '\\': Data += '\\'; break;
1261 /// ParseDirectiveAscii:
1262 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1263 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1264 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1265 CheckForValidSection();
1268 if (getLexer().isNot(AsmToken::String))
1269 return TokError("expected string in '.ascii' or '.asciz' directive");
1272 if (ParseEscapedString(Data))
1275 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1277 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1281 if (getLexer().is(AsmToken::EndOfStatement))
1284 if (getLexer().isNot(AsmToken::Comma))
1285 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1294 /// ParseDirectiveValue
1295 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1296 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1297 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1298 CheckForValidSection();
1301 const MCExpr *Value;
1302 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1303 if (ParseExpression(Value))
1306 // Special case constant expressions to match code generator.
1307 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1308 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1310 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1312 if (getLexer().is(AsmToken::EndOfStatement))
1315 // FIXME: Improve diagnostic.
1316 if (getLexer().isNot(AsmToken::Comma))
1317 return TokError("unexpected token in directive");
1326 /// ParseDirectiveSpace
1327 /// ::= .space expression [ , expression ]
1328 bool AsmParser::ParseDirectiveSpace() {
1329 CheckForValidSection();
1332 if (ParseAbsoluteExpression(NumBytes))
1335 int64_t FillExpr = 0;
1336 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1337 if (getLexer().isNot(AsmToken::Comma))
1338 return TokError("unexpected token in '.space' directive");
1341 if (ParseAbsoluteExpression(FillExpr))
1344 if (getLexer().isNot(AsmToken::EndOfStatement))
1345 return TokError("unexpected token in '.space' directive");
1351 return TokError("invalid number of bytes in '.space' directive");
1353 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1354 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1359 /// ParseDirectiveZero
1360 /// ::= .zero expression
1361 bool AsmParser::ParseDirectiveZero() {
1362 CheckForValidSection();
1365 if (ParseAbsoluteExpression(NumBytes))
1368 if (getLexer().isNot(AsmToken::EndOfStatement))
1369 return TokError("unexpected token in '.zero' directive");
1373 getStreamer().EmitFill(NumBytes, 0, DEFAULT_ADDRSPACE);
1378 /// ParseDirectiveFill
1379 /// ::= .fill expression , expression , expression
1380 bool AsmParser::ParseDirectiveFill() {
1381 CheckForValidSection();
1384 if (ParseAbsoluteExpression(NumValues))
1387 if (getLexer().isNot(AsmToken::Comma))
1388 return TokError("unexpected token in '.fill' directive");
1392 if (ParseAbsoluteExpression(FillSize))
1395 if (getLexer().isNot(AsmToken::Comma))
1396 return TokError("unexpected token in '.fill' directive");
1400 if (ParseAbsoluteExpression(FillExpr))
1403 if (getLexer().isNot(AsmToken::EndOfStatement))
1404 return TokError("unexpected token in '.fill' directive");
1408 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1409 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1411 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1412 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1417 /// ParseDirectiveOrg
1418 /// ::= .org expression [ , expression ]
1419 bool AsmParser::ParseDirectiveOrg() {
1420 CheckForValidSection();
1422 const MCExpr *Offset;
1423 if (ParseExpression(Offset))
1426 // Parse optional fill expression.
1427 int64_t FillExpr = 0;
1428 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1429 if (getLexer().isNot(AsmToken::Comma))
1430 return TokError("unexpected token in '.org' directive");
1433 if (ParseAbsoluteExpression(FillExpr))
1436 if (getLexer().isNot(AsmToken::EndOfStatement))
1437 return TokError("unexpected token in '.org' directive");
1442 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1443 // has to be relative to the current section.
1444 getStreamer().EmitValueToOffset(Offset, FillExpr);
1449 /// ParseDirectiveAlign
1450 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1451 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1452 CheckForValidSection();
1454 SMLoc AlignmentLoc = getLexer().getLoc();
1456 if (ParseAbsoluteExpression(Alignment))
1460 bool HasFillExpr = false;
1461 int64_t FillExpr = 0;
1462 int64_t MaxBytesToFill = 0;
1463 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1464 if (getLexer().isNot(AsmToken::Comma))
1465 return TokError("unexpected token in directive");
1468 // The fill expression can be omitted while specifying a maximum number of
1469 // alignment bytes, e.g:
1471 if (getLexer().isNot(AsmToken::Comma)) {
1473 if (ParseAbsoluteExpression(FillExpr))
1477 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1478 if (getLexer().isNot(AsmToken::Comma))
1479 return TokError("unexpected token in directive");
1482 MaxBytesLoc = getLexer().getLoc();
1483 if (ParseAbsoluteExpression(MaxBytesToFill))
1486 if (getLexer().isNot(AsmToken::EndOfStatement))
1487 return TokError("unexpected token in directive");
1496 // Compute alignment in bytes.
1498 // FIXME: Diagnose overflow.
1499 if (Alignment >= 32) {
1500 Error(AlignmentLoc, "invalid alignment value");
1504 Alignment = 1ULL << Alignment;
1507 // Diagnose non-sensical max bytes to align.
1508 if (MaxBytesLoc.isValid()) {
1509 if (MaxBytesToFill < 1) {
1510 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1511 "many bytes, ignoring maximum bytes expression");
1515 if (MaxBytesToFill >= Alignment) {
1516 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1522 // Check whether we should use optimal code alignment for this .align
1525 // FIXME: This should be using a target hook.
1526 bool UseCodeAlign = false;
1527 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1528 getStreamer().getCurrentSection()))
1529 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1530 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1531 ValueSize == 1 && UseCodeAlign) {
1532 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1534 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1535 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1542 /// ParseDirectiveSymbolAttribute
1543 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1544 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1545 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1549 if (ParseIdentifier(Name))
1550 return TokError("expected identifier in directive");
1552 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1554 getStreamer().EmitSymbolAttribute(Sym, Attr);
1556 if (getLexer().is(AsmToken::EndOfStatement))
1559 if (getLexer().isNot(AsmToken::Comma))
1560 return TokError("unexpected token in directive");
1569 /// ParseDirectiveELFType
1570 /// ::= .type identifier , @attribute
1571 bool AsmParser::ParseDirectiveELFType() {
1573 if (ParseIdentifier(Name))
1574 return TokError("expected identifier in directive");
1576 // Handle the identifier as the key symbol.
1577 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1579 if (getLexer().isNot(AsmToken::Comma))
1580 return TokError("unexpected token in '.type' directive");
1583 if (getLexer().isNot(AsmToken::At))
1584 return TokError("expected '@' before type");
1590 TypeLoc = getLexer().getLoc();
1591 if (ParseIdentifier(Type))
1592 return TokError("expected symbol type in directive");
1594 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1595 .Case("function", MCSA_ELF_TypeFunction)
1596 .Case("object", MCSA_ELF_TypeObject)
1597 .Case("tls_object", MCSA_ELF_TypeTLS)
1598 .Case("common", MCSA_ELF_TypeCommon)
1599 .Case("notype", MCSA_ELF_TypeNoType)
1600 .Default(MCSA_Invalid);
1602 if (Attr == MCSA_Invalid)
1603 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1605 if (getLexer().isNot(AsmToken::EndOfStatement))
1606 return TokError("unexpected token in '.type' directive");
1610 getStreamer().EmitSymbolAttribute(Sym, Attr);
1615 /// ParseDirectiveComm
1616 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1617 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1618 CheckForValidSection();
1620 SMLoc IDLoc = getLexer().getLoc();
1622 if (ParseIdentifier(Name))
1623 return TokError("expected identifier in directive");
1625 // Handle the identifier as the key symbol.
1626 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1628 if (getLexer().isNot(AsmToken::Comma))
1629 return TokError("unexpected token in directive");
1633 SMLoc SizeLoc = getLexer().getLoc();
1634 if (ParseAbsoluteExpression(Size))
1637 int64_t Pow2Alignment = 0;
1638 SMLoc Pow2AlignmentLoc;
1639 if (getLexer().is(AsmToken::Comma)) {
1641 Pow2AlignmentLoc = getLexer().getLoc();
1642 if (ParseAbsoluteExpression(Pow2Alignment))
1645 // If this target takes alignments in bytes (not log) validate and convert.
1646 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1647 if (!isPowerOf2_64(Pow2Alignment))
1648 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1649 Pow2Alignment = Log2_64(Pow2Alignment);
1653 if (getLexer().isNot(AsmToken::EndOfStatement))
1654 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1658 // NOTE: a size of zero for a .comm should create a undefined symbol
1659 // but a size of .lcomm creates a bss symbol of size zero.
1661 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1662 "be less than zero");
1664 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1665 // may internally end up wanting an alignment in bytes.
1666 // FIXME: Diagnose overflow.
1667 if (Pow2Alignment < 0)
1668 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1669 "alignment, can't be less than zero");
1671 if (!Sym->isUndefined())
1672 return Error(IDLoc, "invalid symbol redefinition");
1674 // '.lcomm' is equivalent to '.zerofill'.
1675 // Create the Symbol as a common or local common with Size and Pow2Alignment
1677 getStreamer().EmitZerofill(Ctx.getMachOSection(
1678 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1679 0, SectionKind::getBSS()),
1680 Sym, Size, 1 << Pow2Alignment);
1684 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1688 /// ParseDirectiveAbort
1689 /// ::= .abort [... message ...]
1690 bool AsmParser::ParseDirectiveAbort() {
1691 // FIXME: Use loc from directive.
1692 SMLoc Loc = getLexer().getLoc();
1694 StringRef Str = ParseStringToEndOfStatement();
1695 if (getLexer().isNot(AsmToken::EndOfStatement))
1696 return TokError("unexpected token in '.abort' directive");
1701 Error(Loc, ".abort detected. Assembly stopping.");
1703 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1704 // FIXME: Actually abort assembly here.
1709 /// ParseDirectiveInclude
1710 /// ::= .include "filename"
1711 bool AsmParser::ParseDirectiveInclude() {
1712 if (getLexer().isNot(AsmToken::String))
1713 return TokError("expected string in '.include' directive");
1715 std::string Filename = getTok().getString();
1716 SMLoc IncludeLoc = getLexer().getLoc();
1719 if (getLexer().isNot(AsmToken::EndOfStatement))
1720 return TokError("unexpected token in '.include' directive");
1722 // Strip the quotes.
1723 Filename = Filename.substr(1, Filename.size()-2);
1725 // Attempt to switch the lexer to the included file before consuming the end
1726 // of statement to avoid losing it when we switch.
1727 if (EnterIncludeFile(Filename)) {
1728 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1735 /// ParseDirectiveIf
1736 /// ::= .if expression
1737 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1738 TheCondStack.push_back(TheCondState);
1739 TheCondState.TheCond = AsmCond::IfCond;
1740 if(TheCondState.Ignore) {
1741 EatToEndOfStatement();
1745 if (ParseAbsoluteExpression(ExprValue))
1748 if (getLexer().isNot(AsmToken::EndOfStatement))
1749 return TokError("unexpected token in '.if' directive");
1753 TheCondState.CondMet = ExprValue;
1754 TheCondState.Ignore = !TheCondState.CondMet;
1760 /// ParseDirectiveElseIf
1761 /// ::= .elseif expression
1762 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1763 if (TheCondState.TheCond != AsmCond::IfCond &&
1764 TheCondState.TheCond != AsmCond::ElseIfCond)
1765 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1767 TheCondState.TheCond = AsmCond::ElseIfCond;
1769 bool LastIgnoreState = false;
1770 if (!TheCondStack.empty())
1771 LastIgnoreState = TheCondStack.back().Ignore;
1772 if (LastIgnoreState || TheCondState.CondMet) {
1773 TheCondState.Ignore = true;
1774 EatToEndOfStatement();
1778 if (ParseAbsoluteExpression(ExprValue))
1781 if (getLexer().isNot(AsmToken::EndOfStatement))
1782 return TokError("unexpected token in '.elseif' directive");
1785 TheCondState.CondMet = ExprValue;
1786 TheCondState.Ignore = !TheCondState.CondMet;
1792 /// ParseDirectiveElse
1794 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1795 if (getLexer().isNot(AsmToken::EndOfStatement))
1796 return TokError("unexpected token in '.else' directive");
1800 if (TheCondState.TheCond != AsmCond::IfCond &&
1801 TheCondState.TheCond != AsmCond::ElseIfCond)
1802 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1804 TheCondState.TheCond = AsmCond::ElseCond;
1805 bool LastIgnoreState = false;
1806 if (!TheCondStack.empty())
1807 LastIgnoreState = TheCondStack.back().Ignore;
1808 if (LastIgnoreState || TheCondState.CondMet)
1809 TheCondState.Ignore = true;
1811 TheCondState.Ignore = false;
1816 /// ParseDirectiveEndIf
1818 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1819 if (getLexer().isNot(AsmToken::EndOfStatement))
1820 return TokError("unexpected token in '.endif' directive");
1824 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1825 TheCondStack.empty())
1826 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1828 if (!TheCondStack.empty()) {
1829 TheCondState = TheCondStack.back();
1830 TheCondStack.pop_back();
1836 /// ParseDirectiveFile
1837 /// ::= .file [number] string
1838 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1839 // FIXME: I'm not sure what this is.
1840 int64_t FileNumber = -1;
1841 SMLoc FileNumberLoc = getLexer().getLoc();
1842 if (getLexer().is(AsmToken::Integer)) {
1843 FileNumber = getTok().getIntVal();
1847 return TokError("file number less than one");
1850 if (getLexer().isNot(AsmToken::String))
1851 return TokError("unexpected token in '.file' directive");
1853 StringRef Filename = getTok().getString();
1854 Filename = Filename.substr(1, Filename.size()-2);
1857 if (getLexer().isNot(AsmToken::EndOfStatement))
1858 return TokError("unexpected token in '.file' directive");
1860 if (FileNumber == -1)
1861 getStreamer().EmitFileDirective(Filename);
1863 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1864 Error(FileNumberLoc, "file number already allocated");
1865 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1871 /// ParseDirectiveLine
1872 /// ::= .line [number]
1873 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1874 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1875 if (getLexer().isNot(AsmToken::Integer))
1876 return TokError("unexpected token in '.line' directive");
1878 int64_t LineNumber = getTok().getIntVal();
1882 // FIXME: Do something with the .line.
1885 if (getLexer().isNot(AsmToken::EndOfStatement))
1886 return TokError("unexpected token in '.line' directive");
1892 /// ParseDirectiveLoc
1893 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1894 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1895 /// The first number is a file number, must have been previously assigned with
1896 /// a .file directive, the second number is the line number and optionally the
1897 /// third number is a column position (zero if not specified). The remaining
1898 /// optional items are .loc sub-directives.
1899 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1901 if (getLexer().isNot(AsmToken::Integer))
1902 return TokError("unexpected token in '.loc' directive");
1903 int64_t FileNumber = getTok().getIntVal();
1905 return TokError("file number less than one in '.loc' directive");
1906 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1907 return TokError("unassigned file number in '.loc' directive");
1910 int64_t LineNumber = 0;
1911 if (getLexer().is(AsmToken::Integer)) {
1912 LineNumber = getTok().getIntVal();
1914 return TokError("line number less than one in '.loc' directive");
1918 int64_t ColumnPos = 0;
1919 if (getLexer().is(AsmToken::Integer)) {
1920 ColumnPos = getTok().getIntVal();
1922 return TokError("column position less than zero in '.loc' directive");
1928 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1930 if (getLexer().is(AsmToken::EndOfStatement))
1934 SMLoc Loc = getTok().getLoc();
1935 if (getParser().ParseIdentifier(Name))
1936 return TokError("unexpected token in '.loc' directive");
1938 if (Name == "basic_block")
1939 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1940 else if (Name == "prologue_end")
1941 Flags |= DWARF2_FLAG_PROLOGUE_END;
1942 else if (Name == "epilogue_begin")
1943 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1944 else if (Name == "is_stmt") {
1945 SMLoc Loc = getTok().getLoc();
1946 const MCExpr *Value;
1947 if (getParser().ParseExpression(Value))
1949 // The expression must be the constant 0 or 1.
1950 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1951 int Value = MCE->getValue();
1953 Flags &= ~DWARF2_FLAG_IS_STMT;
1954 else if (Value == 1)
1955 Flags |= DWARF2_FLAG_IS_STMT;
1957 return Error(Loc, "is_stmt value not 0 or 1");
1960 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1963 else if (Name == "isa") {
1964 SMLoc Loc = getTok().getLoc();
1965 const MCExpr *Value;
1966 if (getParser().ParseExpression(Value))
1968 // The expression must be a constant greater or equal to 0.
1969 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1970 int Value = MCE->getValue();
1972 return Error(Loc, "isa number less than zero");
1976 return Error(Loc, "isa number not a constant value");
1980 return Error(Loc, "unknown sub-directive in '.loc' directive");
1983 if (getLexer().is(AsmToken::EndOfStatement))
1988 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1993 /// ParseDirectiveMacrosOnOff
1996 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1997 SMLoc DirectiveLoc) {
1998 if (getLexer().isNot(AsmToken::EndOfStatement))
1999 return Error(getLexer().getLoc(),
2000 "unexpected token in '" + Directive + "' directive");
2002 getParser().MacrosEnabled = Directive == ".macros_on";
2007 /// ParseDirectiveMacro
2009 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2010 SMLoc DirectiveLoc) {
2012 if (getParser().ParseIdentifier(Name))
2013 return TokError("expected identifier in directive");
2015 if (getLexer().isNot(AsmToken::EndOfStatement))
2016 return TokError("unexpected token in '.macro' directive");
2018 // Eat the end of statement.
2021 AsmToken EndToken, StartToken = getTok();
2023 // Lex the macro definition.
2025 // Check whether we have reached the end of the file.
2026 if (getLexer().is(AsmToken::Eof))
2027 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2029 // Otherwise, check whether we have reach the .endmacro.
2030 if (getLexer().is(AsmToken::Identifier) &&
2031 (getTok().getIdentifier() == ".endm" ||
2032 getTok().getIdentifier() == ".endmacro")) {
2033 EndToken = getTok();
2035 if (getLexer().isNot(AsmToken::EndOfStatement))
2036 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2041 // Otherwise, scan til the end of the statement.
2042 getParser().EatToEndOfStatement();
2045 if (getParser().MacroMap.lookup(Name)) {
2046 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2049 const char *BodyStart = StartToken.getLoc().getPointer();
2050 const char *BodyEnd = EndToken.getLoc().getPointer();
2051 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2052 getParser().MacroMap[Name] = new Macro(Name, Body);
2056 /// ParseDirectiveEndMacro
2059 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2060 SMLoc DirectiveLoc) {
2061 if (getLexer().isNot(AsmToken::EndOfStatement))
2062 return TokError("unexpected token in '" + Directive + "' directive");
2064 // If we are inside a macro instantiation, terminate the current
2066 if (!getParser().ActiveMacros.empty()) {
2067 getParser().HandleMacroExit();
2071 // Otherwise, this .endmacro is a stray entry in the file; well formed
2072 // .endmacro directives are handled during the macro definition parsing.
2073 return TokError("unexpected '" + Directive + "' in file, "
2074 "no current macro definition");
2077 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2078 const uint64_t Mask = (1 << 7) - 1;
2080 unsigned Byte = Value & Mask;
2082 if (Value) // Not the last one
2084 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2088 void GenericAsmParser::ParseSleb128(int64_t Value) {
2089 const int64_t Mask = (1 << 7) - 1;
2091 unsigned Byte = Value & Mask;
2093 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2094 (Value == -1 && (Byte & 0x40) != 0));
2097 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2103 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2105 if (getParser().ParseAbsoluteExpression(Value))
2108 if (getLexer().isNot(AsmToken::EndOfStatement))
2109 return TokError("unexpected token in directive");
2111 if (DirName[1] == 's')
2112 ParseSleb128(Value);
2114 ParseUleb128(Value);
2119 /// \brief Create an MCAsmParser instance.
2120 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2121 MCContext &C, MCStreamer &Out,
2122 const MCAsmInfo &MAI) {
2123 return new AsmParser(T, SM, C, Out, MAI);