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/MCInst.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetAsmParser.h"
41 /// \brief Helper class for tracking macro definitions.
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
50 /// \brief Helper class for storing information about an active macro
52 struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
62 /// The location where parsing should resume upon instantiation completion.
66 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72 friend class GenericAsmParser;
74 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
84 /// This is the current buffer index we're lexing from as managed by the
89 std::vector<AsmCond> TheCondStack;
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
97 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
123 /// @name MCAsmParser Interface
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
134 const AsmToken &Lex();
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
144 void CheckForValidSection();
146 bool ParseStatement();
148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
151 void PrintMacroInstantiations();
152 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
153 SrcMgr.PrintMessage(Loc, Msg, Type);
156 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
157 bool EnterIncludeFile(const std::string &Filename);
159 /// \brief Reset the current lexer position to that given by \arg Loc. The
160 /// current token is not set; clients should ensure Lex() is called
162 void JumpToLoc(SMLoc Loc);
164 void EatToEndOfStatement();
166 /// \brief Parse up to the end of statement and a return the contents from the
167 /// current token until the end of the statement; the current token on exit
168 /// will be either the EndOfStatement or EOF.
169 StringRef ParseStringToEndOfStatement();
171 bool ParseAssignment(StringRef Name);
173 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
175 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
177 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
178 /// and set \arg Res to the identifier contents.
179 bool ParseIdentifier(StringRef &Res);
181 // Directive Parsing.
182 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
183 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
184 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
185 bool ParseDirectiveFill(); // ".fill"
186 bool ParseDirectiveSpace(); // ".space"
187 bool ParseDirectiveZero(); // ".zero"
188 bool ParseDirectiveSet(); // ".set"
189 bool ParseDirectiveOrg(); // ".org"
190 // ".align{,32}", ".p2align{,w,l}"
191 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
193 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
194 /// accepts a single symbol (which should be a label or an external).
195 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
196 bool ParseDirectiveELFType(); // ELF specific ".type"
198 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
200 bool ParseDirectiveAbort(); // ".abort"
201 bool ParseDirectiveInclude(); // ".include"
203 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
204 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
205 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
206 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
208 /// ParseEscapedString - Parse the current token as a string which may include
209 /// escaped characters and return the string contents.
210 bool ParseEscapedString(std::string &Data);
212 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
213 MCSymbolRefExpr::VariantKind Variant);
216 /// \brief Generic implementations of directive handling, etc. which is shared
217 /// (or the default, at least) for all assembler parser.
218 class GenericAsmParser : public MCAsmParserExtension {
219 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
220 void AddDirectiveHandler(StringRef Directive) {
221 getParser().AddDirectiveHandler(this, Directive,
222 HandleDirective<GenericAsmParser, Handler>);
226 GenericAsmParser() {}
228 AsmParser &getParser() {
229 return (AsmParser&) this->MCAsmParserExtension::getParser();
232 virtual void Initialize(MCAsmParser &Parser) {
233 // Call the base implementation.
234 this->MCAsmParserExtension::Initialize(Parser);
236 // Debugging directives.
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
254 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
255 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
256 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
258 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
259 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
260 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
262 void ParseUleb128(uint64_t Value);
263 void ParseSleb128(int64_t Value);
264 bool ParseDirectiveLEB128(StringRef, SMLoc);
271 extern MCAsmParserExtension *createDarwinAsmParser();
272 extern MCAsmParserExtension *createELFAsmParser();
276 enum { DEFAULT_ADDRSPACE = 0 };
278 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
279 MCStreamer &_Out, const MCAsmInfo &_MAI)
280 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
281 GenericParser(new GenericAsmParser), PlatformParser(0),
282 CurBuffer(0), MacrosEnabled(true) {
283 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
285 // Initialize the generic parser.
286 GenericParser->Initialize(*this);
288 // Initialize the platform / file format parser.
290 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
292 if (_MAI.hasSubsectionsViaSymbols()) {
293 PlatformParser = createDarwinAsmParser();
294 PlatformParser->Initialize(*this);
296 PlatformParser = createELFAsmParser();
297 PlatformParser->Initialize(*this);
301 AsmParser::~AsmParser() {
302 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
304 // Destroy any macros.
305 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
306 ie = MacroMap.end(); it != ie; ++it)
307 delete it->getValue();
309 delete PlatformParser;
310 delete GenericParser;
313 void AsmParser::PrintMacroInstantiations() {
314 // Print the active macro instantiation stack.
315 for (std::vector<MacroInstantiation*>::const_reverse_iterator
316 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
317 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
321 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
322 PrintMessage(L, Msg, "warning");
323 PrintMacroInstantiations();
326 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
328 PrintMessage(L, Msg, "error");
329 PrintMacroInstantiations();
333 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
334 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
340 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
345 void AsmParser::JumpToLoc(SMLoc Loc) {
346 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
347 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
350 const AsmToken &AsmParser::Lex() {
351 const AsmToken *tok = &Lexer.Lex();
353 if (tok->is(AsmToken::Eof)) {
354 // If this is the end of an included file, pop the parent file off the
356 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
357 if (ParentIncludeLoc != SMLoc()) {
358 JumpToLoc(ParentIncludeLoc);
363 if (tok->is(AsmToken::Error))
364 Error(Lexer.getErrLoc(), Lexer.getErr());
369 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
370 // Create the initial section, if requested.
371 if (!NoInitialTextSection)
378 AsmCond StartingCondState = TheCondState;
380 // While we have input, parse each statement.
381 while (Lexer.isNot(AsmToken::Eof)) {
382 if (!ParseStatement()) continue;
384 // We had an error, validate that one was emitted and recover by skipping to
386 assert(HadError && "Parse statement returned an error, but none emitted!");
387 EatToEndOfStatement();
390 if (TheCondState.TheCond != StartingCondState.TheCond ||
391 TheCondState.Ignore != StartingCondState.Ignore)
392 return TokError("unmatched .ifs or .elses");
394 // Check to see there are no empty DwarfFile slots.
395 const std::vector<MCDwarfFile *> &MCDwarfFiles =
396 getContext().getMCDwarfFiles();
397 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
398 if (!MCDwarfFiles[i])
399 TokError("unassigned file number: " + Twine(i) + " for .file directives");
402 // Finalize the output stream if there are no errors and if the client wants
404 if (!HadError && !NoFinalize)
410 void AsmParser::CheckForValidSection() {
411 if (!getStreamer().getCurrentSection()) {
412 TokError("expected section directive before assembly directive");
413 Out.SwitchSection(Ctx.getMachOSection(
415 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
416 0, SectionKind::getText()));
420 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
421 void AsmParser::EatToEndOfStatement() {
422 while (Lexer.isNot(AsmToken::EndOfStatement) &&
423 Lexer.isNot(AsmToken::Eof))
427 if (Lexer.is(AsmToken::EndOfStatement))
431 StringRef AsmParser::ParseStringToEndOfStatement() {
432 const char *Start = getTok().getLoc().getPointer();
434 while (Lexer.isNot(AsmToken::EndOfStatement) &&
435 Lexer.isNot(AsmToken::Eof))
438 const char *End = getTok().getLoc().getPointer();
439 return StringRef(Start, End - Start);
442 /// ParseParenExpr - Parse a paren expression and return it.
443 /// NOTE: This assumes the leading '(' has already been consumed.
445 /// parenexpr ::= expr)
447 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
448 if (ParseExpression(Res)) return true;
449 if (Lexer.isNot(AsmToken::RParen))
450 return TokError("expected ')' in parentheses expression");
451 EndLoc = Lexer.getLoc();
456 /// ParsePrimaryExpr - Parse a primary expression and return it.
457 /// primaryexpr ::= (parenexpr
458 /// primaryexpr ::= symbol
459 /// primaryexpr ::= number
460 /// primaryexpr ::= '.'
461 /// primaryexpr ::= ~,+,- primaryexpr
462 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
463 switch (Lexer.getKind()) {
465 return TokError("unknown token in expression");
466 case AsmToken::Exclaim:
467 Lex(); // Eat the operator.
468 if (ParsePrimaryExpr(Res, EndLoc))
470 Res = MCUnaryExpr::CreateLNot(Res, getContext());
472 case AsmToken::Dollar:
473 case AsmToken::String:
474 case AsmToken::Identifier: {
475 EndLoc = Lexer.getLoc();
477 StringRef Identifier;
478 if (ParseIdentifier(Identifier))
481 // This is a symbol reference.
482 std::pair<StringRef, StringRef> Split = Identifier.split('@');
483 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
485 // Mark the symbol as used in an expression.
486 Sym->setUsedInExpr(true);
488 // Lookup the symbol variant if used.
489 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
490 if (Split.first.size() != Identifier.size()) {
491 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
492 if (Variant == MCSymbolRefExpr::VK_Invalid) {
493 Variant = MCSymbolRefExpr::VK_None;
494 TokError("invalid variant '" + Split.second + "'");
498 // If this is an absolute variable reference, substitute it now to preserve
499 // semantics in the face of reassignment.
500 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
502 return Error(EndLoc, "unexpected modified on variable reference");
504 Res = Sym->getVariableValue();
508 // Otherwise create a symbol ref.
509 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
512 case AsmToken::Integer: {
513 SMLoc Loc = getTok().getLoc();
514 int64_t IntVal = getTok().getIntVal();
515 Res = MCConstantExpr::Create(IntVal, getContext());
516 EndLoc = Lexer.getLoc();
518 // Look for 'b' or 'f' following an Integer as a directional label
519 if (Lexer.getKind() == AsmToken::Identifier) {
520 StringRef IDVal = getTok().getString();
521 if (IDVal == "f" || IDVal == "b"){
522 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
523 IDVal == "f" ? 1 : 0);
524 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
526 if(IDVal == "b" && Sym->isUndefined())
527 return Error(Loc, "invalid reference to undefined symbol");
528 EndLoc = Lexer.getLoc();
529 Lex(); // Eat identifier.
534 case AsmToken::Dot: {
535 // This is a '.' reference, which references the current PC. Emit a
536 // temporary label to the streamer and refer to it.
537 MCSymbol *Sym = Ctx.CreateTempSymbol();
539 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
540 EndLoc = Lexer.getLoc();
541 Lex(); // Eat identifier.
545 case AsmToken::LParen:
546 Lex(); // Eat the '('.
547 return ParseParenExpr(Res, EndLoc);
548 case AsmToken::Minus:
549 Lex(); // Eat the operator.
550 if (ParsePrimaryExpr(Res, EndLoc))
552 Res = MCUnaryExpr::CreateMinus(Res, getContext());
555 Lex(); // Eat the operator.
556 if (ParsePrimaryExpr(Res, EndLoc))
558 Res = MCUnaryExpr::CreatePlus(Res, getContext());
560 case AsmToken::Tilde:
561 Lex(); // Eat the operator.
562 if (ParsePrimaryExpr(Res, EndLoc))
564 Res = MCUnaryExpr::CreateNot(Res, getContext());
569 bool AsmParser::ParseExpression(const MCExpr *&Res) {
571 return ParseExpression(Res, EndLoc);
575 AsmParser::ApplyModifierToExpr(const MCExpr *E,
576 MCSymbolRefExpr::VariantKind Variant) {
577 // Recurse over the given expression, rebuilding it to apply the given variant
578 // if there is exactly one symbol.
579 switch (E->getKind()) {
581 case MCExpr::Constant:
584 case MCExpr::SymbolRef: {
585 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
587 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
588 TokError("invalid variant on expression '" +
589 getTok().getIdentifier() + "' (already modified)");
593 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
596 case MCExpr::Unary: {
597 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
598 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
601 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
604 case MCExpr::Binary: {
605 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
606 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
607 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
612 if (!LHS) LHS = BE->getLHS();
613 if (!RHS) RHS = BE->getRHS();
615 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
619 assert(0 && "Invalid expression kind!");
623 /// ParseExpression - Parse an expression and return it.
625 /// expr ::= expr +,- expr -> lowest.
626 /// expr ::= expr |,^,&,! expr -> middle.
627 /// expr ::= expr *,/,%,<<,>> expr -> highest.
628 /// expr ::= primaryexpr
630 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
631 // Parse the expression.
633 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
636 // As a special case, we support 'a op b @ modifier' by rewriting the
637 // expression to include the modifier. This is inefficient, but in general we
638 // expect users to use 'a@modifier op b'.
639 if (Lexer.getKind() == AsmToken::At) {
642 if (Lexer.isNot(AsmToken::Identifier))
643 return TokError("unexpected symbol modifier following '@'");
645 MCSymbolRefExpr::VariantKind Variant =
646 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
647 if (Variant == MCSymbolRefExpr::VK_Invalid)
648 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
650 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
652 return TokError("invalid modifier '" + getTok().getIdentifier() +
653 "' (no symbols present)");
661 // Try to constant fold it up front, if possible.
663 if (Res->EvaluateAsAbsolute(Value))
664 Res = MCConstantExpr::Create(Value, getContext());
669 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
671 return ParseParenExpr(Res, EndLoc) ||
672 ParseBinOpRHS(1, Res, EndLoc);
675 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
678 SMLoc StartLoc = Lexer.getLoc();
679 if (ParseExpression(Expr))
682 if (!Expr->EvaluateAsAbsolute(Res))
683 return Error(StartLoc, "expected absolute expression");
688 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
689 MCBinaryExpr::Opcode &Kind) {
692 return 0; // not a binop.
694 // Lowest Precedence: &&, ||, @
695 case AsmToken::AmpAmp:
696 Kind = MCBinaryExpr::LAnd;
698 case AsmToken::PipePipe:
699 Kind = MCBinaryExpr::LOr;
703 // Low Precedence: |, &, ^
705 // FIXME: gas seems to support '!' as an infix operator?
707 Kind = MCBinaryExpr::Or;
709 case AsmToken::Caret:
710 Kind = MCBinaryExpr::Xor;
713 Kind = MCBinaryExpr::And;
716 // Intermediate Precedence: +, -, ==, !=, <>, <, <=, >, >=
718 Kind = MCBinaryExpr::Add;
720 case AsmToken::Minus:
721 Kind = MCBinaryExpr::Sub;
723 case AsmToken::EqualEqual:
724 Kind = MCBinaryExpr::EQ;
726 case AsmToken::ExclaimEqual:
727 case AsmToken::LessGreater:
728 Kind = MCBinaryExpr::NE;
731 Kind = MCBinaryExpr::LT;
733 case AsmToken::LessEqual:
734 Kind = MCBinaryExpr::LTE;
736 case AsmToken::Greater:
737 Kind = MCBinaryExpr::GT;
739 case AsmToken::GreaterEqual:
740 Kind = MCBinaryExpr::GTE;
743 // Highest Precedence: *, /, %, <<, >>
745 Kind = MCBinaryExpr::Mul;
747 case AsmToken::Slash:
748 Kind = MCBinaryExpr::Div;
750 case AsmToken::Percent:
751 Kind = MCBinaryExpr::Mod;
753 case AsmToken::LessLess:
754 Kind = MCBinaryExpr::Shl;
756 case AsmToken::GreaterGreater:
757 Kind = MCBinaryExpr::Shr;
763 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
764 /// Res contains the LHS of the expression on input.
765 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
768 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
769 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
771 // If the next token is lower precedence than we are allowed to eat, return
772 // successfully with what we ate already.
773 if (TokPrec < Precedence)
778 // Eat the next primary expression.
780 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
782 // If BinOp binds less tightly with RHS than the operator after RHS, let
783 // the pending operator take RHS as its LHS.
784 MCBinaryExpr::Opcode Dummy;
785 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
786 if (TokPrec < NextTokPrec) {
787 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
790 // Merge LHS and RHS according to operator.
791 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
799 /// ::= EndOfStatement
800 /// ::= Label* Directive ...Operands... EndOfStatement
801 /// ::= Label* Identifier OperandList* EndOfStatement
802 bool AsmParser::ParseStatement() {
803 if (Lexer.is(AsmToken::EndOfStatement)) {
809 // Statements always start with an identifier.
810 AsmToken ID = getTok();
811 SMLoc IDLoc = ID.getLoc();
813 int64_t LocalLabelVal = -1;
814 // GUESS allow an integer followed by a ':' as a directional local label
815 if (Lexer.is(AsmToken::Integer)) {
816 LocalLabelVal = getTok().getIntVal();
817 if (LocalLabelVal < 0) {
818 if (!TheCondState.Ignore)
819 return TokError("unexpected token at start of statement");
823 IDVal = getTok().getString();
824 Lex(); // Consume the integer token to be used as an identifier token.
825 if (Lexer.getKind() != AsmToken::Colon) {
826 if (!TheCondState.Ignore)
827 return TokError("unexpected token at start of statement");
831 else if (ParseIdentifier(IDVal)) {
832 if (!TheCondState.Ignore)
833 return TokError("unexpected token at start of statement");
837 // Handle conditional assembly here before checking for skipping. We
838 // have to do this so that .endif isn't skipped in a ".if 0" block for
841 return ParseDirectiveIf(IDLoc);
842 if (IDVal == ".elseif")
843 return ParseDirectiveElseIf(IDLoc);
844 if (IDVal == ".else")
845 return ParseDirectiveElse(IDLoc);
846 if (IDVal == ".endif")
847 return ParseDirectiveEndIf(IDLoc);
849 // If we are in a ".if 0" block, ignore this statement.
850 if (TheCondState.Ignore) {
851 EatToEndOfStatement();
855 // FIXME: Recurse on local labels?
857 // See what kind of statement we have.
858 switch (Lexer.getKind()) {
859 case AsmToken::Colon: {
860 CheckForValidSection();
862 // identifier ':' -> Label.
865 // Diagnose attempt to use a variable as a label.
867 // FIXME: Diagnostics. Note the location of the definition as a label.
868 // FIXME: This doesn't diagnose assignment to a symbol which has been
869 // implicitly marked as external.
871 if (LocalLabelVal == -1)
872 Sym = getContext().GetOrCreateSymbol(IDVal);
874 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
875 if (!Sym->isUndefined() || Sym->isVariable())
876 return Error(IDLoc, "invalid symbol redefinition");
881 // Consume any end of statement token, if present, to avoid spurious
882 // AddBlankLine calls().
883 if (Lexer.is(AsmToken::EndOfStatement)) {
885 if (Lexer.is(AsmToken::Eof))
889 return ParseStatement();
892 case AsmToken::Equal:
893 // identifier '=' ... -> assignment statement
896 return ParseAssignment(IDVal);
898 default: // Normal instruction or directive.
902 // If macros are enabled, check to see if this is a macro instantiation.
904 if (const Macro *M = MacroMap.lookup(IDVal))
905 return HandleMacroEntry(IDVal, IDLoc, M);
907 // Otherwise, we have a normal instruction or directive.
908 if (IDVal[0] == '.') {
909 // Assembler features
911 return ParseDirectiveSet();
915 if (IDVal == ".ascii")
916 return ParseDirectiveAscii(false);
917 if (IDVal == ".asciz")
918 return ParseDirectiveAscii(true);
920 if (IDVal == ".byte")
921 return ParseDirectiveValue(1);
922 if (IDVal == ".short")
923 return ParseDirectiveValue(2);
924 if (IDVal == ".long")
925 return ParseDirectiveValue(4);
926 if (IDVal == ".quad")
927 return ParseDirectiveValue(8);
928 if (IDVal == ".single")
929 return ParseDirectiveRealValue(APFloat::IEEEsingle);
930 if (IDVal == ".double")
931 return ParseDirectiveRealValue(APFloat::IEEEdouble);
933 if (IDVal == ".align") {
934 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
935 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
937 if (IDVal == ".align32") {
938 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
939 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
941 if (IDVal == ".balign")
942 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
943 if (IDVal == ".balignw")
944 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
945 if (IDVal == ".balignl")
946 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
947 if (IDVal == ".p2align")
948 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
949 if (IDVal == ".p2alignw")
950 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
951 if (IDVal == ".p2alignl")
952 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
955 return ParseDirectiveOrg();
957 if (IDVal == ".fill")
958 return ParseDirectiveFill();
959 if (IDVal == ".space")
960 return ParseDirectiveSpace();
961 if (IDVal == ".zero")
962 return ParseDirectiveZero();
964 // Symbol attribute directives
966 if (IDVal == ".globl" || IDVal == ".global")
967 return ParseDirectiveSymbolAttribute(MCSA_Global);
968 // ELF only? Should it be here?
969 if (IDVal == ".local")
970 return ParseDirectiveSymbolAttribute(MCSA_Local);
971 if (IDVal == ".hidden")
972 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
973 if (IDVal == ".indirect_symbol")
974 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
975 if (IDVal == ".internal")
976 return ParseDirectiveSymbolAttribute(MCSA_Internal);
977 if (IDVal == ".lazy_reference")
978 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
979 if (IDVal == ".no_dead_strip")
980 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
981 if (IDVal == ".private_extern")
982 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
983 if (IDVal == ".protected")
984 return ParseDirectiveSymbolAttribute(MCSA_Protected);
985 if (IDVal == ".reference")
986 return ParseDirectiveSymbolAttribute(MCSA_Reference);
987 if (IDVal == ".type")
988 return ParseDirectiveELFType();
989 if (IDVal == ".weak")
990 return ParseDirectiveSymbolAttribute(MCSA_Weak);
991 if (IDVal == ".weak_definition")
992 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
993 if (IDVal == ".weak_reference")
994 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
995 if (IDVal == ".weak_def_can_be_hidden")
996 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
998 if (IDVal == ".comm")
999 return ParseDirectiveComm(/*IsLocal=*/false);
1000 if (IDVal == ".lcomm")
1001 return ParseDirectiveComm(/*IsLocal=*/true);
1003 if (IDVal == ".abort")
1004 return ParseDirectiveAbort();
1005 if (IDVal == ".include")
1006 return ParseDirectiveInclude();
1008 // Look up the handler in the handler table.
1009 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1010 DirectiveMap.lookup(IDVal);
1012 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1014 // Target hook for parsing target specific directives.
1015 if (!getTargetParser().ParseDirective(ID))
1018 Warning(IDLoc, "ignoring directive for now");
1019 EatToEndOfStatement();
1023 CheckForValidSection();
1025 // Canonicalize the opcode to lower case.
1026 SmallString<128> Opcode;
1027 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1028 Opcode.push_back(tolower(IDVal[i]));
1030 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1031 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1034 // Dump the parsed representation, if requested.
1035 if (getShowParsedOperands()) {
1036 SmallString<256> Str;
1037 raw_svector_ostream OS(Str);
1038 OS << "parsed instruction: [";
1039 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1042 ParsedOperands[i]->dump(OS);
1046 PrintMessage(IDLoc, OS.str(), "note");
1049 // If parsing succeeded, match the instruction.
1052 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
1053 // Emit the instruction on success.
1054 Out.EmitInstruction(Inst);
1059 // Free any parsed operands.
1060 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1061 delete ParsedOperands[i];
1063 // Don't skip the rest of the line, the instruction parser is responsible for
1068 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1069 const std::vector<std::vector<AsmToken> > &A)
1070 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1072 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1073 // to hold the macro body with substitutions.
1074 SmallString<256> Buf;
1075 raw_svector_ostream OS(Buf);
1077 StringRef Body = M->Body;
1078 while (!Body.empty()) {
1079 // Scan for the next substitution.
1080 std::size_t End = Body.size(), Pos = 0;
1081 for (; Pos != End; ++Pos) {
1082 // Check for a substitution or escape.
1083 if (Body[Pos] != '$' || Pos + 1 == End)
1086 char Next = Body[Pos + 1];
1087 if (Next == '$' || Next == 'n' || isdigit(Next))
1092 OS << Body.slice(0, Pos);
1094 // Check if we reached the end.
1098 switch (Body[Pos+1]) {
1104 // $n => number of arguments
1109 // $[0-9] => argument
1111 // Missing arguments are ignored.
1112 unsigned Index = Body[Pos+1] - '0';
1113 if (Index >= A.size())
1116 // Otherwise substitute with the token values, with spaces eliminated.
1117 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1118 ie = A[Index].end(); it != ie; ++it)
1119 OS << it->getString();
1124 // Update the scan point.
1125 Body = Body.substr(Pos + 2);
1128 // We include the .endmacro in the buffer as our queue to exit the macro
1130 OS << ".endmacro\n";
1132 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1135 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1137 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1138 // this, although we should protect against infinite loops.
1139 if (ActiveMacros.size() == 20)
1140 return TokError("macros cannot be nested more than 20 levels deep");
1142 // Parse the macro instantiation arguments.
1143 std::vector<std::vector<AsmToken> > MacroArguments;
1144 MacroArguments.push_back(std::vector<AsmToken>());
1145 unsigned ParenLevel = 0;
1147 if (Lexer.is(AsmToken::Eof))
1148 return TokError("unexpected token in macro instantiation");
1149 if (Lexer.is(AsmToken::EndOfStatement))
1152 // If we aren't inside parentheses and this is a comma, start a new token
1154 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1155 MacroArguments.push_back(std::vector<AsmToken>());
1157 // Adjust the current parentheses level.
1158 if (Lexer.is(AsmToken::LParen))
1160 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1163 // Append the token to the current argument list.
1164 MacroArguments.back().push_back(getTok());
1169 // Create the macro instantiation object and add to the current macro
1170 // instantiation stack.
1171 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1174 ActiveMacros.push_back(MI);
1176 // Jump to the macro instantiation and prime the lexer.
1177 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1178 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1184 void AsmParser::HandleMacroExit() {
1185 // Jump to the EndOfStatement we should return to, and consume it.
1186 JumpToLoc(ActiveMacros.back()->ExitLoc);
1189 // Pop the instantiation entry.
1190 delete ActiveMacros.back();
1191 ActiveMacros.pop_back();
1194 bool AsmParser::ParseAssignment(StringRef Name) {
1195 // FIXME: Use better location, we should use proper tokens.
1196 SMLoc EqualLoc = Lexer.getLoc();
1198 const MCExpr *Value;
1199 if (ParseExpression(Value))
1202 if (Lexer.isNot(AsmToken::EndOfStatement))
1203 return TokError("unexpected token in assignment");
1205 // Eat the end of statement marker.
1208 // Validate that the LHS is allowed to be a variable (either it has not been
1209 // used as a symbol, or it is an absolute symbol).
1210 MCSymbol *Sym = getContext().LookupSymbol(Name);
1212 // Diagnose assignment to a label.
1214 // FIXME: Diagnostics. Note the location of the definition as a label.
1215 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1216 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1217 ; // Allow redefinitions of undefined symbols only used in directives.
1218 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1219 return Error(EqualLoc, "redefinition of '" + Name + "'");
1220 else if (!Sym->isVariable())
1221 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1222 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1223 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1226 Sym = getContext().GetOrCreateSymbol(Name);
1228 // FIXME: Handle '.'.
1230 Sym->setUsedInExpr(true);
1232 // Do the assignment.
1233 Out.EmitAssignment(Sym, Value);
1238 /// ParseIdentifier:
1241 bool AsmParser::ParseIdentifier(StringRef &Res) {
1242 // The assembler has relaxed rules for accepting identifiers, in particular we
1243 // allow things like '.globl $foo', which would normally be separate
1244 // tokens. At this level, we have already lexed so we cannot (currently)
1245 // handle this as a context dependent token, instead we detect adjacent tokens
1246 // and return the combined identifier.
1247 if (Lexer.is(AsmToken::Dollar)) {
1248 SMLoc DollarLoc = getLexer().getLoc();
1250 // Consume the dollar sign, and check for a following identifier.
1252 if (Lexer.isNot(AsmToken::Identifier))
1255 // We have a '$' followed by an identifier, make sure they are adjacent.
1256 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1259 // Construct the joined identifier and consume the token.
1260 Res = StringRef(DollarLoc.getPointer(),
1261 getTok().getIdentifier().size() + 1);
1266 if (Lexer.isNot(AsmToken::Identifier) &&
1267 Lexer.isNot(AsmToken::String))
1270 Res = getTok().getIdentifier();
1272 Lex(); // Consume the identifier token.
1277 /// ParseDirectiveSet:
1278 /// ::= .set identifier ',' expression
1279 bool AsmParser::ParseDirectiveSet() {
1282 if (ParseIdentifier(Name))
1283 return TokError("expected identifier after '.set' directive");
1285 if (getLexer().isNot(AsmToken::Comma))
1286 return TokError("unexpected token in '.set'");
1289 return ParseAssignment(Name);
1292 bool AsmParser::ParseEscapedString(std::string &Data) {
1293 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1296 StringRef Str = getTok().getStringContents();
1297 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1298 if (Str[i] != '\\') {
1303 // Recognize escaped characters. Note that this escape semantics currently
1304 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1307 return TokError("unexpected backslash at end of string");
1309 // Recognize octal sequences.
1310 if ((unsigned) (Str[i] - '0') <= 7) {
1311 // Consume up to three octal characters.
1312 unsigned Value = Str[i] - '0';
1314 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1316 Value = Value * 8 + (Str[i] - '0');
1318 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1320 Value = Value * 8 + (Str[i] - '0');
1325 return TokError("invalid octal escape sequence (out of range)");
1327 Data += (unsigned char) Value;
1331 // Otherwise recognize individual escapes.
1334 // Just reject invalid escape sequences for now.
1335 return TokError("invalid escape sequence (unrecognized character)");
1337 case 'b': Data += '\b'; break;
1338 case 'f': Data += '\f'; break;
1339 case 'n': Data += '\n'; break;
1340 case 'r': Data += '\r'; break;
1341 case 't': Data += '\t'; break;
1342 case '"': Data += '"'; break;
1343 case '\\': Data += '\\'; break;
1350 /// ParseDirectiveAscii:
1351 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1352 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1354 CheckForValidSection();
1357 if (getLexer().isNot(AsmToken::String))
1358 return TokError("expected string in '.ascii' or '.asciz' directive");
1361 if (ParseEscapedString(Data))
1364 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1366 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1370 if (getLexer().is(AsmToken::EndOfStatement))
1373 if (getLexer().isNot(AsmToken::Comma))
1374 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1383 /// ParseDirectiveValue
1384 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1385 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1387 CheckForValidSection();
1390 const MCExpr *Value;
1391 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1392 if (ParseExpression(Value))
1395 // Special case constant expressions to match code generator.
1396 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1397 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1399 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1401 if (getLexer().is(AsmToken::EndOfStatement))
1404 // FIXME: Improve diagnostic.
1405 if (getLexer().isNot(AsmToken::Comma))
1406 return TokError("unexpected token in directive");
1415 /// ParseDirectiveRealValue
1416 /// ::= (.single | .double) [ expression (, expression)* ]
1417 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1418 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1419 CheckForValidSection();
1422 // We don't truly support arithmetic on floating point expressions, so we
1423 // have to manually parse unary prefixes.
1425 if (getLexer().is(AsmToken::Minus)) {
1428 } else if (getLexer().is(AsmToken::Plus))
1431 if (getLexer().isNot(AsmToken::Integer) &&
1432 getLexer().isNot(AsmToken::Real))
1433 return TokError("unexpected token in directive");
1435 // Convert to an APFloat.
1436 APFloat Value(Semantics);
1437 if (Value.convertFromString(getTok().getString(),
1438 APFloat::rmNearestTiesToEven) ==
1439 APFloat::opInvalidOp)
1440 return TokError("invalid floating point literal");
1444 // Consume the numeric token.
1447 // Emit the value as an integer.
1448 APInt AsInt = Value.bitcastToAPInt();
1449 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1450 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1452 if (getLexer().is(AsmToken::EndOfStatement))
1455 if (getLexer().isNot(AsmToken::Comma))
1456 return TokError("unexpected token in directive");
1465 /// ParseDirectiveSpace
1466 /// ::= .space expression [ , expression ]
1467 bool AsmParser::ParseDirectiveSpace() {
1468 CheckForValidSection();
1471 if (ParseAbsoluteExpression(NumBytes))
1474 int64_t FillExpr = 0;
1475 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1476 if (getLexer().isNot(AsmToken::Comma))
1477 return TokError("unexpected token in '.space' directive");
1480 if (ParseAbsoluteExpression(FillExpr))
1483 if (getLexer().isNot(AsmToken::EndOfStatement))
1484 return TokError("unexpected token in '.space' directive");
1490 return TokError("invalid number of bytes in '.space' directive");
1492 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1493 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1498 /// ParseDirectiveZero
1499 /// ::= .zero expression
1500 bool AsmParser::ParseDirectiveZero() {
1501 CheckForValidSection();
1504 if (ParseAbsoluteExpression(NumBytes))
1507 if (getLexer().isNot(AsmToken::EndOfStatement))
1508 return TokError("unexpected token in '.zero' directive");
1512 getStreamer().EmitFill(NumBytes, 0, DEFAULT_ADDRSPACE);
1517 /// ParseDirectiveFill
1518 /// ::= .fill expression , expression , expression
1519 bool AsmParser::ParseDirectiveFill() {
1520 CheckForValidSection();
1523 if (ParseAbsoluteExpression(NumValues))
1526 if (getLexer().isNot(AsmToken::Comma))
1527 return TokError("unexpected token in '.fill' directive");
1531 if (ParseAbsoluteExpression(FillSize))
1534 if (getLexer().isNot(AsmToken::Comma))
1535 return TokError("unexpected token in '.fill' directive");
1539 if (ParseAbsoluteExpression(FillExpr))
1542 if (getLexer().isNot(AsmToken::EndOfStatement))
1543 return TokError("unexpected token in '.fill' directive");
1547 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1548 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1550 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1551 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1556 /// ParseDirectiveOrg
1557 /// ::= .org expression [ , expression ]
1558 bool AsmParser::ParseDirectiveOrg() {
1559 CheckForValidSection();
1561 const MCExpr *Offset;
1562 if (ParseExpression(Offset))
1565 // Parse optional fill expression.
1566 int64_t FillExpr = 0;
1567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1568 if (getLexer().isNot(AsmToken::Comma))
1569 return TokError("unexpected token in '.org' directive");
1572 if (ParseAbsoluteExpression(FillExpr))
1575 if (getLexer().isNot(AsmToken::EndOfStatement))
1576 return TokError("unexpected token in '.org' directive");
1581 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1582 // has to be relative to the current section.
1583 getStreamer().EmitValueToOffset(Offset, FillExpr);
1588 /// ParseDirectiveAlign
1589 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1590 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1591 CheckForValidSection();
1593 SMLoc AlignmentLoc = getLexer().getLoc();
1595 if (ParseAbsoluteExpression(Alignment))
1599 bool HasFillExpr = false;
1600 int64_t FillExpr = 0;
1601 int64_t MaxBytesToFill = 0;
1602 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1603 if (getLexer().isNot(AsmToken::Comma))
1604 return TokError("unexpected token in directive");
1607 // The fill expression can be omitted while specifying a maximum number of
1608 // alignment bytes, e.g:
1610 if (getLexer().isNot(AsmToken::Comma)) {
1612 if (ParseAbsoluteExpression(FillExpr))
1616 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1617 if (getLexer().isNot(AsmToken::Comma))
1618 return TokError("unexpected token in directive");
1621 MaxBytesLoc = getLexer().getLoc();
1622 if (ParseAbsoluteExpression(MaxBytesToFill))
1625 if (getLexer().isNot(AsmToken::EndOfStatement))
1626 return TokError("unexpected token in directive");
1635 // Compute alignment in bytes.
1637 // FIXME: Diagnose overflow.
1638 if (Alignment >= 32) {
1639 Error(AlignmentLoc, "invalid alignment value");
1643 Alignment = 1ULL << Alignment;
1646 // Diagnose non-sensical max bytes to align.
1647 if (MaxBytesLoc.isValid()) {
1648 if (MaxBytesToFill < 1) {
1649 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1650 "many bytes, ignoring maximum bytes expression");
1654 if (MaxBytesToFill >= Alignment) {
1655 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1661 // Check whether we should use optimal code alignment for this .align
1664 // FIXME: This should be using a target hook.
1665 bool UseCodeAlign = false;
1666 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1667 getStreamer().getCurrentSection()))
1668 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1669 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1670 ValueSize == 1 && UseCodeAlign) {
1671 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1673 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1674 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1681 /// ParseDirectiveSymbolAttribute
1682 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1683 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1684 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1688 if (ParseIdentifier(Name))
1689 return TokError("expected identifier in directive");
1691 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1693 getStreamer().EmitSymbolAttribute(Sym, Attr);
1695 if (getLexer().is(AsmToken::EndOfStatement))
1698 if (getLexer().isNot(AsmToken::Comma))
1699 return TokError("unexpected token in directive");
1708 /// ParseDirectiveELFType
1709 /// ::= .type identifier , @attribute
1710 bool AsmParser::ParseDirectiveELFType() {
1712 if (ParseIdentifier(Name))
1713 return TokError("expected identifier in directive");
1715 // Handle the identifier as the key symbol.
1716 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1718 if (getLexer().isNot(AsmToken::Comma))
1719 return TokError("unexpected token in '.type' directive");
1722 if (getLexer().isNot(AsmToken::At))
1723 return TokError("expected '@' before type");
1729 TypeLoc = getLexer().getLoc();
1730 if (ParseIdentifier(Type))
1731 return TokError("expected symbol type in directive");
1733 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1734 .Case("function", MCSA_ELF_TypeFunction)
1735 .Case("object", MCSA_ELF_TypeObject)
1736 .Case("tls_object", MCSA_ELF_TypeTLS)
1737 .Case("common", MCSA_ELF_TypeCommon)
1738 .Case("notype", MCSA_ELF_TypeNoType)
1739 .Default(MCSA_Invalid);
1741 if (Attr == MCSA_Invalid)
1742 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1744 if (getLexer().isNot(AsmToken::EndOfStatement))
1745 return TokError("unexpected token in '.type' directive");
1749 getStreamer().EmitSymbolAttribute(Sym, Attr);
1754 /// ParseDirectiveComm
1755 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1756 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1757 CheckForValidSection();
1759 SMLoc IDLoc = getLexer().getLoc();
1761 if (ParseIdentifier(Name))
1762 return TokError("expected identifier in directive");
1764 // Handle the identifier as the key symbol.
1765 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1767 if (getLexer().isNot(AsmToken::Comma))
1768 return TokError("unexpected token in directive");
1772 SMLoc SizeLoc = getLexer().getLoc();
1773 if (ParseAbsoluteExpression(Size))
1776 int64_t Pow2Alignment = 0;
1777 SMLoc Pow2AlignmentLoc;
1778 if (getLexer().is(AsmToken::Comma)) {
1780 Pow2AlignmentLoc = getLexer().getLoc();
1781 if (ParseAbsoluteExpression(Pow2Alignment))
1784 // If this target takes alignments in bytes (not log) validate and convert.
1785 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1786 if (!isPowerOf2_64(Pow2Alignment))
1787 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1788 Pow2Alignment = Log2_64(Pow2Alignment);
1792 if (getLexer().isNot(AsmToken::EndOfStatement))
1793 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1797 // NOTE: a size of zero for a .comm should create a undefined symbol
1798 // but a size of .lcomm creates a bss symbol of size zero.
1800 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1801 "be less than zero");
1803 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1804 // may internally end up wanting an alignment in bytes.
1805 // FIXME: Diagnose overflow.
1806 if (Pow2Alignment < 0)
1807 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1808 "alignment, can't be less than zero");
1810 if (!Sym->isUndefined())
1811 return Error(IDLoc, "invalid symbol redefinition");
1813 // '.lcomm' is equivalent to '.zerofill'.
1814 // Create the Symbol as a common or local common with Size and Pow2Alignment
1816 getStreamer().EmitZerofill(Ctx.getMachOSection(
1817 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1818 0, SectionKind::getBSS()),
1819 Sym, Size, 1 << Pow2Alignment);
1823 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1827 /// ParseDirectiveAbort
1828 /// ::= .abort [... message ...]
1829 bool AsmParser::ParseDirectiveAbort() {
1830 // FIXME: Use loc from directive.
1831 SMLoc Loc = getLexer().getLoc();
1833 StringRef Str = ParseStringToEndOfStatement();
1834 if (getLexer().isNot(AsmToken::EndOfStatement))
1835 return TokError("unexpected token in '.abort' directive");
1840 Error(Loc, ".abort detected. Assembly stopping.");
1842 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1843 // FIXME: Actually abort assembly here.
1848 /// ParseDirectiveInclude
1849 /// ::= .include "filename"
1850 bool AsmParser::ParseDirectiveInclude() {
1851 if (getLexer().isNot(AsmToken::String))
1852 return TokError("expected string in '.include' directive");
1854 std::string Filename = getTok().getString();
1855 SMLoc IncludeLoc = getLexer().getLoc();
1858 if (getLexer().isNot(AsmToken::EndOfStatement))
1859 return TokError("unexpected token in '.include' directive");
1861 // Strip the quotes.
1862 Filename = Filename.substr(1, Filename.size()-2);
1864 // Attempt to switch the lexer to the included file before consuming the end
1865 // of statement to avoid losing it when we switch.
1866 if (EnterIncludeFile(Filename)) {
1867 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1874 /// ParseDirectiveIf
1875 /// ::= .if expression
1876 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1877 TheCondStack.push_back(TheCondState);
1878 TheCondState.TheCond = AsmCond::IfCond;
1879 if(TheCondState.Ignore) {
1880 EatToEndOfStatement();
1884 if (ParseAbsoluteExpression(ExprValue))
1887 if (getLexer().isNot(AsmToken::EndOfStatement))
1888 return TokError("unexpected token in '.if' directive");
1892 TheCondState.CondMet = ExprValue;
1893 TheCondState.Ignore = !TheCondState.CondMet;
1899 /// ParseDirectiveElseIf
1900 /// ::= .elseif expression
1901 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1902 if (TheCondState.TheCond != AsmCond::IfCond &&
1903 TheCondState.TheCond != AsmCond::ElseIfCond)
1904 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1906 TheCondState.TheCond = AsmCond::ElseIfCond;
1908 bool LastIgnoreState = false;
1909 if (!TheCondStack.empty())
1910 LastIgnoreState = TheCondStack.back().Ignore;
1911 if (LastIgnoreState || TheCondState.CondMet) {
1912 TheCondState.Ignore = true;
1913 EatToEndOfStatement();
1917 if (ParseAbsoluteExpression(ExprValue))
1920 if (getLexer().isNot(AsmToken::EndOfStatement))
1921 return TokError("unexpected token in '.elseif' directive");
1924 TheCondState.CondMet = ExprValue;
1925 TheCondState.Ignore = !TheCondState.CondMet;
1931 /// ParseDirectiveElse
1933 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1934 if (getLexer().isNot(AsmToken::EndOfStatement))
1935 return TokError("unexpected token in '.else' directive");
1939 if (TheCondState.TheCond != AsmCond::IfCond &&
1940 TheCondState.TheCond != AsmCond::ElseIfCond)
1941 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1943 TheCondState.TheCond = AsmCond::ElseCond;
1944 bool LastIgnoreState = false;
1945 if (!TheCondStack.empty())
1946 LastIgnoreState = TheCondStack.back().Ignore;
1947 if (LastIgnoreState || TheCondState.CondMet)
1948 TheCondState.Ignore = true;
1950 TheCondState.Ignore = false;
1955 /// ParseDirectiveEndIf
1957 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1958 if (getLexer().isNot(AsmToken::EndOfStatement))
1959 return TokError("unexpected token in '.endif' directive");
1963 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1964 TheCondStack.empty())
1965 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1967 if (!TheCondStack.empty()) {
1968 TheCondState = TheCondStack.back();
1969 TheCondStack.pop_back();
1975 /// ParseDirectiveFile
1976 /// ::= .file [number] string
1977 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1978 // FIXME: I'm not sure what this is.
1979 int64_t FileNumber = -1;
1980 SMLoc FileNumberLoc = getLexer().getLoc();
1981 if (getLexer().is(AsmToken::Integer)) {
1982 FileNumber = getTok().getIntVal();
1986 return TokError("file number less than one");
1989 if (getLexer().isNot(AsmToken::String))
1990 return TokError("unexpected token in '.file' directive");
1992 StringRef Filename = getTok().getString();
1993 Filename = Filename.substr(1, Filename.size()-2);
1996 if (getLexer().isNot(AsmToken::EndOfStatement))
1997 return TokError("unexpected token in '.file' directive");
1999 if (FileNumber == -1)
2000 getStreamer().EmitFileDirective(Filename);
2002 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
2003 Error(FileNumberLoc, "file number already allocated");
2004 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
2010 /// ParseDirectiveLine
2011 /// ::= .line [number]
2012 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2013 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2014 if (getLexer().isNot(AsmToken::Integer))
2015 return TokError("unexpected token in '.line' directive");
2017 int64_t LineNumber = getTok().getIntVal();
2021 // FIXME: Do something with the .line.
2024 if (getLexer().isNot(AsmToken::EndOfStatement))
2025 return TokError("unexpected token in '.line' directive");
2031 /// ParseDirectiveLoc
2032 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2033 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2034 /// The first number is a file number, must have been previously assigned with
2035 /// a .file directive, the second number is the line number and optionally the
2036 /// third number is a column position (zero if not specified). The remaining
2037 /// optional items are .loc sub-directives.
2038 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2040 if (getLexer().isNot(AsmToken::Integer))
2041 return TokError("unexpected token in '.loc' directive");
2042 int64_t FileNumber = getTok().getIntVal();
2044 return TokError("file number less than one in '.loc' directive");
2045 if (!getContext().ValidateDwarfFileNumber(FileNumber))
2046 return TokError("unassigned file number in '.loc' directive");
2049 int64_t LineNumber = 0;
2050 if (getLexer().is(AsmToken::Integer)) {
2051 LineNumber = getTok().getIntVal();
2053 return TokError("line number less than one in '.loc' directive");
2057 int64_t ColumnPos = 0;
2058 if (getLexer().is(AsmToken::Integer)) {
2059 ColumnPos = getTok().getIntVal();
2061 return TokError("column position less than zero in '.loc' directive");
2067 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2069 if (getLexer().is(AsmToken::EndOfStatement))
2073 SMLoc Loc = getTok().getLoc();
2074 if (getParser().ParseIdentifier(Name))
2075 return TokError("unexpected token in '.loc' directive");
2077 if (Name == "basic_block")
2078 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2079 else if (Name == "prologue_end")
2080 Flags |= DWARF2_FLAG_PROLOGUE_END;
2081 else if (Name == "epilogue_begin")
2082 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2083 else if (Name == "is_stmt") {
2084 SMLoc Loc = getTok().getLoc();
2085 const MCExpr *Value;
2086 if (getParser().ParseExpression(Value))
2088 // The expression must be the constant 0 or 1.
2089 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2090 int Value = MCE->getValue();
2092 Flags &= ~DWARF2_FLAG_IS_STMT;
2093 else if (Value == 1)
2094 Flags |= DWARF2_FLAG_IS_STMT;
2096 return Error(Loc, "is_stmt value not 0 or 1");
2099 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2102 else if (Name == "isa") {
2103 SMLoc Loc = getTok().getLoc();
2104 const MCExpr *Value;
2105 if (getParser().ParseExpression(Value))
2107 // The expression must be a constant greater or equal to 0.
2108 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2109 int Value = MCE->getValue();
2111 return Error(Loc, "isa number less than zero");
2115 return Error(Loc, "isa number not a constant value");
2119 return Error(Loc, "unknown sub-directive in '.loc' directive");
2122 if (getLexer().is(AsmToken::EndOfStatement))
2127 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
2132 /// ParseDirectiveMacrosOnOff
2135 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2136 SMLoc DirectiveLoc) {
2137 if (getLexer().isNot(AsmToken::EndOfStatement))
2138 return Error(getLexer().getLoc(),
2139 "unexpected token in '" + Directive + "' directive");
2141 getParser().MacrosEnabled = Directive == ".macros_on";
2146 /// ParseDirectiveMacro
2148 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2149 SMLoc DirectiveLoc) {
2151 if (getParser().ParseIdentifier(Name))
2152 return TokError("expected identifier in directive");
2154 if (getLexer().isNot(AsmToken::EndOfStatement))
2155 return TokError("unexpected token in '.macro' directive");
2157 // Eat the end of statement.
2160 AsmToken EndToken, StartToken = getTok();
2162 // Lex the macro definition.
2164 // Check whether we have reached the end of the file.
2165 if (getLexer().is(AsmToken::Eof))
2166 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2168 // Otherwise, check whether we have reach the .endmacro.
2169 if (getLexer().is(AsmToken::Identifier) &&
2170 (getTok().getIdentifier() == ".endm" ||
2171 getTok().getIdentifier() == ".endmacro")) {
2172 EndToken = getTok();
2174 if (getLexer().isNot(AsmToken::EndOfStatement))
2175 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2180 // Otherwise, scan til the end of the statement.
2181 getParser().EatToEndOfStatement();
2184 if (getParser().MacroMap.lookup(Name)) {
2185 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2188 const char *BodyStart = StartToken.getLoc().getPointer();
2189 const char *BodyEnd = EndToken.getLoc().getPointer();
2190 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2191 getParser().MacroMap[Name] = new Macro(Name, Body);
2195 /// ParseDirectiveEndMacro
2198 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2199 SMLoc DirectiveLoc) {
2200 if (getLexer().isNot(AsmToken::EndOfStatement))
2201 return TokError("unexpected token in '" + Directive + "' directive");
2203 // If we are inside a macro instantiation, terminate the current
2205 if (!getParser().ActiveMacros.empty()) {
2206 getParser().HandleMacroExit();
2210 // Otherwise, this .endmacro is a stray entry in the file; well formed
2211 // .endmacro directives are handled during the macro definition parsing.
2212 return TokError("unexpected '" + Directive + "' in file, "
2213 "no current macro definition");
2216 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2217 const uint64_t Mask = (1 << 7) - 1;
2219 unsigned Byte = Value & Mask;
2221 if (Value) // Not the last one
2223 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2227 void GenericAsmParser::ParseSleb128(int64_t Value) {
2228 const int64_t Mask = (1 << 7) - 1;
2230 unsigned Byte = Value & Mask;
2232 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2233 (Value == -1 && (Byte & 0x40) != 0));
2236 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2242 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2244 if (getParser().ParseAbsoluteExpression(Value))
2247 if (getLexer().isNot(AsmToken::EndOfStatement))
2248 return TokError("unexpected token in directive");
2250 if (DirName[1] == 's')
2251 ParseSleb128(Value);
2253 ParseUleb128(Value);
2258 /// \brief Create an MCAsmParser instance.
2259 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2260 MCContext &C, MCStreamer &Out,
2261 const MCAsmInfo &MAI) {
2262 return new AsmParser(T, SM, C, Out, MAI);