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/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.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 Twine &Msg, const char *Type) const {
152 SrcMgr.PrintMessage(Loc, Msg, Type);
155 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
156 bool EnterIncludeFile(const std::string &Filename);
158 /// \brief Reset the current lexer position to that given by \arg Loc. The
159 /// current token is not set; clients should ensure Lex() is called
161 void JumpToLoc(SMLoc Loc);
163 void EatToEndOfStatement();
165 /// \brief Parse up to the end of statement and a return the contents from the
166 /// current token until the end of the statement; the current token on exit
167 /// will be either the EndOfStatement or EOF.
168 StringRef ParseStringToEndOfStatement();
170 bool ParseAssignment(StringRef Name);
172 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
177 /// and set \arg Res to the identifier contents.
178 bool ParseIdentifier(StringRef &Res);
180 // Directive Parsing.
181 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
182 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
183 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
184 bool ParseDirectiveFill(); // ".fill"
185 bool ParseDirectiveSpace(); // ".space"
186 bool ParseDirectiveZero(); // ".zero"
187 bool ParseDirectiveSet(); // ".set"
188 bool ParseDirectiveOrg(); // ".org"
189 // ".align{,32}", ".p2align{,w,l}"
190 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
192 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
193 /// accepts a single symbol (which should be a label or an external).
194 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
195 bool ParseDirectiveELFType(); // ELF specific ".type"
197 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
199 bool ParseDirectiveAbort(); // ".abort"
200 bool ParseDirectiveInclude(); // ".include"
202 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
203 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
204 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
205 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
207 /// ParseEscapedString - Parse the current token as a string which may include
208 /// escaped characters and return the string contents.
209 bool ParseEscapedString(std::string &Data);
211 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
212 MCSymbolRefExpr::VariantKind Variant);
215 /// \brief Generic implementations of directive handling, etc. which is shared
216 /// (or the default, at least) for all assembler parser.
217 class GenericAsmParser : public MCAsmParserExtension {
218 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
219 void AddDirectiveHandler(StringRef Directive) {
220 getParser().AddDirectiveHandler(this, Directive,
221 HandleDirective<GenericAsmParser, Handler>);
225 GenericAsmParser() {}
227 AsmParser &getParser() {
228 return (AsmParser&) this->MCAsmParserExtension::getParser();
231 virtual void Initialize(MCAsmParser &Parser) {
232 // Call the base implementation.
233 this->MCAsmParserExtension::Initialize(Parser);
235 // Debugging directives.
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
253 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
254 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
255 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
257 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
258 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
259 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
261 void ParseUleb128(uint64_t Value);
262 void ParseSleb128(int64_t Value);
263 bool ParseDirectiveLEB128(StringRef, SMLoc);
270 extern MCAsmParserExtension *createDarwinAsmParser();
271 extern MCAsmParserExtension *createELFAsmParser();
275 enum { DEFAULT_ADDRSPACE = 0 };
277 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
278 MCStreamer &_Out, const MCAsmInfo &_MAI)
279 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
280 GenericParser(new GenericAsmParser), PlatformParser(0),
281 CurBuffer(0), MacrosEnabled(true) {
282 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
284 // Initialize the generic parser.
285 GenericParser->Initialize(*this);
287 // Initialize the platform / file format parser.
289 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
291 if (_MAI.hasSubsectionsViaSymbols()) {
292 PlatformParser = createDarwinAsmParser();
293 PlatformParser->Initialize(*this);
295 PlatformParser = createELFAsmParser();
296 PlatformParser->Initialize(*this);
300 AsmParser::~AsmParser() {
301 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
303 // Destroy any macros.
304 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
305 ie = MacroMap.end(); it != ie; ++it)
306 delete it->getValue();
308 delete PlatformParser;
309 delete GenericParser;
312 void AsmParser::PrintMacroInstantiations() {
313 // Print the active macro instantiation stack.
314 for (std::vector<MacroInstantiation*>::const_reverse_iterator
315 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
316 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
320 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
321 PrintMessage(L, Msg, "warning");
322 PrintMacroInstantiations();
325 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
327 PrintMessage(L, Msg, "error");
328 PrintMacroInstantiations();
332 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
333 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
339 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
344 void AsmParser::JumpToLoc(SMLoc Loc) {
345 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
346 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
349 const AsmToken &AsmParser::Lex() {
350 const AsmToken *tok = &Lexer.Lex();
352 if (tok->is(AsmToken::Eof)) {
353 // If this is the end of an included file, pop the parent file off the
355 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
356 if (ParentIncludeLoc != SMLoc()) {
357 JumpToLoc(ParentIncludeLoc);
362 if (tok->is(AsmToken::Error))
363 Error(Lexer.getErrLoc(), Lexer.getErr());
368 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
369 // Create the initial section, if requested.
370 if (!NoInitialTextSection)
377 AsmCond StartingCondState = TheCondState;
379 // While we have input, parse each statement.
380 while (Lexer.isNot(AsmToken::Eof)) {
381 if (!ParseStatement()) continue;
383 // We had an error, validate that one was emitted and recover by skipping to
385 assert(HadError && "Parse statement returned an error, but none emitted!");
386 EatToEndOfStatement();
389 if (TheCondState.TheCond != StartingCondState.TheCond ||
390 TheCondState.Ignore != StartingCondState.Ignore)
391 return TokError("unmatched .ifs or .elses");
393 // Check to see there are no empty DwarfFile slots.
394 const std::vector<MCDwarfFile *> &MCDwarfFiles =
395 getContext().getMCDwarfFiles();
396 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
397 if (!MCDwarfFiles[i])
398 TokError("unassigned file number: " + Twine(i) + " for .file directives");
401 // Finalize the output stream if there are no errors and if the client wants
403 if (!HadError && !NoFinalize)
409 void AsmParser::CheckForValidSection() {
410 if (!getStreamer().getCurrentSection()) {
411 TokError("expected section directive before assembly directive");
412 Out.SwitchSection(Ctx.getMachOSection(
414 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
415 0, SectionKind::getText()));
419 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
420 void AsmParser::EatToEndOfStatement() {
421 while (Lexer.isNot(AsmToken::EndOfStatement) &&
422 Lexer.isNot(AsmToken::Eof))
426 if (Lexer.is(AsmToken::EndOfStatement))
430 StringRef AsmParser::ParseStringToEndOfStatement() {
431 const char *Start = getTok().getLoc().getPointer();
433 while (Lexer.isNot(AsmToken::EndOfStatement) &&
434 Lexer.isNot(AsmToken::Eof))
437 const char *End = getTok().getLoc().getPointer();
438 return StringRef(Start, End - Start);
441 /// ParseParenExpr - Parse a paren expression and return it.
442 /// NOTE: This assumes the leading '(' has already been consumed.
444 /// parenexpr ::= expr)
446 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
447 if (ParseExpression(Res)) return true;
448 if (Lexer.isNot(AsmToken::RParen))
449 return TokError("expected ')' in parentheses expression");
450 EndLoc = Lexer.getLoc();
455 /// ParsePrimaryExpr - Parse a primary expression and return it.
456 /// primaryexpr ::= (parenexpr
457 /// primaryexpr ::= symbol
458 /// primaryexpr ::= number
459 /// primaryexpr ::= '.'
460 /// primaryexpr ::= ~,+,- primaryexpr
461 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
462 switch (Lexer.getKind()) {
464 return TokError("unknown token in expression");
465 case AsmToken::Exclaim:
466 Lex(); // Eat the operator.
467 if (ParsePrimaryExpr(Res, EndLoc))
469 Res = MCUnaryExpr::CreateLNot(Res, getContext());
471 case AsmToken::Dollar:
472 case AsmToken::String:
473 case AsmToken::Identifier: {
474 EndLoc = Lexer.getLoc();
476 StringRef Identifier;
477 if (ParseIdentifier(Identifier))
480 // This is a symbol reference.
481 std::pair<StringRef, StringRef> Split = Identifier.split('@');
482 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
484 // Mark the symbol as used in an expression.
485 Sym->setUsedInExpr(true);
487 // Lookup the symbol variant if used.
488 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
489 if (Split.first.size() != Identifier.size()) {
490 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
491 if (Variant == MCSymbolRefExpr::VK_Invalid) {
492 Variant = MCSymbolRefExpr::VK_None;
493 TokError("invalid variant '" + Split.second + "'");
497 // If this is an absolute variable reference, substitute it now to preserve
498 // semantics in the face of reassignment.
499 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
501 return Error(EndLoc, "unexpected modified on variable reference");
503 Res = Sym->getVariableValue();
507 // Otherwise create a symbol ref.
508 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
511 case AsmToken::Integer: {
512 SMLoc Loc = getTok().getLoc();
513 int64_t IntVal = getTok().getIntVal();
514 Res = MCConstantExpr::Create(IntVal, getContext());
515 EndLoc = Lexer.getLoc();
517 // Look for 'b' or 'f' following an Integer as a directional label
518 if (Lexer.getKind() == AsmToken::Identifier) {
519 StringRef IDVal = getTok().getString();
520 if (IDVal == "f" || IDVal == "b"){
521 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
522 IDVal == "f" ? 1 : 0);
523 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
525 if(IDVal == "b" && Sym->isUndefined())
526 return Error(Loc, "invalid reference to undefined symbol");
527 EndLoc = Lexer.getLoc();
528 Lex(); // Eat identifier.
533 case AsmToken::Dot: {
534 // This is a '.' reference, which references the current PC. Emit a
535 // temporary label to the streamer and refer to it.
536 MCSymbol *Sym = Ctx.CreateTempSymbol();
538 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
539 EndLoc = Lexer.getLoc();
540 Lex(); // Eat identifier.
544 case AsmToken::LParen:
545 Lex(); // Eat the '('.
546 return ParseParenExpr(Res, EndLoc);
547 case AsmToken::Minus:
548 Lex(); // Eat the operator.
549 if (ParsePrimaryExpr(Res, EndLoc))
551 Res = MCUnaryExpr::CreateMinus(Res, getContext());
554 Lex(); // Eat the operator.
555 if (ParsePrimaryExpr(Res, EndLoc))
557 Res = MCUnaryExpr::CreatePlus(Res, getContext());
559 case AsmToken::Tilde:
560 Lex(); // Eat the operator.
561 if (ParsePrimaryExpr(Res, EndLoc))
563 Res = MCUnaryExpr::CreateNot(Res, getContext());
568 bool AsmParser::ParseExpression(const MCExpr *&Res) {
570 return ParseExpression(Res, EndLoc);
574 AsmParser::ApplyModifierToExpr(const MCExpr *E,
575 MCSymbolRefExpr::VariantKind Variant) {
576 // Recurse over the given expression, rebuilding it to apply the given variant
577 // if there is exactly one symbol.
578 switch (E->getKind()) {
580 case MCExpr::Constant:
583 case MCExpr::SymbolRef: {
584 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
586 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
587 TokError("invalid variant on expression '" +
588 getTok().getIdentifier() + "' (already modified)");
592 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
595 case MCExpr::Unary: {
596 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
597 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
600 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
603 case MCExpr::Binary: {
604 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
605 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
606 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
611 if (!LHS) LHS = BE->getLHS();
612 if (!RHS) RHS = BE->getRHS();
614 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
618 assert(0 && "Invalid expression kind!");
622 /// ParseExpression - Parse an expression and return it.
624 /// expr ::= expr +,- expr -> lowest.
625 /// expr ::= expr |,^,&,! expr -> middle.
626 /// expr ::= expr *,/,%,<<,>> expr -> highest.
627 /// expr ::= primaryexpr
629 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
630 // Parse the expression.
632 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
635 // As a special case, we support 'a op b @ modifier' by rewriting the
636 // expression to include the modifier. This is inefficient, but in general we
637 // expect users to use 'a@modifier op b'.
638 if (Lexer.getKind() == AsmToken::At) {
641 if (Lexer.isNot(AsmToken::Identifier))
642 return TokError("unexpected symbol modifier following '@'");
644 MCSymbolRefExpr::VariantKind Variant =
645 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
646 if (Variant == MCSymbolRefExpr::VK_Invalid)
647 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
649 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
651 return TokError("invalid modifier '" + getTok().getIdentifier() +
652 "' (no symbols present)");
660 // Try to constant fold it up front, if possible.
662 if (Res->EvaluateAsAbsolute(Value))
663 Res = MCConstantExpr::Create(Value, getContext());
668 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
670 return ParseParenExpr(Res, EndLoc) ||
671 ParseBinOpRHS(1, Res, EndLoc);
674 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
677 SMLoc StartLoc = Lexer.getLoc();
678 if (ParseExpression(Expr))
681 if (!Expr->EvaluateAsAbsolute(Res))
682 return Error(StartLoc, "expected absolute expression");
687 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
688 MCBinaryExpr::Opcode &Kind) {
691 return 0; // not a binop.
693 // Lowest Precedence: &&, ||, @
694 case AsmToken::AmpAmp:
695 Kind = MCBinaryExpr::LAnd;
697 case AsmToken::PipePipe:
698 Kind = MCBinaryExpr::LOr;
702 // Low Precedence: |, &, ^
704 // FIXME: gas seems to support '!' as an infix operator?
706 Kind = MCBinaryExpr::Or;
708 case AsmToken::Caret:
709 Kind = MCBinaryExpr::Xor;
712 Kind = MCBinaryExpr::And;
715 // Intermediate Precedence: +, -, ==, !=, <>, <, <=, >, >=
717 Kind = MCBinaryExpr::Add;
719 case AsmToken::Minus:
720 Kind = MCBinaryExpr::Sub;
722 case AsmToken::EqualEqual:
723 Kind = MCBinaryExpr::EQ;
725 case AsmToken::ExclaimEqual:
726 case AsmToken::LessGreater:
727 Kind = MCBinaryExpr::NE;
730 Kind = MCBinaryExpr::LT;
732 case AsmToken::LessEqual:
733 Kind = MCBinaryExpr::LTE;
735 case AsmToken::Greater:
736 Kind = MCBinaryExpr::GT;
738 case AsmToken::GreaterEqual:
739 Kind = MCBinaryExpr::GTE;
742 // Highest Precedence: *, /, %, <<, >>
744 Kind = MCBinaryExpr::Mul;
746 case AsmToken::Slash:
747 Kind = MCBinaryExpr::Div;
749 case AsmToken::Percent:
750 Kind = MCBinaryExpr::Mod;
752 case AsmToken::LessLess:
753 Kind = MCBinaryExpr::Shl;
755 case AsmToken::GreaterGreater:
756 Kind = MCBinaryExpr::Shr;
762 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
763 /// Res contains the LHS of the expression on input.
764 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
767 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
768 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
770 // If the next token is lower precedence than we are allowed to eat, return
771 // successfully with what we ate already.
772 if (TokPrec < Precedence)
777 // Eat the next primary expression.
779 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
781 // If BinOp binds less tightly with RHS than the operator after RHS, let
782 // the pending operator take RHS as its LHS.
783 MCBinaryExpr::Opcode Dummy;
784 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
785 if (TokPrec < NextTokPrec) {
786 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
789 // Merge LHS and RHS according to operator.
790 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
798 /// ::= EndOfStatement
799 /// ::= Label* Directive ...Operands... EndOfStatement
800 /// ::= Label* Identifier OperandList* EndOfStatement
801 bool AsmParser::ParseStatement() {
802 if (Lexer.is(AsmToken::EndOfStatement)) {
808 // Statements always start with an identifier.
809 AsmToken ID = getTok();
810 SMLoc IDLoc = ID.getLoc();
812 int64_t LocalLabelVal = -1;
813 // GUESS allow an integer followed by a ':' as a directional local label
814 if (Lexer.is(AsmToken::Integer)) {
815 LocalLabelVal = getTok().getIntVal();
816 if (LocalLabelVal < 0) {
817 if (!TheCondState.Ignore)
818 return TokError("unexpected token at start of statement");
822 IDVal = getTok().getString();
823 Lex(); // Consume the integer token to be used as an identifier token.
824 if (Lexer.getKind() != AsmToken::Colon) {
825 if (!TheCondState.Ignore)
826 return TokError("unexpected token at start of statement");
830 else if (ParseIdentifier(IDVal)) {
831 if (!TheCondState.Ignore)
832 return TokError("unexpected token at start of statement");
836 // Handle conditional assembly here before checking for skipping. We
837 // have to do this so that .endif isn't skipped in a ".if 0" block for
840 return ParseDirectiveIf(IDLoc);
841 if (IDVal == ".elseif")
842 return ParseDirectiveElseIf(IDLoc);
843 if (IDVal == ".else")
844 return ParseDirectiveElse(IDLoc);
845 if (IDVal == ".endif")
846 return ParseDirectiveEndIf(IDLoc);
848 // If we are in a ".if 0" block, ignore this statement.
849 if (TheCondState.Ignore) {
850 EatToEndOfStatement();
854 // FIXME: Recurse on local labels?
856 // See what kind of statement we have.
857 switch (Lexer.getKind()) {
858 case AsmToken::Colon: {
859 CheckForValidSection();
861 // identifier ':' -> Label.
864 // Diagnose attempt to use a variable as a label.
866 // FIXME: Diagnostics. Note the location of the definition as a label.
867 // FIXME: This doesn't diagnose assignment to a symbol which has been
868 // implicitly marked as external.
870 if (LocalLabelVal == -1)
871 Sym = getContext().GetOrCreateSymbol(IDVal);
873 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
874 if (!Sym->isUndefined() || Sym->isVariable())
875 return Error(IDLoc, "invalid symbol redefinition");
880 // Consume any end of statement token, if present, to avoid spurious
881 // AddBlankLine calls().
882 if (Lexer.is(AsmToken::EndOfStatement)) {
884 if (Lexer.is(AsmToken::Eof))
888 return ParseStatement();
891 case AsmToken::Equal:
892 // identifier '=' ... -> assignment statement
895 return ParseAssignment(IDVal);
897 default: // Normal instruction or directive.
901 // If macros are enabled, check to see if this is a macro instantiation.
903 if (const Macro *M = MacroMap.lookup(IDVal))
904 return HandleMacroEntry(IDVal, IDLoc, M);
906 // Otherwise, we have a normal instruction or directive.
907 if (IDVal[0] == '.') {
908 // Assembler features
910 return ParseDirectiveSet();
914 if (IDVal == ".ascii")
915 return ParseDirectiveAscii(false);
916 if (IDVal == ".asciz")
917 return ParseDirectiveAscii(true);
919 if (IDVal == ".byte")
920 return ParseDirectiveValue(1);
921 if (IDVal == ".short")
922 return ParseDirectiveValue(2);
923 if (IDVal == ".long")
924 return ParseDirectiveValue(4);
925 if (IDVal == ".quad")
926 return ParseDirectiveValue(8);
927 if (IDVal == ".single")
928 return ParseDirectiveRealValue(APFloat::IEEEsingle);
929 if (IDVal == ".double")
930 return ParseDirectiveRealValue(APFloat::IEEEdouble);
932 if (IDVal == ".align") {
933 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
934 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
936 if (IDVal == ".align32") {
937 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
938 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
940 if (IDVal == ".balign")
941 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
942 if (IDVal == ".balignw")
943 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
944 if (IDVal == ".balignl")
945 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
946 if (IDVal == ".p2align")
947 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
948 if (IDVal == ".p2alignw")
949 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
950 if (IDVal == ".p2alignl")
951 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
954 return ParseDirectiveOrg();
956 if (IDVal == ".fill")
957 return ParseDirectiveFill();
958 if (IDVal == ".space")
959 return ParseDirectiveSpace();
960 if (IDVal == ".zero")
961 return ParseDirectiveZero();
963 // Symbol attribute directives
965 if (IDVal == ".globl" || IDVal == ".global")
966 return ParseDirectiveSymbolAttribute(MCSA_Global);
967 // ELF only? Should it be here?
968 if (IDVal == ".local")
969 return ParseDirectiveSymbolAttribute(MCSA_Local);
970 if (IDVal == ".hidden")
971 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
972 if (IDVal == ".indirect_symbol")
973 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
974 if (IDVal == ".internal")
975 return ParseDirectiveSymbolAttribute(MCSA_Internal);
976 if (IDVal == ".lazy_reference")
977 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
978 if (IDVal == ".no_dead_strip")
979 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
980 if (IDVal == ".private_extern")
981 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
982 if (IDVal == ".protected")
983 return ParseDirectiveSymbolAttribute(MCSA_Protected);
984 if (IDVal == ".reference")
985 return ParseDirectiveSymbolAttribute(MCSA_Reference);
986 if (IDVal == ".type")
987 return ParseDirectiveELFType();
988 if (IDVal == ".weak")
989 return ParseDirectiveSymbolAttribute(MCSA_Weak);
990 if (IDVal == ".weak_definition")
991 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
992 if (IDVal == ".weak_reference")
993 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
994 if (IDVal == ".weak_def_can_be_hidden")
995 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
997 if (IDVal == ".comm")
998 return ParseDirectiveComm(/*IsLocal=*/false);
999 if (IDVal == ".lcomm")
1000 return ParseDirectiveComm(/*IsLocal=*/true);
1002 if (IDVal == ".abort")
1003 return ParseDirectiveAbort();
1004 if (IDVal == ".include")
1005 return ParseDirectiveInclude();
1007 // Look up the handler in the handler table.
1008 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1009 DirectiveMap.lookup(IDVal);
1011 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1013 // Target hook for parsing target specific directives.
1014 if (!getTargetParser().ParseDirective(ID))
1017 Warning(IDLoc, "ignoring directive for now");
1018 EatToEndOfStatement();
1022 CheckForValidSection();
1024 // Canonicalize the opcode to lower case.
1025 SmallString<128> Opcode;
1026 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1027 Opcode.push_back(tolower(IDVal[i]));
1029 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1030 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1033 // Dump the parsed representation, if requested.
1034 if (getShowParsedOperands()) {
1035 SmallString<256> Str;
1036 raw_svector_ostream OS(Str);
1037 OS << "parsed instruction: [";
1038 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1041 ParsedOperands[i]->dump(OS);
1045 PrintMessage(IDLoc, OS.str(), "note");
1048 // If parsing succeeded, match the instruction.
1050 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1053 // Free any parsed operands.
1054 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1055 delete ParsedOperands[i];
1057 // Don't skip the rest of the line, the instruction parser is responsible for
1062 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1063 const std::vector<std::vector<AsmToken> > &A)
1064 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1066 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1067 // to hold the macro body with substitutions.
1068 SmallString<256> Buf;
1069 raw_svector_ostream OS(Buf);
1071 StringRef Body = M->Body;
1072 while (!Body.empty()) {
1073 // Scan for the next substitution.
1074 std::size_t End = Body.size(), Pos = 0;
1075 for (; Pos != End; ++Pos) {
1076 // Check for a substitution or escape.
1077 if (Body[Pos] != '$' || Pos + 1 == End)
1080 char Next = Body[Pos + 1];
1081 if (Next == '$' || Next == 'n' || isdigit(Next))
1086 OS << Body.slice(0, Pos);
1088 // Check if we reached the end.
1092 switch (Body[Pos+1]) {
1098 // $n => number of arguments
1103 // $[0-9] => argument
1105 // Missing arguments are ignored.
1106 unsigned Index = Body[Pos+1] - '0';
1107 if (Index >= A.size())
1110 // Otherwise substitute with the token values, with spaces eliminated.
1111 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1112 ie = A[Index].end(); it != ie; ++it)
1113 OS << it->getString();
1118 // Update the scan point.
1119 Body = Body.substr(Pos + 2);
1122 // We include the .endmacro in the buffer as our queue to exit the macro
1124 OS << ".endmacro\n";
1126 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1129 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1131 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1132 // this, although we should protect against infinite loops.
1133 if (ActiveMacros.size() == 20)
1134 return TokError("macros cannot be nested more than 20 levels deep");
1136 // Parse the macro instantiation arguments.
1137 std::vector<std::vector<AsmToken> > MacroArguments;
1138 MacroArguments.push_back(std::vector<AsmToken>());
1139 unsigned ParenLevel = 0;
1141 if (Lexer.is(AsmToken::Eof))
1142 return TokError("unexpected token in macro instantiation");
1143 if (Lexer.is(AsmToken::EndOfStatement))
1146 // If we aren't inside parentheses and this is a comma, start a new token
1148 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1149 MacroArguments.push_back(std::vector<AsmToken>());
1151 // Adjust the current parentheses level.
1152 if (Lexer.is(AsmToken::LParen))
1154 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1157 // Append the token to the current argument list.
1158 MacroArguments.back().push_back(getTok());
1163 // Create the macro instantiation object and add to the current macro
1164 // instantiation stack.
1165 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1168 ActiveMacros.push_back(MI);
1170 // Jump to the macro instantiation and prime the lexer.
1171 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1172 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1178 void AsmParser::HandleMacroExit() {
1179 // Jump to the EndOfStatement we should return to, and consume it.
1180 JumpToLoc(ActiveMacros.back()->ExitLoc);
1183 // Pop the instantiation entry.
1184 delete ActiveMacros.back();
1185 ActiveMacros.pop_back();
1188 bool AsmParser::ParseAssignment(StringRef Name) {
1189 // FIXME: Use better location, we should use proper tokens.
1190 SMLoc EqualLoc = Lexer.getLoc();
1192 const MCExpr *Value;
1193 if (ParseExpression(Value))
1196 if (Lexer.isNot(AsmToken::EndOfStatement))
1197 return TokError("unexpected token in assignment");
1199 // Eat the end of statement marker.
1202 // Validate that the LHS is allowed to be a variable (either it has not been
1203 // used as a symbol, or it is an absolute symbol).
1204 MCSymbol *Sym = getContext().LookupSymbol(Name);
1206 // Diagnose assignment to a label.
1208 // FIXME: Diagnostics. Note the location of the definition as a label.
1209 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1210 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1211 ; // Allow redefinitions of undefined symbols only used in directives.
1212 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1213 return Error(EqualLoc, "redefinition of '" + Name + "'");
1214 else if (!Sym->isVariable())
1215 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1216 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1217 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1220 Sym = getContext().GetOrCreateSymbol(Name);
1222 // FIXME: Handle '.'.
1224 Sym->setUsedInExpr(true);
1226 // Do the assignment.
1227 Out.EmitAssignment(Sym, Value);
1232 /// ParseIdentifier:
1235 bool AsmParser::ParseIdentifier(StringRef &Res) {
1236 // The assembler has relaxed rules for accepting identifiers, in particular we
1237 // allow things like '.globl $foo', which would normally be separate
1238 // tokens. At this level, we have already lexed so we cannot (currently)
1239 // handle this as a context dependent token, instead we detect adjacent tokens
1240 // and return the combined identifier.
1241 if (Lexer.is(AsmToken::Dollar)) {
1242 SMLoc DollarLoc = getLexer().getLoc();
1244 // Consume the dollar sign, and check for a following identifier.
1246 if (Lexer.isNot(AsmToken::Identifier))
1249 // We have a '$' followed by an identifier, make sure they are adjacent.
1250 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1253 // Construct the joined identifier and consume the token.
1254 Res = StringRef(DollarLoc.getPointer(),
1255 getTok().getIdentifier().size() + 1);
1260 if (Lexer.isNot(AsmToken::Identifier) &&
1261 Lexer.isNot(AsmToken::String))
1264 Res = getTok().getIdentifier();
1266 Lex(); // Consume the identifier token.
1271 /// ParseDirectiveSet:
1272 /// ::= .set identifier ',' expression
1273 bool AsmParser::ParseDirectiveSet() {
1276 if (ParseIdentifier(Name))
1277 return TokError("expected identifier after '.set' directive");
1279 if (getLexer().isNot(AsmToken::Comma))
1280 return TokError("unexpected token in '.set'");
1283 return ParseAssignment(Name);
1286 bool AsmParser::ParseEscapedString(std::string &Data) {
1287 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1290 StringRef Str = getTok().getStringContents();
1291 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1292 if (Str[i] != '\\') {
1297 // Recognize escaped characters. Note that this escape semantics currently
1298 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1301 return TokError("unexpected backslash at end of string");
1303 // Recognize octal sequences.
1304 if ((unsigned) (Str[i] - '0') <= 7) {
1305 // Consume up to three octal characters.
1306 unsigned Value = Str[i] - '0';
1308 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1310 Value = Value * 8 + (Str[i] - '0');
1312 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1314 Value = Value * 8 + (Str[i] - '0');
1319 return TokError("invalid octal escape sequence (out of range)");
1321 Data += (unsigned char) Value;
1325 // Otherwise recognize individual escapes.
1328 // Just reject invalid escape sequences for now.
1329 return TokError("invalid escape sequence (unrecognized character)");
1331 case 'b': Data += '\b'; break;
1332 case 'f': Data += '\f'; break;
1333 case 'n': Data += '\n'; break;
1334 case 'r': Data += '\r'; break;
1335 case 't': Data += '\t'; break;
1336 case '"': Data += '"'; break;
1337 case '\\': Data += '\\'; break;
1344 /// ParseDirectiveAscii:
1345 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1346 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1348 CheckForValidSection();
1351 if (getLexer().isNot(AsmToken::String))
1352 return TokError("expected string in '.ascii' or '.asciz' directive");
1355 if (ParseEscapedString(Data))
1358 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1360 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1364 if (getLexer().is(AsmToken::EndOfStatement))
1367 if (getLexer().isNot(AsmToken::Comma))
1368 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1377 /// ParseDirectiveValue
1378 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1379 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1381 CheckForValidSection();
1384 const MCExpr *Value;
1385 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1386 if (ParseExpression(Value))
1389 // Special case constant expressions to match code generator.
1390 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1391 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1393 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1395 if (getLexer().is(AsmToken::EndOfStatement))
1398 // FIXME: Improve diagnostic.
1399 if (getLexer().isNot(AsmToken::Comma))
1400 return TokError("unexpected token in directive");
1409 /// ParseDirectiveRealValue
1410 /// ::= (.single | .double) [ expression (, expression)* ]
1411 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1412 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1413 CheckForValidSection();
1416 // We don't truly support arithmetic on floating point expressions, so we
1417 // have to manually parse unary prefixes.
1419 if (getLexer().is(AsmToken::Minus)) {
1422 } else if (getLexer().is(AsmToken::Plus))
1425 if (getLexer().isNot(AsmToken::Integer) &&
1426 getLexer().isNot(AsmToken::Real))
1427 return TokError("unexpected token in directive");
1429 // Convert to an APFloat.
1430 APFloat Value(Semantics);
1431 if (Value.convertFromString(getTok().getString(),
1432 APFloat::rmNearestTiesToEven) ==
1433 APFloat::opInvalidOp)
1434 return TokError("invalid floating point literal");
1438 // Consume the numeric token.
1441 // Emit the value as an integer.
1442 APInt AsInt = Value.bitcastToAPInt();
1443 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1444 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1446 if (getLexer().is(AsmToken::EndOfStatement))
1449 if (getLexer().isNot(AsmToken::Comma))
1450 return TokError("unexpected token in directive");
1459 /// ParseDirectiveSpace
1460 /// ::= .space expression [ , expression ]
1461 bool AsmParser::ParseDirectiveSpace() {
1462 CheckForValidSection();
1465 if (ParseAbsoluteExpression(NumBytes))
1468 int64_t FillExpr = 0;
1469 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1470 if (getLexer().isNot(AsmToken::Comma))
1471 return TokError("unexpected token in '.space' directive");
1474 if (ParseAbsoluteExpression(FillExpr))
1477 if (getLexer().isNot(AsmToken::EndOfStatement))
1478 return TokError("unexpected token in '.space' directive");
1484 return TokError("invalid number of bytes in '.space' directive");
1486 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1487 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1492 /// ParseDirectiveZero
1493 /// ::= .zero expression
1494 bool AsmParser::ParseDirectiveZero() {
1495 CheckForValidSection();
1498 if (ParseAbsoluteExpression(NumBytes))
1502 if (getLexer().is(AsmToken::Comma)) {
1504 if (ParseAbsoluteExpression(Val))
1508 if (getLexer().isNot(AsmToken::EndOfStatement))
1509 return TokError("unexpected token in '.zero' directive");
1513 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1518 /// ParseDirectiveFill
1519 /// ::= .fill expression , expression , expression
1520 bool AsmParser::ParseDirectiveFill() {
1521 CheckForValidSection();
1524 if (ParseAbsoluteExpression(NumValues))
1527 if (getLexer().isNot(AsmToken::Comma))
1528 return TokError("unexpected token in '.fill' directive");
1532 if (ParseAbsoluteExpression(FillSize))
1535 if (getLexer().isNot(AsmToken::Comma))
1536 return TokError("unexpected token in '.fill' directive");
1540 if (ParseAbsoluteExpression(FillExpr))
1543 if (getLexer().isNot(AsmToken::EndOfStatement))
1544 return TokError("unexpected token in '.fill' directive");
1548 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1549 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1551 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1552 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1557 /// ParseDirectiveOrg
1558 /// ::= .org expression [ , expression ]
1559 bool AsmParser::ParseDirectiveOrg() {
1560 CheckForValidSection();
1562 const MCExpr *Offset;
1563 if (ParseExpression(Offset))
1566 // Parse optional fill expression.
1567 int64_t FillExpr = 0;
1568 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1569 if (getLexer().isNot(AsmToken::Comma))
1570 return TokError("unexpected token in '.org' directive");
1573 if (ParseAbsoluteExpression(FillExpr))
1576 if (getLexer().isNot(AsmToken::EndOfStatement))
1577 return TokError("unexpected token in '.org' directive");
1582 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1583 // has to be relative to the current section.
1584 getStreamer().EmitValueToOffset(Offset, FillExpr);
1589 /// ParseDirectiveAlign
1590 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1591 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1592 CheckForValidSection();
1594 SMLoc AlignmentLoc = getLexer().getLoc();
1596 if (ParseAbsoluteExpression(Alignment))
1600 bool HasFillExpr = false;
1601 int64_t FillExpr = 0;
1602 int64_t MaxBytesToFill = 0;
1603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1604 if (getLexer().isNot(AsmToken::Comma))
1605 return TokError("unexpected token in directive");
1608 // The fill expression can be omitted while specifying a maximum number of
1609 // alignment bytes, e.g:
1611 if (getLexer().isNot(AsmToken::Comma)) {
1613 if (ParseAbsoluteExpression(FillExpr))
1617 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1618 if (getLexer().isNot(AsmToken::Comma))
1619 return TokError("unexpected token in directive");
1622 MaxBytesLoc = getLexer().getLoc();
1623 if (ParseAbsoluteExpression(MaxBytesToFill))
1626 if (getLexer().isNot(AsmToken::EndOfStatement))
1627 return TokError("unexpected token in directive");
1636 // Compute alignment in bytes.
1638 // FIXME: Diagnose overflow.
1639 if (Alignment >= 32) {
1640 Error(AlignmentLoc, "invalid alignment value");
1644 Alignment = 1ULL << Alignment;
1647 // Diagnose non-sensical max bytes to align.
1648 if (MaxBytesLoc.isValid()) {
1649 if (MaxBytesToFill < 1) {
1650 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1651 "many bytes, ignoring maximum bytes expression");
1655 if (MaxBytesToFill >= Alignment) {
1656 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1662 // Check whether we should use optimal code alignment for this .align
1664 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1665 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1666 ValueSize == 1 && UseCodeAlign) {
1667 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1669 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1670 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1677 /// ParseDirectiveSymbolAttribute
1678 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1679 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1680 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1684 if (ParseIdentifier(Name))
1685 return TokError("expected identifier in directive");
1687 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1689 getStreamer().EmitSymbolAttribute(Sym, Attr);
1691 if (getLexer().is(AsmToken::EndOfStatement))
1694 if (getLexer().isNot(AsmToken::Comma))
1695 return TokError("unexpected token in directive");
1704 /// ParseDirectiveELFType
1705 /// ::= .type identifier , @attribute
1706 bool AsmParser::ParseDirectiveELFType() {
1708 if (ParseIdentifier(Name))
1709 return TokError("expected identifier in directive");
1711 // Handle the identifier as the key symbol.
1712 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1714 if (getLexer().isNot(AsmToken::Comma))
1715 return TokError("unexpected token in '.type' directive");
1718 if (getLexer().isNot(AsmToken::At))
1719 return TokError("expected '@' before type");
1725 TypeLoc = getLexer().getLoc();
1726 if (ParseIdentifier(Type))
1727 return TokError("expected symbol type in directive");
1729 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1730 .Case("function", MCSA_ELF_TypeFunction)
1731 .Case("object", MCSA_ELF_TypeObject)
1732 .Case("tls_object", MCSA_ELF_TypeTLS)
1733 .Case("common", MCSA_ELF_TypeCommon)
1734 .Case("notype", MCSA_ELF_TypeNoType)
1735 .Default(MCSA_Invalid);
1737 if (Attr == MCSA_Invalid)
1738 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1740 if (getLexer().isNot(AsmToken::EndOfStatement))
1741 return TokError("unexpected token in '.type' directive");
1745 getStreamer().EmitSymbolAttribute(Sym, Attr);
1750 /// ParseDirectiveComm
1751 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1752 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1753 CheckForValidSection();
1755 SMLoc IDLoc = getLexer().getLoc();
1757 if (ParseIdentifier(Name))
1758 return TokError("expected identifier in directive");
1760 // Handle the identifier as the key symbol.
1761 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1763 if (getLexer().isNot(AsmToken::Comma))
1764 return TokError("unexpected token in directive");
1768 SMLoc SizeLoc = getLexer().getLoc();
1769 if (ParseAbsoluteExpression(Size))
1772 int64_t Pow2Alignment = 0;
1773 SMLoc Pow2AlignmentLoc;
1774 if (getLexer().is(AsmToken::Comma)) {
1776 Pow2AlignmentLoc = getLexer().getLoc();
1777 if (ParseAbsoluteExpression(Pow2Alignment))
1780 // If this target takes alignments in bytes (not log) validate and convert.
1781 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1782 if (!isPowerOf2_64(Pow2Alignment))
1783 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1784 Pow2Alignment = Log2_64(Pow2Alignment);
1788 if (getLexer().isNot(AsmToken::EndOfStatement))
1789 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1793 // NOTE: a size of zero for a .comm should create a undefined symbol
1794 // but a size of .lcomm creates a bss symbol of size zero.
1796 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1797 "be less than zero");
1799 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1800 // may internally end up wanting an alignment in bytes.
1801 // FIXME: Diagnose overflow.
1802 if (Pow2Alignment < 0)
1803 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1804 "alignment, can't be less than zero");
1806 if (!Sym->isUndefined())
1807 return Error(IDLoc, "invalid symbol redefinition");
1809 // '.lcomm' is equivalent to '.zerofill'.
1810 // Create the Symbol as a common or local common with Size and Pow2Alignment
1812 getStreamer().EmitZerofill(Ctx.getMachOSection(
1813 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1814 0, SectionKind::getBSS()),
1815 Sym, Size, 1 << Pow2Alignment);
1819 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1823 /// ParseDirectiveAbort
1824 /// ::= .abort [... message ...]
1825 bool AsmParser::ParseDirectiveAbort() {
1826 // FIXME: Use loc from directive.
1827 SMLoc Loc = getLexer().getLoc();
1829 StringRef Str = ParseStringToEndOfStatement();
1830 if (getLexer().isNot(AsmToken::EndOfStatement))
1831 return TokError("unexpected token in '.abort' directive");
1836 Error(Loc, ".abort detected. Assembly stopping.");
1838 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1839 // FIXME: Actually abort assembly here.
1844 /// ParseDirectiveInclude
1845 /// ::= .include "filename"
1846 bool AsmParser::ParseDirectiveInclude() {
1847 if (getLexer().isNot(AsmToken::String))
1848 return TokError("expected string in '.include' directive");
1850 std::string Filename = getTok().getString();
1851 SMLoc IncludeLoc = getLexer().getLoc();
1854 if (getLexer().isNot(AsmToken::EndOfStatement))
1855 return TokError("unexpected token in '.include' directive");
1857 // Strip the quotes.
1858 Filename = Filename.substr(1, Filename.size()-2);
1860 // Attempt to switch the lexer to the included file before consuming the end
1861 // of statement to avoid losing it when we switch.
1862 if (EnterIncludeFile(Filename)) {
1863 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1870 /// ParseDirectiveIf
1871 /// ::= .if expression
1872 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1873 TheCondStack.push_back(TheCondState);
1874 TheCondState.TheCond = AsmCond::IfCond;
1875 if(TheCondState.Ignore) {
1876 EatToEndOfStatement();
1880 if (ParseAbsoluteExpression(ExprValue))
1883 if (getLexer().isNot(AsmToken::EndOfStatement))
1884 return TokError("unexpected token in '.if' directive");
1888 TheCondState.CondMet = ExprValue;
1889 TheCondState.Ignore = !TheCondState.CondMet;
1895 /// ParseDirectiveElseIf
1896 /// ::= .elseif expression
1897 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1898 if (TheCondState.TheCond != AsmCond::IfCond &&
1899 TheCondState.TheCond != AsmCond::ElseIfCond)
1900 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1902 TheCondState.TheCond = AsmCond::ElseIfCond;
1904 bool LastIgnoreState = false;
1905 if (!TheCondStack.empty())
1906 LastIgnoreState = TheCondStack.back().Ignore;
1907 if (LastIgnoreState || TheCondState.CondMet) {
1908 TheCondState.Ignore = true;
1909 EatToEndOfStatement();
1913 if (ParseAbsoluteExpression(ExprValue))
1916 if (getLexer().isNot(AsmToken::EndOfStatement))
1917 return TokError("unexpected token in '.elseif' directive");
1920 TheCondState.CondMet = ExprValue;
1921 TheCondState.Ignore = !TheCondState.CondMet;
1927 /// ParseDirectiveElse
1929 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1930 if (getLexer().isNot(AsmToken::EndOfStatement))
1931 return TokError("unexpected token in '.else' directive");
1935 if (TheCondState.TheCond != AsmCond::IfCond &&
1936 TheCondState.TheCond != AsmCond::ElseIfCond)
1937 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1939 TheCondState.TheCond = AsmCond::ElseCond;
1940 bool LastIgnoreState = false;
1941 if (!TheCondStack.empty())
1942 LastIgnoreState = TheCondStack.back().Ignore;
1943 if (LastIgnoreState || TheCondState.CondMet)
1944 TheCondState.Ignore = true;
1946 TheCondState.Ignore = false;
1951 /// ParseDirectiveEndIf
1953 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1954 if (getLexer().isNot(AsmToken::EndOfStatement))
1955 return TokError("unexpected token in '.endif' directive");
1959 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1960 TheCondStack.empty())
1961 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1963 if (!TheCondStack.empty()) {
1964 TheCondState = TheCondStack.back();
1965 TheCondStack.pop_back();
1971 /// ParseDirectiveFile
1972 /// ::= .file [number] string
1973 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1974 // FIXME: I'm not sure what this is.
1975 int64_t FileNumber = -1;
1976 SMLoc FileNumberLoc = getLexer().getLoc();
1977 if (getLexer().is(AsmToken::Integer)) {
1978 FileNumber = getTok().getIntVal();
1982 return TokError("file number less than one");
1985 if (getLexer().isNot(AsmToken::String))
1986 return TokError("unexpected token in '.file' directive");
1988 StringRef Filename = getTok().getString();
1989 Filename = Filename.substr(1, Filename.size()-2);
1992 if (getLexer().isNot(AsmToken::EndOfStatement))
1993 return TokError("unexpected token in '.file' directive");
1995 if (FileNumber == -1)
1996 getStreamer().EmitFileDirective(Filename);
1998 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1999 Error(FileNumberLoc, "file number already allocated");
2000 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
2006 /// ParseDirectiveLine
2007 /// ::= .line [number]
2008 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2009 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2010 if (getLexer().isNot(AsmToken::Integer))
2011 return TokError("unexpected token in '.line' directive");
2013 int64_t LineNumber = getTok().getIntVal();
2017 // FIXME: Do something with the .line.
2020 if (getLexer().isNot(AsmToken::EndOfStatement))
2021 return TokError("unexpected token in '.line' directive");
2027 /// ParseDirectiveLoc
2028 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2029 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2030 /// The first number is a file number, must have been previously assigned with
2031 /// a .file directive, the second number is the line number and optionally the
2032 /// third number is a column position (zero if not specified). The remaining
2033 /// optional items are .loc sub-directives.
2034 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2036 if (getLexer().isNot(AsmToken::Integer))
2037 return TokError("unexpected token in '.loc' directive");
2038 int64_t FileNumber = getTok().getIntVal();
2040 return TokError("file number less than one in '.loc' directive");
2041 if (!getContext().isValidDwarfFileNumber(FileNumber))
2042 return TokError("unassigned file number in '.loc' directive");
2045 int64_t LineNumber = 0;
2046 if (getLexer().is(AsmToken::Integer)) {
2047 LineNumber = getTok().getIntVal();
2049 return TokError("line number less than one in '.loc' directive");
2053 int64_t ColumnPos = 0;
2054 if (getLexer().is(AsmToken::Integer)) {
2055 ColumnPos = getTok().getIntVal();
2057 return TokError("column position less than zero in '.loc' directive");
2061 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2063 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2065 if (getLexer().is(AsmToken::EndOfStatement))
2069 SMLoc Loc = getTok().getLoc();
2070 if (getParser().ParseIdentifier(Name))
2071 return TokError("unexpected token in '.loc' directive");
2073 if (Name == "basic_block")
2074 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2075 else if (Name == "prologue_end")
2076 Flags |= DWARF2_FLAG_PROLOGUE_END;
2077 else if (Name == "epilogue_begin")
2078 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2079 else if (Name == "is_stmt") {
2080 SMLoc Loc = getTok().getLoc();
2081 const MCExpr *Value;
2082 if (getParser().ParseExpression(Value))
2084 // The expression must be the constant 0 or 1.
2085 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2086 int Value = MCE->getValue();
2088 Flags &= ~DWARF2_FLAG_IS_STMT;
2089 else if (Value == 1)
2090 Flags |= DWARF2_FLAG_IS_STMT;
2092 return Error(Loc, "is_stmt value not 0 or 1");
2095 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2098 else if (Name == "isa") {
2099 SMLoc Loc = getTok().getLoc();
2100 const MCExpr *Value;
2101 if (getParser().ParseExpression(Value))
2103 // The expression must be a constant greater or equal to 0.
2104 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2105 int Value = MCE->getValue();
2107 return Error(Loc, "isa number less than zero");
2111 return Error(Loc, "isa number not a constant value");
2115 return Error(Loc, "unknown sub-directive in '.loc' directive");
2118 if (getLexer().is(AsmToken::EndOfStatement))
2123 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
2128 /// ParseDirectiveMacrosOnOff
2131 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2132 SMLoc DirectiveLoc) {
2133 if (getLexer().isNot(AsmToken::EndOfStatement))
2134 return Error(getLexer().getLoc(),
2135 "unexpected token in '" + Directive + "' directive");
2137 getParser().MacrosEnabled = Directive == ".macros_on";
2142 /// ParseDirectiveMacro
2144 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2145 SMLoc DirectiveLoc) {
2147 if (getParser().ParseIdentifier(Name))
2148 return TokError("expected identifier in directive");
2150 if (getLexer().isNot(AsmToken::EndOfStatement))
2151 return TokError("unexpected token in '.macro' directive");
2153 // Eat the end of statement.
2156 AsmToken EndToken, StartToken = getTok();
2158 // Lex the macro definition.
2160 // Check whether we have reached the end of the file.
2161 if (getLexer().is(AsmToken::Eof))
2162 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2164 // Otherwise, check whether we have reach the .endmacro.
2165 if (getLexer().is(AsmToken::Identifier) &&
2166 (getTok().getIdentifier() == ".endm" ||
2167 getTok().getIdentifier() == ".endmacro")) {
2168 EndToken = getTok();
2170 if (getLexer().isNot(AsmToken::EndOfStatement))
2171 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2176 // Otherwise, scan til the end of the statement.
2177 getParser().EatToEndOfStatement();
2180 if (getParser().MacroMap.lookup(Name)) {
2181 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2184 const char *BodyStart = StartToken.getLoc().getPointer();
2185 const char *BodyEnd = EndToken.getLoc().getPointer();
2186 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2187 getParser().MacroMap[Name] = new Macro(Name, Body);
2191 /// ParseDirectiveEndMacro
2194 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2195 SMLoc DirectiveLoc) {
2196 if (getLexer().isNot(AsmToken::EndOfStatement))
2197 return TokError("unexpected token in '" + Directive + "' directive");
2199 // If we are inside a macro instantiation, terminate the current
2201 if (!getParser().ActiveMacros.empty()) {
2202 getParser().HandleMacroExit();
2206 // Otherwise, this .endmacro is a stray entry in the file; well formed
2207 // .endmacro directives are handled during the macro definition parsing.
2208 return TokError("unexpected '" + Directive + "' in file, "
2209 "no current macro definition");
2212 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2213 const uint64_t Mask = (1 << 7) - 1;
2215 unsigned Byte = Value & Mask;
2217 if (Value) // Not the last one
2219 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2223 void GenericAsmParser::ParseSleb128(int64_t Value) {
2224 const int64_t Mask = (1 << 7) - 1;
2226 unsigned Byte = Value & Mask;
2228 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2229 (Value == -1 && (Byte & 0x40) != 0));
2232 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2238 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2240 if (getParser().ParseAbsoluteExpression(Value))
2243 if (getLexer().isNot(AsmToken::EndOfStatement))
2244 return TokError("unexpected token in directive");
2246 if (DirName[1] == 's')
2247 ParseSleb128(Value);
2249 ParseUleb128(Value);
2254 /// \brief Create an MCAsmParser instance.
2255 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2256 MCContext &C, MCStreamer &Out,
2257 const MCAsmInfo &MAI) {
2258 return new AsmParser(T, SM, C, Out, MAI);